@adonisjs/bodyparser
Version:
AdonisJs body parser to read and parse HTTP request bodies
61 lines (60 loc) • 1.97 kB
JavaScript
;
/*
* @adonisjs/bodyparser
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.computeFileTypeFromName = exports.getFileType = exports.supportMagicFileTypes = void 0;
/// <reference path="../adonis-typings/bodyparser.ts" />
const path_1 = require("path");
const file_type_1 = require("file-type");
const media_typer_1 = __importDefault(require("media-typer"));
/**
* We can detect file types for these files using the magic
* number
*/
exports.supportMagicFileTypes = file_type_1.extensions;
/**
* Attempts to parse the file mime type using the file magic number
*/
function parseMimeType(mime) {
try {
const { type, subtype } = media_typer_1.default.parse(mime);
return { type, subtype };
}
catch (error) {
return null;
}
}
/**
* Returns the file `type`, `subtype` and `extension`.
*/
async function getFileType(fileContents) {
/**
* Attempt to detect file type from it's content
*/
const magicType = await (0, file_type_1.fromBuffer)(fileContents);
if (magicType) {
return Object.assign({ ext: magicType.ext }, parseMimeType(magicType.mime));
}
return null;
}
exports.getFileType = getFileType;
/**
* Computes file name from the file type
*/
function computeFileTypeFromName(clientName, headers) {
/**
* Otherwise fallback to file extension from it's client name
* and pull type/subtype from the headers content type.
*/
return Object.assign({ ext: (0, path_1.extname)(clientName).replace(/^\./, '') }, parseMimeType(headers['content-type']));
}
exports.computeFileTypeFromName = computeFileTypeFromName;