upload/middleware/UploadFile.js

/**
 * @module flitter-upload/middleware/UploadFile
 */

const Middleware = require('libflitter/middleware/Middleware')

/**
 * Middleware that uploads the files provided in the request
 * to the default backend store and places references to the
 * instantiated {@link module:flitter-upload/model/File~File}
 * records in "request.uploads".
 * @extends module:libflitter/middleware/Middleware~Middleware
 */
class UploadFile extends Middleware {
    /**
     * Defines the services required by this middleware.
     * @returns {Array<string>}
     */
    static get services() {
        return [...super.services, 'upload', 'models']
    }

    /**
     * Executes the middleware. For any files that exist in the request,
     * they will be stored in the {@link module:flitter-upload/store/Store~Store}
     * that is configured as the default.
     *
     * This creates instances of {@link module:flitter-upload/model/File~File} and
     * places them in req.uploads in an object mapping the upload field name to the
     * File model instance.
     *
     * @param {express/request} req - the request
     * @param {express/response} res - the response
     * @param {function} next - the next function in the chain
     * @param {object} [args = {}] - optional arguments
     * @returns {Promise<void>}
     */
    async test(req, res, next, { tag = '' }){
        const uploader = this.upload.provider()
        const uploads = {}

        if ( req.files ) {
            for ( const field_name in req.files ) {
                if ( !req.files.hasOwnProperty(field_name) ) continue
                const file = req.files[field_name]
                uploads[field_name] = await uploader.store({
                    temp_path: file.file,
                    original_name: file.filename,
                    mime_type: file.mimetype,
                    tag,
                })
            }
        }

        req.uploads = uploads
        next()
    }
}

module.exports = exports = UploadFile