Skip to content

Commit e1da87e

Browse files
authored
feat: add x-request-id to the response (#96)
1 parent 182dbb9 commit e1da87e

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/response.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,13 @@ export class Response extends Macroable {
378378
return
379379
}
380380

381+
/*
382+
* ----------------------------------------
383+
* SET X-REQUEST-ID HEADER
384+
* ----------------------------------------
385+
*/
386+
this.setRequestId()
387+
381388
/*
382389
* ----------------------------------------
383390
* SET CONTENT-LENGTH HEADER
@@ -779,6 +786,18 @@ export class Response extends Macroable {
779786
return this
780787
}
781788

789+
/**
790+
* Set X-Request-Id header by copying the header value from the request if it exists.
791+
*
792+
*/
793+
setRequestId(): this {
794+
const requestId = this.request.headers['x-request-id']
795+
if (requestId) {
796+
this.header('X-Request-Id', requestId)
797+
}
798+
return this
799+
}
800+
782801
/**
783802
* Returns a boolean telling if the new response etag evaluates same
784803
* as the request header `if-none-match`. In case of `true`, the

tests/response.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,18 @@ test.group('Response', (group) => {
108108
})
109109
})
110110

111+
test('set x-request-id header', async () => {
112+
const { url } = await httpServer.create((req, res) => {
113+
req.headers['x-request-id'] = '20241127'
114+
const response = new ResponseFactory().merge({ req, res, encryption, router }).create()
115+
116+
response.send('<p> hello </p>')
117+
response.finish()
118+
})
119+
120+
await supertest(url).get('/').expect(200).expect('x-request-id', '20241127')
121+
})
122+
111123
test('get merged from http res object', async ({ assert }) => {
112124
const { url } = await httpServer.create((req, res) => {
113125
res.setHeader('content-type', 'application/json')

0 commit comments

Comments
 (0)