* ContentType parses and represents the value of the content-type header. * * @see https://httpwg.org/specs/rfc9110.html#media.type * @see https://httpwg.org/specs/rfc9110.html#parameter
| 50 | * @see https://httpwg.org/specs/rfc9110.html#parameter |
| 51 | */ |
| 52 | class ContentType { |
| 53 | #valid = false |
| 54 | #empty = true |
| 55 | #type = '' |
| 56 | #subtype = '' |
| 57 | #parameters = new Map() |
| 58 | #string |
| 59 | |
| 60 | /** |
| 61 | * The shared cache of ContentType instances. The cache is used to avoid |
| 62 | * creating multiple instances of ContentType for the same header value. |
| 63 | * @type {Lru<ContentType>} |
| 64 | */ |
| 65 | static get cache () { return cache } |
| 66 | |
| 67 | /** |
| 68 | * Create a ContentType instance from a header value. If the value has been |
| 69 | * previously parsed, the cached instance will be returned. |
| 70 | * @param {string} headerValue |
| 71 | * @returns {ContentType | undefined} |
| 72 | */ |
| 73 | static from (headerValue) { |
| 74 | let contentType = cache.get(headerValue) |
| 75 | if (contentType !== undefined) return contentType |
| 76 | contentType = new ContentType(headerValue) |
| 77 | cache.set(headerValue, contentType) |
| 78 | return contentType |
| 79 | } |
| 80 | |
| 81 | constructor (headerValue) { |
| 82 | if (headerValue == null || headerValue === '' || headerValue === 'undefined') { |
| 83 | return |
| 84 | } |
| 85 | |
| 86 | let sepIdx = headerValue.indexOf(';') |
| 87 | if (sepIdx === -1) { |
| 88 | // The value is the simplest `type/subtype` variant. |
| 89 | sepIdx = headerValue.indexOf('/') |
| 90 | if (sepIdx === -1) { |
| 91 | // Got a string without the correct `type/subtype` format. |
| 92 | return |
| 93 | } |
| 94 | |
| 95 | const type = headerValue.slice(0, sepIdx).trimStart().toLowerCase() |
| 96 | const subtype = headerValue.slice(sepIdx + 1).trimEnd().toLowerCase() |
| 97 | |
| 98 | if ( |
| 99 | typeNameReg.test(type) === true && |
| 100 | subtypeNameReg.test(subtype) === true |
| 101 | ) { |
| 102 | this.#valid = true |
| 103 | this.#empty = false |
| 104 | this.#type = type |
| 105 | this.#subtype = subtype |
| 106 | } |
| 107 | |
| 108 | return |
| 109 | } |
nothing calls this directly
no outgoing calls
no test coverage detected