UNPKG

@nestjs/platform-fastify

Version:

Nest - modern, fast, powerful node.js web framework (@platform-fastify)

59 lines (58 loc) • 2.23 kB
import { randomBytes } from 'crypto'; import { createWriteStream, mkdirSync } from 'fs'; import { unlink } from 'fs/promises'; import { tmpdir } from 'os'; import { join } from 'path'; import { pipeline } from 'stream/promises'; function resolveName(resolver, req, file) { return new Promise((resolve, reject) => resolver(req, file, (err, value) => (err ? reject(err) : resolve(value)))); } /** * Writes each file to disk, with multer's `diskStorage` defaults and file * shape (`destination`, `filename`, `path`, `size`). * * @publicApi */ export function diskStorage(options = {}) { let resolveDestination; if (typeof options.destination === 'string') { const destination = options.destination; mkdirSync(destination, { recursive: true }); resolveDestination = (_req, _file, callback) => callback(null, destination); } else { resolveDestination = options.destination ?? ((_req, _file, callback) => callback(null, tmpdir())); } const resolveFilename = options.filename ?? ((_req, _file, callback) => callback(null, randomBytes(16).toString('hex'))); const store = async (req, file) => { const destination = await resolveName(resolveDestination, req, file); const filename = await resolveName(resolveFilename, req, file); const path = join(destination, filename); // As in multer, `path` is known to the file before it is written. file.path = path; const out = createWriteStream(path); try { await pipeline(file.stream, out); } catch (err) { await unlink(path).catch(() => undefined); throw err; } return { destination, filename, path, size: out.bytesWritten }; }; return { _handleFile(req, file, callback) { store(req, file).then(info => callback(null, info), err => callback(err)); }, _removeFile(_req, file, callback) { const path = file.path; delete file.destination; delete file.filename; delete file.path; unlink(path).then(() => callback(null), err => callback(err)); }, }; }