From: Justin Wind <justin.wind+git@gmail.com>
Date: Sat, 26 Aug 2023 18:45:15 +0000 (-0700)
Subject: minor refactor of extension to mime-type lookups
X-Git-Tag: v2.0.0^2~5
X-Git-Url: https://git.squeep.com/?a=commitdiff_plain;h=364087437981d41c2dfb1b20ff2260f1edc0920f;p=squeep-api-dingus

minor refactor of extension to mime-type lookups
---

diff --git a/lib/mime-helper.js b/lib/mime-helper.js
index 086dc6a..687d27b 100644
--- a/lib/mime-helper.js
+++ b/lib/mime-helper.js
@@ -4,15 +4,23 @@
 const mimeDb = require('mime-db');
 
 const defaultType = 'application/octet-stream';
+
+/**
+ * Expects mime-db source data as object:
+ *   mime-type:
+ *     source: <String>
+ *     charset: <String>
+ *     compressible: <Boolean>
+ *     extensions: <String[]>
+ * Populate `extension` as an index from extensions to mime-types.
+ */
 const extension = {};
 for (const [mimeType, entry] of Object.entries(mimeDb)) {
-  if (entry.extensions) {
-    entry.extensions.forEach((ext) => {
-      if (!(ext in extension)) {
-        extension[ext] = [];
-      }
-      extension[ext].push(mimeType);
-    });
+  for (const ext of entry?.extensions || []) {
+    if (!(ext in extension)) {
+      extension[ext] = [];
+    }
+    extension[ext].push(mimeType);
   }
 }
 
@@ -20,8 +28,9 @@ for (const [mimeType, entry] of Object.entries(mimeDb)) {
  * Return a suitable type for a file extension.
  * @param {string} ext file extension
  * @param {string} def type to return if no match
+ * @returns {string}
  */
-const extensionToMime = (ext, def = defaultType) => extension[ext] && extension[ext][extension[ext].length - 1] || def;
+const extensionToMime = (ext, def = defaultType) => extension?.[ext]?.[0] || def;
 
 module.exports = {
   extensionToMime,