All files / src/services file-upload.service.ts

50% Statements 7/14
0% Branches 0/3
0% Functions 0/3
41.67% Lines 5/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 351x 1x 1x 1x                   1x                                          
import multer from 'multer';
import { HttpErrors } from '@loopback/rest';
import { BindingScope, config, ContextTags, injectable, Provider, } from '@loopback/core';
import { FILE_UPLOAD_SERVICE, FileUploadHandler } from '@logchain/csv-parser';
 
 
/**
 * A provider to return an `Express` request handler from `multer` middleware
 */
@injectable({
  scope: BindingScope.TRANSIENT,
  tags: { [ContextTags.KEY]: FILE_UPLOAD_SERVICE },
})
export class FileUploadProvider implements Provider<FileUploadHandler> {
  constructor(@config() private options: multer.Options = {}) {
    this.options.storage = multer.memoryStorage();
    this.options.fileFilter = (req, file, cb) => {
      if (file.mimetype === "text/csv") {
        cb(null, true);
      } else {
        cb(new HttpErrors.BadRequest('Only .csv format allowed!'));
      }
    }
  }
 
  /**
   * The value method returns an Express request handler from multer middleware.
   * The handler will store the uploaded file in memory and allow only .csv files.
   * @returns Express request handler
   */
  value(): FileUploadHandler {
    return multer(this.options).any() as FileUploadHandler;
  }
}