Last active
July 28, 2019 21:24
-
-
Save Rowadz/f0dbb864ff9797dafa1ce58e5d582da7 to your computer and use it in GitHub Desktop.
a gist for https://medium.com/@mohammedalrowad/painless-file-upload-using-feathersjs-services-e994e4734e0c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createService = require('feathers-sequelize'); | |
const createModel = require('../../models/uploads.model'); | |
const hooks = require('./uploads.hooks'); | |
const multer = require('multer'); | |
const { | |
authenticate | |
} = require('@feathersjs/authentication').express; // getting feathers' authenticate middleware | |
const storage = multer.diskStorage({ | |
destination: (_req, _file, cb) => cb(null, 'public/uploads'), // where the files are being stored | |
filename: (_req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`) // getting the file name | |
}); | |
const upload = multer({ | |
storage, | |
limits: { | |
fieldSize: 1e+8, // Max field value size in bytes, here it's 100MB | |
fileSize: 1e+7 // The max file size in bytes, here it's 10MB | |
// files: the number of files | |
// READ MORE https://www.npmjs.com/package/multer#limits | |
} | |
}); | |
module.exports = function (app) { | |
const Model = createModel(app); | |
const paginate = app.get('paginate'); | |
const options = { | |
Model, | |
paginate, | |
multi: true // allowing us to store multiple instances of the model, in the same request | |
}; | |
app.use('/uploads', | |
authenticate('jwt'), | |
upload.array('files'), (req, _res, next) => { | |
const { method } = req; | |
if (method === 'POST' || method === 'PATCH') { | |
// I believe this middleware should only transfer | |
// files to feathers and call next(); | |
// and the mapping of data to the model shape | |
// should be in a hook. | |
// this code is only for this demo. | |
req.feathers.files = req.files; // transfer the received files to feathers | |
// for transforming the request to the model shape | |
const body = []; | |
for (const file of req.files) | |
body.push({ | |
description: req.body.description, | |
orignalName: file.originalname, | |
newNameWithPath: file.path, | |
userId: req.user.id | |
}); | |
req.body = method === 'POST' ? body : body[0]; | |
} | |
next(); | |
}, createService(options)); | |
const service = app.service('uploads'); | |
service.hooks(hooks); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment