diff --git a/api/src/app.ts b/api/src/app.ts index 88e4475..8d7b0f4 100644 --- a/api/src/app.ts +++ b/api/src/app.ts @@ -1,5 +1,5 @@ import path from 'path' -import express from 'express' +import express, { ErrorRequestHandler } from 'express' import morgan from 'morgan' import dotenv from 'dotenv' import cors from 'cors' @@ -26,12 +26,19 @@ app.use(morgan('tiny')) app.use(express.static(path.join(__dirname, '../public'))) app.use(express.static(getWebBuildFolderPath())) +const onError: ErrorRequestHandler = (err, req, res, next) => { + console.error(err.stack) + res.status(500).send('Something broke!') +} + export default setProcessVariables().then(async () => { // loading these modules after setting up variables due to // multer's usage of process var process.driveLoc const { setupRoutes } = await import('./routes/setupRoutes') setupRoutes(app) + app.use(onError) + await connectDB() return app }) diff --git a/api/src/controllers/drive.ts b/api/src/controllers/drive.ts index 84d2fd2..bab541b 100644 --- a/api/src/controllers/drive.ts +++ b/api/src/controllers/drive.ts @@ -214,18 +214,15 @@ const saveFile = async ( .replace(new RegExp('/', 'g'), path.sep) if (!filePathFull.includes(driveFilesPath)) { - await deleteFile(multerFile.path) throw new Error('Cannot put file outside drive.') } if (await fileExists(filePathFull)) { - await deleteFile(multerFile.path) throw new Error('File already exists.') } const folderPath = path.dirname(filePathFull) await createFolder(folderPath) - await moveFile(multerFile.path, filePathFull) return { status: 'success' } diff --git a/api/src/routes/api/drive.ts b/api/src/routes/api/drive.ts index fabae4f..fb4bc7c 100644 --- a/api/src/routes/api/drive.ts +++ b/api/src/routes/api/drive.ts @@ -1,5 +1,7 @@ import express from 'express' -import multer, { multerSingle } from '../../middlewares/multer' +import { deleteFile } from '@sasjs/utils' + +import { multerSingle } from '../../middlewares/multer' import { DriveController } from '../../controllers/' import { getFileDriveValidation, updateFileDriveValidation } from '../../utils' @@ -41,7 +43,10 @@ driveRouter.post( (...arg) => multerSingle('file', arg), async (req, res) => { const { error, value: body } = updateFileDriveValidation(req.body) - if (error) return res.status(400).send(error.details[0].message) + if (error) { + if (req.file) await deleteFile(req.file.path) + return res.status(400).send(error.details[0].message) + } if (!req.file) return res.status(400).send('"file" is not present.') @@ -49,6 +54,7 @@ driveRouter.post( const response = await controller.saveFile(body.filePath, req.file) res.send(response) } catch (err: any) { + await deleteFile(req.file.path) res.status(403).send(err.toString()) } }