Skip to content

Commit

Permalink
feat(mime): add preferredType()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Feb 24, 2020
1 parent 3cddc82 commit 942aa84
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
38 changes: 37 additions & 1 deletion packages/mime/README.tpl.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ This project is part of the

${pkg.description}

All MIME type mappings based on
[mime-db](https://github.com/jshttp/mime-db).

${status}

${supportPackages}
Expand All @@ -39,7 +42,40 @@ ${examples}

${docLink}

TODO
This package exposes a `MIME_TYPES` object which provides
mappings from file extensions to MIME types. For each extension one or
more MIME types are provided, with the default type always in first
position.

```ts
import { MIME_TYPES } from "@thi.ng/mime";

MIME_TYPES.mp3
// [ 'audio/mpeg', 'audio/mp3' ]

MIME_TYPES.jpg
// [ 'image/jpeg' ]

MIME_TYPES.jpeg
// [ 'image/jpeg' ]
```

To simplify lookup and support a fallback type, the package also has `preferredType()` function:

```ts
import { preferredType } from "@thi.ng/mime";

preferredType("mp3")
// "audio/mpeg"

// unknown file extension w/ default fallback type
preferredType("foo")
// "application/octet-stream"

// unknown file extension w/ given fallback type
preferredType("foo", "text/plain")
// "text/plain"
```

## Authors

Expand Down
2 changes: 1 addition & 1 deletion packages/mime/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@thi.ng/mime",
"version": "0.0.1",
"description": "350+ file extension to MIME type mappings",
"description": "350+ file extension to MIME type mappings, based on mime-db",
"module": "./index.js",
"main": "./lib/index.js",
"umd:main": "./lib/index.umd.js",
Expand Down
13 changes: 13 additions & 0 deletions packages/mime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,3 +289,16 @@ export const MIME_TYPES = ((defs: any) => {
"x-msvideo": "avi"
}
});

/**
* Returns preferred MIME type for given file extension or, if no match
* is available, the `fallback` MIME type (default:
* `application/octet-stream`).
*
* @param ext
* @param fallback
*/
export const preferredType = (ext: string, fallback = MIME_TYPES.bin[0]) => {
const type = MIME_TYPES[ext];
return type ? type[0] : fallback;
};

0 comments on commit 942aa84

Please sign in to comment.