Home Reference Source

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.
 */
class RollupSendFile {
  /**
   * Class constructor.
   * @param {RollupFrontendFs} frontendFs To be able to read the file the Rollup output directory.
   */
  constructor(frontendFs) {
    /**
     * A local reference for the `frontendFs` service.
     * @type {RollupFrontendFs}
     */
    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
 * `RollupSendFile.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 rollupSendFile = provider((app) => {
  app.set('sendFile', () => new RollupSendFile(
    app.get('frontendFs')
  ).sendFile);
});

module.exports = {
  RollupSendFile,
  rollupSendFile,
};