UNPKG

@remix-run/headers

Version:

A toolkit for working with HTTP headers in JavaScript

59 lines (58 loc) 1.78 kB
import {} from "./header-value.js"; import { parseParams, quote } from "./param-values.js"; /** * The value of a `Content-Type` HTTP header. * * [MDN `Content-Type` Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) * * [HTTP/1.1 Specification](https://datatracker.ietf.org/doc/html/rfc7231#section-3.1.1.5) */ export class ContentType { boundary; charset; mediaType; /** * @param init A string or object to initialize the header */ constructor(init) { if (init) { if (typeof init === 'string') { let params = parseParams(init); if (params.length > 0) { this.mediaType = params[0][0]; for (let [name, value] of params.slice(1)) { if (name === 'boundary') { this.boundary = value; } else if (name === 'charset') { this.charset = value; } } } } else { this.boundary = init.boundary; this.charset = init.charset; this.mediaType = init.mediaType; } } } /** * Returns the string representation of the header value. * * @return The header value as a string */ toString() { if (!this.mediaType) { return ''; } let parts = [this.mediaType]; if (this.charset) { parts.push(`charset=${quote(this.charset)}`); } if (this.boundary) { parts.push(`boundary=${quote(this.boundary)}`); } return parts.join('; '); } }