UNPKG

1.97 kBJavaScriptView Raw
1"use strict";
2/*
3 * @adonisjs/bodyparser
4 *
5 * (c) Harminder Virk <virk@adonisjs.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10var __importDefault = (this && this.__importDefault) || function (mod) {
11 return (mod && mod.__esModule) ? mod : { "default": mod };
12};
13Object.defineProperty(exports, "__esModule", { value: true });
14exports.computeFileTypeFromName = exports.getFileType = exports.supportMagicFileTypes = void 0;
15/// <reference path="../adonis-typings/bodyparser.ts" />
16const path_1 = require("path");
17const file_type_1 = require("file-type");
18const media_typer_1 = __importDefault(require("media-typer"));
19/**
20 * We can detect file types for these files using the magic
21 * number
22 */
23exports.supportMagicFileTypes = file_type_1.extensions;
24/**
25 * Attempts to parse the file mime type using the file magic number
26 */
27function parseMimeType(mime) {
28 try {
29 const { type, subtype } = media_typer_1.default.parse(mime);
30 return { type, subtype };
31 }
32 catch (error) {
33 return null;
34 }
35}
36/**
37 * Returns the file `type`, `subtype` and `extension`.
38 */
39async function getFileType(fileContents) {
40 /**
41 * Attempt to detect file type from it's content
42 */
43 const magicType = await (0, file_type_1.fromBuffer)(fileContents);
44 if (magicType) {
45 return Object.assign({ ext: magicType.ext }, parseMimeType(magicType.mime));
46 }
47 return null;
48}
49exports.getFileType = getFileType;
50/**
51 * Computes file name from the file type
52 */
53function computeFileTypeFromName(clientName, headers) {
54 /**
55 * Otherwise fallback to file extension from it's client name
56 * and pull type/subtype from the headers content type.
57 */
58 return Object.assign({ ext: (0, path_1.extname)(clientName).replace(/^\./, '') }, parseMimeType(headers['content-type']));
59}
60exports.computeFileTypeFromName = computeFileTypeFromName;