cosette/server/services/upload-service.ts

47 lines
1 KiB
TypeScript
Raw Normal View History

2022-08-18 09:44:51 +02:00
import multer from 'multer'
import type { Options } from 'multer'
import fs from 'fs'
import { v4 } from 'uuid'
import path from 'path'
2022-08-11 09:57:51 +02:00
export const uploadService = () => {
2022-08-22 17:18:45 +02:00
let folderPath = './public/'
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true })
}
const { limits: templateLimits }: Options = {
limits: {
2022-08-23 23:26:57 +02:00
files: 10,
2022-08-22 17:18:45 +02:00
fieldNameSize: 400,
fileSize: 800 * 1024 * 1024,
2022-08-22 17:18:45 +02:00
},
};
2022-08-11 09:57:51 +02:00
2022-08-22 17:18:45 +02:00
const { filename }: multer.DiskStorageOptions = {
2022-08-23 23:26:57 +02:00
filename: (_req, file, cb: Function) => {
2022-08-22 17:18:45 +02:00
const type = path.extname(file.originalname)
cb(null, v4() + type)
}
}
2022-08-11 09:57:51 +02:00
2022-08-22 17:18:45 +02:00
const generateHandler = () => {
try {
const options: Options = {
limits: {
...templateLimits,
},
storage: multer.diskStorage({
filename,
destination: folderPath
}),
};
2022-08-11 09:57:51 +02:00
return multer(options).array('images', 10);
2022-08-22 17:18:45 +02:00
} catch (e) {
console.error('Upload error', e)
throw e;
}
};
return { generateHandler };
2022-08-23 23:26:57 +02:00
};