Skip to content

Commit

Permalink
Add parse() static factory method
Browse files Browse the repository at this point in the history
  • Loading branch information
domenic committed Feb 4, 2018
1 parent d9a42ae commit 4ee0e0d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ This package's algorithms conform to those of the WHATWG [MIME Sniffing Standard

This package's main module's default export is a class, `MIMEType`. Its constructor takes a string which it will attempt to parse into a MIME type; if parsing fails, an `Error` will be thrown.

### The `parse()` static factory method

As an alternative to the constructor, you can use `MIMEType.parse(string)`. The only difference is that `parse()` will return `null` on failed parsing, whereas the constructor will throw. It thus makes the most sense to use the constructor in cases where unparseable MIME types would be exceptional, and use `parse()` when dealing with input from some unconstrained source.

### Properties

- `type`: the MIME type's [type](https://mimesniff.spec.whatwg.org/#mime-type-type), e.g. `"text"`
Expand Down
8 changes: 8 additions & 0 deletions lib/mime-type.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ module.exports = class MIMEType {
this._parameters = new MIMETypeParameters(result.parameters);
}

static parse(string) {
try {
return new this(string);
} catch (e) {
return null;
}
}

get essence() {
return `${this.type}/${this.subtype}`;
}
Expand Down
18 changes: 18 additions & 0 deletions test/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,24 @@ describe("Constructor behavior", () => {
});
});

describe("static parse() behavior", () => {
it("converts incoming arguments into strings", () => {
const arg = {
toString() {
return "text/HTML";
}
};
const mimeType = MIMEType.parse(arg);

expect(mimeType.toString()).toEqual("text/html");
});

it("returns null on unparseable MIME types", () => {
expect(MIMEType.parse("asdf")).toBe(null);
expect(MIMEType.parse("text/html™")).toBe(null);
});
});

describe("type manipulation", () => {
let mimeType;
beforeEach(() => {
Expand Down

0 comments on commit 4ee0e0d

Please sign in to comment.