UNPKG

@uploadx/core

Version:
76 lines (75 loc) 2.78 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Multipart = void 0; exports.multipart = multipart; const multiparty_1 = __importDefault(require("multiparty")); const utils_1 = require("../utils"); const base_handler_1 = require("./base-handler"); class Multipart extends base_handler_1.BaseHandler { async post(req, res) { return new Promise((resolve, reject) => { const form = new multiparty_1.default.Form(); const config = { metadata: {} }; form.on('field', (key, value) => { Object.assign(config.metadata, key === 'metadata' ? JSON.parse(value) : { [key]: value }); }); form.on('error', error => reject(error)); form.on('part', (part) => { config.size = part.byteCount; config.originalName = part.filename; config.contentType = part.headers['content-type']; config.userId = this.getUserId(req, res); part.on('error', _ => null); this.storage .create(req, config) .then(({ id }) => this.storage.write({ start: 0, contentLength: part.byteCount, body: part, id })) .then(file => { if (file.status === 'completed') { const headers = { Location: this.buildFileUrl(req, file) }; (0, utils_1.setHeaders)(res, headers); } return resolve(file); }) .catch(err => reject(err)); }); form.parse(req); }); } /** * Delete upload */ async delete(req, res) { const id = await this.getAndVerifyId(req, res); const [file] = await this.storage.delete({ id }); this.send(res, { statusCode: 204 }); return file; } } exports.Multipart = Multipart; /** * Basic express wrapper * @example * ```ts * app.use('/files', multipart({directory: '/tmp', maxUploadSize: '250GB'})); * ``` */ function multipart(options = {}) { return new Multipart(options).handle; } /** * Express wrapper * * - express ***should*** respond to the client when the upload complete and handle errors and GET requests * @example * ```ts * app.use('/files', multipart.upload({ storage }), (req, res, next) => { * if (req.method === 'GET') return res.sendStatus(404); * console.log('File upload complete: ', req.body.name); * return res.sendStatus(200); * }); * ``` */ multipart.upload = (options = {}) => new Multipart(options).upload;