UNPKG

2.56 kBJavaScriptView Raw
1'use strict';
2
3const {
4 isFunc,
5 debugLog,
6 moveFile,
7 promiseCallback,
8 checkAndMakeDir,
9 saveBufferToFile
10} = require('./utilities');
11
12/**
13 * Returns Local function that moves the file to a different location on the filesystem
14 * which takes two function arguments to make it compatible w/ Promise or Callback APIs
15 * @param {String} filePath - destination file path.
16 * @param {Object} options - file factory options.
17 * @param {Object} fileUploadOptions - middleware options.
18 * @returns {Function}
19 */
20const moveFromTemp = (filePath, options, fileUploadOptions) => (resolve, reject) => {
21 debugLog(fileUploadOptions, `Moving temporary file ${options.tempFilePath} to ${filePath}`);
22 moveFile(options.tempFilePath, filePath, promiseCallback(resolve, reject));
23};
24
25/**
26 * Returns Local function that moves the file from buffer to a different location on the filesystem
27 * which takes two function arguments to make it compatible w/ Promise or Callback APIs
28 * @param {String} filePath - destination file path.
29 * @param {Object} options - file factory options.
30 * @param {Object} fileUploadOptions - middleware options.
31 * @returns {Function}
32 */
33const moveFromBuffer = (filePath, options, fileUploadOptions) => (resolve, reject) => {
34 debugLog(fileUploadOptions, `Moving uploaded buffer to ${filePath}`);
35 saveBufferToFile(options.buffer, filePath, promiseCallback(resolve, reject));
36};
37
38module.exports = (options, fileUploadOptions = {}) => {
39 // see: https://github.com/richardgirges/express-fileupload/issues/14
40 // firefox uploads empty file in case of cache miss when f5ing page.
41 // resulting in unexpected behavior. if there is no file data, the file is invalid.
42 if (!fileUploadOptions.useTempFiles && !options.buffer.length) return;
43
44 // Create and return file object.
45 return {
46 name: options.name,
47 data: options.buffer,
48 size: options.size,
49 encoding: options.encoding,
50 tempFilePath: options.tempFilePath,
51 truncated: options.truncated,
52 mimetype: options.mimetype,
53 md5: options.hash,
54 mv: (filePath, callback) => {
55 // Define a propper move function.
56 const moveFunc = fileUploadOptions.useTempFiles
57 ? moveFromTemp(filePath, options, fileUploadOptions)
58 : moveFromBuffer(filePath, options, fileUploadOptions);
59 // Create a folder for a file.
60 checkAndMakeDir(fileUploadOptions, filePath);
61 // If callback is passed in, use the callback API, otherwise return a promise.
62 return isFunc(callback) ? moveFunc(callback) : new Promise(moveFunc);
63 }
64 };
65};