Skip to content

Commit

Permalink
update default headers for send
Browse files Browse the repository at this point in the history
  • Loading branch information
ynwd committed Aug 18, 2024
1 parent 53233c8 commit 31c72c1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
19 changes: 13 additions & 6 deletions http/server/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,22 @@ const parseBody = (req: Request) => {
};
};

const createResponse = (res: any, status = 200): Response => {
if (typeof res === "string") return new Response(res, { status });
const createResponse = (
res: any,
status = 200,
headers?: Headers,
): Response => {
const h = headers ? headers : new Headers({
"Content-Type": "application/json",
});
if (typeof res === "string") return new Response(res, { status, headers: h });
if (res instanceof Response) return res;
if (
typeof res === "number" || typeof res === "bigint" ||
typeof res === "boolean" || typeof res === "undefined"
) return new Response(JSON.stringify(res), { status });
) return new Response(JSON.stringify(res), { status, headers: h });
try {
return Response.json(res, { status });
return Response.json(res, { status, headers: h });
} catch (error) {
throw error;
}
Expand Down Expand Up @@ -392,8 +399,8 @@ if (root) fetchProps(root);
ctx.next = () => {};
ctx.url = new URL(req.url);
ctx.server = this;
ctx.send = <T>(data: T, status = 200) => {
return createResponse(data, status);
ctx.send = <T>(data: T, status = 200, headers?: Headers) => {
return createResponse(data, status, headers);
};
ctx.kv = this.serverOptions["kv"];
ctx.options = this.serverOptions;
Expand Down
1 change: 1 addition & 0 deletions http/server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export class Context {
send!: <T>(
data?: T | undefined,
status?: number | undefined,
headers?: Headers,
) => Response | Promise<Response>;
/**
* Middleware callback
Expand Down

0 comments on commit 31c72c1

Please sign in to comment.