Skip to content

Commit ad149d8

Browse files
committed
adding post-processing example
1 parent b361588 commit ad149d8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

demos/post-processing.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const toArray = require('stream-to-array')
2+
const gateway = require('../index')
3+
4+
gateway({
5+
routes: [{
6+
prefix: '/httpbin',
7+
target: 'https://httpbin.org',
8+
hooks: {
9+
async onResponse (req, res, stream) {
10+
// collect all streams parts
11+
const resBuffer = Buffer.concat(await toArray(stream))
12+
13+
// parse response body, for example: JSON
14+
const payload = JSON.parse(resBuffer)
15+
// modify the response, for example adding new properties
16+
payload.newProperty = 'post-processing'
17+
18+
// stringify response object again
19+
const newResponseBody = JSON.stringify(payload)
20+
21+
// set new content-length header
22+
res.setHeader('content-length', '' + Buffer.byteLength(newResponseBody))
23+
// set response statusCode
24+
res.statusCode = stream.statusCode
25+
26+
// send new response payload
27+
res.end(newResponseBody)
28+
}
29+
}
30+
}]
31+
}).start(8080)

0 commit comments

Comments
 (0)