Skip to content

Commit c891405

Browse files
authored
Merge pull request #3 from jkyberneees/populate-content-length-if-missing
Populate content-length header if missing
2 parents 2a6f3f8 + 7ad608d commit c891405

File tree

4 files changed

+36
-4
lines changed

4 files changed

+36
-4
lines changed

index.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
const fastProxy = require('fast-proxy')
22
const restana = require('restana')
3+
const pump = require('pump')
4+
const toArray = require('stream-to-array')
35

46
const gateway = (opts) => {
57
opts = Object.assign({
@@ -24,6 +26,7 @@ const gateway = (opts) => {
2426
// populating required NOOPS
2527
route.hooks = route.hooks || {}
2628
route.hooks.onRequest = route.hooks.onRequest || onRequestNoOp
29+
route.hooks.onResponse = route.hooks.onResponse || onResponse
2730

2831
// populating pathRegex if missing
2932
route.pathRegex = undefined === route.pathRegex ? opts.pathRegex : String(route.pathRegex)
@@ -52,5 +55,20 @@ const handler = (route, proxy) => async (req, res) => {
5255
}
5356

5457
const onRequestNoOp = (req, res) => { }
58+
const onResponse = async (req, res, stream) => {
59+
if (!res.hasHeader('content-length')) {
60+
try {
61+
const resBuffer = Buffer.concat(await toArray(stream))
62+
res.statusCode = stream.statusCode
63+
res.setHeader('content-length', '' + Buffer.byteLength(resBuffer))
64+
res.end(resBuffer)
65+
} catch (err) {
66+
res.send(err)
67+
}
68+
} else {
69+
res.statusCode = stream.statusCode
70+
pump(stream, res)
71+
}
72+
}
5573

5674
module.exports = gateway

package-lock.json

Lines changed: 14 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "fast-gateway",
3-
"version": "1.1.2",
3+
"version": "1.2.0",
44
"description": "A Node.js API Gateway for the masses!",
55
"main": "index.js",
66
"scripts": {
@@ -28,7 +28,8 @@
2828
"dependencies": {
2929
"fast-proxy": "^1.1.2",
3030
"http-cache-middleware": "^1.0.0",
31-
"restana": "^3.1.1"
31+
"restana": "^3.1.1",
32+
"stream-to-array": "^2.3.0"
3233
},
3334
"devDependencies": {
3435
"chai": "^4.2.0",

test/smoke.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ describe('API Gateway', () => {
230230

231231
it('POST /users/info - 404', async () => {
232232
await request(gateway)
233-
.post('/users/find')
233+
.post('/users/info')
234234
.expect(404)
235235
})
236236

0 commit comments

Comments
 (0)