Skip to content

Commit

Permalink
fix(use/fastify): Include middleware headers
Browse files Browse the repository at this point in the history
Closes #91
  • Loading branch information
enisdenjo committed Mar 27, 2024
1 parent 1392852 commit 134c1b0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/use/fastify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ export function createHandler<Context extends OperationContext = undefined>(
url: req.url,
headers: {
get(key) {
const header = req.headers[key];
return Array.isArray(header) ? header.join('\n') : header;
const header = reply.getHeader(key) ?? req.headers[key];
return Array.isArray(header) ? header.join('\n') : String(header);
},
},
body: () =>
Expand All @@ -87,7 +87,16 @@ export function createHandler<Context extends OperationContext = undefined>(
context: { reply },
});

reply.raw.writeHead(init.status, init.statusText, init.headers);
const middlewareHeaders: Record<string, string> = {};
for (const [key, val] of Object.entries(reply.getHeaders())) {
middlewareHeaders[key] = Array.isArray(val)
? val.join('\n')
: String(val);
}
reply.raw.writeHead(init.status, init.statusText, {
...middlewareHeaders,
...init.headers,
});

if (!body || typeof body === 'string') {
return new Promise<void>((resolve) =>
Expand Down
35 changes: 35 additions & 0 deletions tests/use.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,38 @@ data: {"data":{"ping":"pong"}}
// nothing should explode
},
);

it("should include middleware headers with 'fastify' handler", async () => {
const fastify = Fastify();

fastify.addHook('onRequest', (_, reply, done) => {
reply.header('x-custom', 'cust');
done();
});
fastify.all(
'/',
createFastifyHandler({
schema,
onConnect(req) {
expect(req.headers.get('x-custom')).toBe('cust');
},
}),
);

const url = await fastify.listen({ port: 0 });
makeDisposeForServer(fastify.server);

const res = await fetch(url, {
method: 'POST',
headers: {
accept: 'text/event-stream',
'content-type': 'application/json',
},
body: JSON.stringify({
query: '{ getValue }',
}),
});

expect(res.ok).toBeTruthy();
expect(res.headers.get('x-custom')).toBe('cust');
});

0 comments on commit 134c1b0

Please sign in to comment.