node.jsmulter-gridfs-storage

How to move middleware to Service Layer


I am trying to move the middleware function to Service Layer but run with errors. I am not sure even whether I am following the right layering.

Error:

** Route.post() requires a callback function but got a [object Object]**

file.service.ts

require('rootpath')()
const db = require('helpers/db.ts')
const mongoose = require('mongoose')
const multer = require('multer')
const GridFsStorage = require('multer-gridfs-storage')
const Grid = require('gridfs-stream')
const myCrypto = require('crypto')
const path = require('path')



var gfs = Grid(mongoose.connection, mongoose.mongo);  
gfs.collection('uploads');


var storage = new GridFsStorage({
    //url: mongoose.connection.client.s.url,
    //options: options,
    db: mongoose.connection,
    file: (req, file) => {
      return new Promise((resolve, reject) => {
        myCrypto.randomBytes(16, (err, buf) => {
          if (err) {
            return reject(err);
          }
          const filename = buf.toString('hex') + path.extname(file.originalname);
          const fileInfo = {
            filename: filename,
            bucketName: 'uploads'
          };
          resolve(fileInfo);
        });
      });
    }
  });
  const upload = multer({ storage });

  module.exports = {
      upload
  }

file.controller.ts

require('rootpath')()
const express = require('express')
const router = express.Router()
const fileService = require('routes/_shared/file.service.ts')

var logger = function(req, res, next)
{
    console.log("File Controller");

    next();
}

  router.use(logger);
  router.post('/upload', fileService.upload, fileUpload);

  module.exports = router;

function fileUpload(req, res) {

    res.send({ file: req.file })
}

Solution

  • Please check multer usage documentation carefully.

    You're passing fileService.upload as a second argument to router.post method and fileService.upload is an object and not a function (which the error message points).

    Instead, you should pass fileService.upload.single('avatar') or use other upload methods like array, fields, any, none.