Files
ontime/server/src/utils/upload.js
T
Carlos Valente 8c740b7111 Feat/excel (#45)
* add dependency

adding dependency to parse the excel file in the node side

* import file

ability to import file
- add extension
- safeguard file type and size

* user is able to upload json or excel

* chore: extract logic into self contained function

* associate model with version

* test id generation

* parse excel data

* prevent UI crash on bad data

* extract validation into self contained function

* chore: add more tests for bad data

* config: stop from opening browser on start

* fix comma in sample db

* handle corrupt files

* error boundary around main components

* jsdocs

* increase id length

* parse excel time string

* feat: excel parsing

* validate json db before import

* chore: test event validator

* feat: make function to clean convert strings

* chore: test parser

* chore: jsdocs

* fix: bug on upload

prevent bug where the component would prevent upload of same file twice
2021-11-24 22:07:31 +01:00

46 lines
1.2 KiB
JavaScript

import multer from 'multer';
import { statSync, mkdirSync } from 'fs';
import { EXCEL_MIME, JSON_MIME } from './parser.js';
// Define multer storage object
const storage = multer.diskStorage({
destination: function (req, file, cb) {
let newDestination = 'uploads/';
let stat = null;
try {
stat = statSync(newDestination);
} catch (err) {
mkdirSync(newDestination);
}
if (stat && !stat.isDirectory()) {
throw new Error(
`Directory cannot be created because an inode of a different type exists at ${newDestination}`
);
}
cb(null, newDestination);
},
filename: function (req, file, cb) {
cb(null, Date.now() + '--' + file.originalname);
},
});
/**
* @description Middleware function to filter allowed file types
* @argument file - reference to file
* @return {boolean} - file allowed
*/
const filterAllowed = (req, file, cb) => {
if (file.mimetype.includes(JSON_MIME) || file.mimetype.includes(EXCEL_MIME)) {
cb(null, true);
} else {
console.log('ERROR: Unrecognised file type');
cb(null, false);
}
};
// Build multer uploader for a single file
export const uploadFile = multer({
storage: storage,
fileFilter: filterAllowed,
}).single('userFile');