src/jimpex/sendFile.js
const { provider } = require('jimple');
/**
* This service overwrites the `Jimpex` default `sendFile` so it will use the `frontendFs` service
* to reads the file contents, thus using the virtual file system from the Webpack middleware.
*/
class WebpackSendFile {
/**
* Class constructor.
* @param {WebpackFrontendFs} frontendFs To be able to read the file from the middleware file
* system.
*/
constructor(frontendFs) {
/**
* A local reference for the `frontendFs` service.
* @type {WebpackFrontendFs}
*/
this.frontendFs = frontendFs;
/**
* Bind the `sendFile` method to use it as the service main function.
* @ignore
*/
this.sendFile = this.sendFile.bind(this);
}
/**
* Send a file on the Jimpex response.
* @param {Reponse} res The response object generated by Express.
* @param {string} filepath The path to the file that needs to be sent.
* @param {function} [next=()=>{}] If anything goes wrong, this function will be called with the
* exception.
*/
sendFile(res, filepath, next = () => {}) {
this.frontendFs.read(filepath)
.then((contents) => {
res.write(contents);
res.end();
})
.catch((error) => {
next(error);
});
}
}
/**
* The service provider that once registered on the app container will set
* `WebpackSendFile.sendFile` as the `sendFile` service.
* @example
* // Register it on the container
* container.register(sendFile);
* // Getting access to the service instance
* const sendFile = container.get('sendFile');
* @type {Provider}
*/
const webpackSendFile = provider((app) => {
app.set('sendFile', () => new WebpackSendFile(
app.get('frontendFs')
).sendFile);
});
module.exports = {
WebpackSendFile,
webpackSendFile,
};