UNPKG

@marblejs/middleware-multipart

Version:

A multipart/form-data middleware for Marble.js

15 lines (14 loc) 2.31 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseFile = void 0; const http_1 = require("@marblejs/http"); const utils_1 = require("@marblejs/core/dist/+internal/utils"); const observable_1 = require("@marblejs/core/dist/+internal/observable"); const rxjs_1 = require("rxjs"); const operators_1 = require("rxjs/operators"); const multipart_util_1 = require("./multipart.util"); const fileSizeLimit = (maxBytes) => (data) => (finish$) => (0, rxjs_1.fromEvent)(data.file, 'limit').pipe((0, operators_1.takeUntil)(finish$), (0, operators_1.mergeMap)(() => (0, rxjs_1.throwError)(() => new http_1.HttpError(`Reached file size limit for "${data.fieldname}" [${maxBytes} bytes]`, http_1.HttpStatus.PRECONDITION_FAILED))), (0, operators_1.ignoreElements)()); const parseFile = (req) => (opts) => (event$, finish$) => event$.pipe((0, operators_1.takeUntil)(finish$), (0, operators_1.map)(([fieldname, file, filename, encoding, mimetype]) => ({ fieldname, file, filename, encoding, mimetype })), (0, operators_1.mergeMap)(data => (0, rxjs_1.iif)(() => !(0, multipart_util_1.shouldParseFieldname)(opts.files)(data.fieldname), (0, rxjs_1.throwError)(() => new http_1.HttpError(`File "${data.fieldname}" is not acceptable`, http_1.HttpStatus.PRECONDITION_FAILED)), (0, rxjs_1.of)(data))), (0, operators_1.mergeMap)(data => (0, rxjs_1.merge)(fileSizeLimit(opts.maxFileSize)(data)(finish$), (0, rxjs_1.of)(data))), (0, operators_1.mergeMap)(data => (0, utils_1.isNonNullable)(opts.stream) ? (0, rxjs_1.of)(data).pipe((0, operators_1.mergeMap)(opts.stream), (0, operators_1.tap)((0, multipart_util_1.setRequestData)(req)(data)), (0, operators_1.tap)(() => data.file.resume()), (0, operators_1.map)(() => data)) : (0, rxjs_1.of)(data).pipe((0, operators_1.map)(data => data.file), (0, operators_1.mergeMap)(observable_1.fromReadableStream), (0, operators_1.toArray)(), (0, operators_1.map)(chunks => ({ buffer: Buffer.concat(chunks) })), (0, operators_1.map)(({ buffer }) => ({ buffer, size: Buffer.byteLength(buffer) })), (0, operators_1.tap)((0, multipart_util_1.setRequestData)(req)(data)), (0, operators_1.tap)(() => data.file.resume()), (0, operators_1.map)(() => data))), (0, operators_1.map)(() => req), (0, operators_1.defaultIfEmpty)(req)); exports.parseFile = parseFile;