Skip to content

Commit

Permalink
Fix content type on enhanced responses
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonmade committed Oct 16, 2024
1 parent 1f96df4 commit d7cad39
Showing 1 changed file with 29 additions and 17 deletions.
46 changes: 29 additions & 17 deletions packages/request-router/source/response-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,36 +35,48 @@ export class RedirectResponse extends EnhancedResponse {
}

const CONTENT_TYPE_HEADER = 'Content-Type';
const CONTENT_TYPE_DEFAULT_VALUE = 'text/html; charset=utf-8';
const CONTENT_TYPE_OPTIONS_HEADER = 'X-Content-Type-Options';
const CONTENT_TYPE_OPTIONS_DEFAULT_VALUE = 'nosniff';

const CONTENT_TYPE_DEFAULT_VALUE_HTML = 'text/html; charset=utf-8';
const CONTENT_TYPE_OPTIONS_DEFAULT_VALUE_HTML = 'nosniff';

export class HTMLResponse extends EnhancedResponse {
constructor(body: BodyInit, options?: ResponseInit) {
super(body, options);

const {headers} = this;

if (!headers.has(CONTENT_TYPE_HEADER)) {
headers.set(CONTENT_TYPE_HEADER, CONTENT_TYPE_DEFAULT_VALUE);
}
const headers = updateHeaders(options?.headers, {
[CONTENT_TYPE_HEADER]: CONTENT_TYPE_DEFAULT_VALUE_HTML,
[CONTENT_TYPE_OPTIONS_HEADER]: CONTENT_TYPE_OPTIONS_DEFAULT_VALUE_HTML,
});

if (!headers.has(CONTENT_TYPE_OPTIONS_HEADER)) {
headers.set(
CONTENT_TYPE_OPTIONS_HEADER,
CONTENT_TYPE_OPTIONS_DEFAULT_VALUE,
);
}
super(body, {...options, headers});
}
}

export {HTMLResponse as HtmlResponse};

export class JsonResponse extends EnhancedResponse {
constructor(body: unknown, options?: ResponseInit) {
super(JSON.stringify(body), options);
this.headers.set('Content-Type', 'application/json; charset=utf-8');
const headers = updateHeaders(options?.headers, {
[CONTENT_TYPE_HEADER]: 'application/json; charset=utf-8',
});

super(JSON.stringify(body), {
...options,
headers,
});
}
}

export {JsonResponse as JSONResponse};

function updateHeaders(
headersInit: HeadersInit | undefined,
updateHeaders: Record<string, string>,
) {
const headers = new Headers(headersInit);

for (const [key, value] of Object.entries(updateHeaders)) {
if (!headers.has(key)) headers.set(key, value);
}

return headers;
}

0 comments on commit d7cad39

Please sign in to comment.