Skip to content

Commit 8882132

Browse files
authored
🔧 fix: map response example (#250)
* fix: map response example * fix: clarify merging headers with map response
1 parent 1ea3865 commit 8882132

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

‎docs/life-cycle/map-response.md

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,32 @@ It's recommended to use transform for the following:
2828
Below is an example of using mapResponse to provide Response compression.
2929

3030
```typescript
31-
import { Elysia, mapResponse } from 'elysia'
32-
import { gzipSync } from 'bun'
31+
import { Elysia } from 'elysia'
3332

3433
new Elysia()
35-
.mapResponse(({ response }) => {
34+
.mapResponse(({ response, set }) => {
35+
const isJson = typeof response === 'object'
36+
37+
const text = isJson
38+
? JSON.stringify(response)
39+
: response?.toString() ?? ''
40+
41+
set.headers['Content-Encoding'] = 'gzip'
42+
3643
return new Response(
37-
gzipSync(
38-
typeof response === 'object'
39-
? JSON.stringify(response)
40-
: response.toString()
41-
)
44+
Bun.gzipSync(new TextEncoder('utf-8').encode(text)),
45+
{
46+
headers: {
47+
'Content-Type': `${
48+
isJson ? 'application/json' : 'text/plain'
49+
}; charset=utf-8`
50+
}
51+
}
4252
)
4353
})
44-
.listen(3000)
54+
.get('/text', () => 'mapResponse')
55+
.get('/json', () => ({ map: 'response' }))
56+
.listen(8080)
4557
```
4658

4759
Like **parse** and **beforeHandle**, after a value is returned, the next iteration of afterHandle will be skipped.

0 commit comments

Comments
 (0)