move fileScope to separate module, update dependencies and devDependencies
[squeep-api-dingus] / lib / mime-helper.js
1 /* eslint-disable security/detect-object-injection */
2 'use strict';
3
4 const mimeDb = require('mime-db');
5
6 const defaultType = 'application/octet-stream';
7
8 /**
9 * Expects mime-db source data as object:
10 * mime-type:
11 * source: <String>
12 * charset: <String>
13 * compressible: <Boolean>
14 * extensions: <String[]>
15 * Populate `extension` as an index from extensions to mime-types.
16 */
17 const extension = {};
18 for (const [mimeType, entry] of Object.entries(mimeDb)) {
19 for (const ext of entry?.extensions || []) {
20 if (!(ext in extension)) {
21 extension[ext] = [];
22 }
23 extension[ext].push(mimeType);
24 }
25 }
26
27 /**
28 * Return a suitable type for a file extension.
29 * @param {string} ext file extension
30 * @param {string} def type to return if no match
31 * @returns {string}
32 */
33 const extensionToMime = (ext, def = defaultType) => extension?.[ext]?.[0] || def;
34
35 module.exports = {
36 extensionToMime,
37 };