-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (67 loc) · 2.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const http2 = require('http2')
function grpcWebMiddleware (grpcUrl, pathPrefix) {
let grpcClient = http2.connect(grpcUrl, {})
grpcClient.on('error', (err) => {
console.log('grpcClient error: ' + JSON.stringify(err))
})
return async function (req, res, next) {
if (grpcClient.destroyed) {
grpcClient = http2.connect(grpcUrl)
grpcClient.on('error', (err) => {
console.log('grpcClient error: ' + JSON.stringify(err))
})
}
if (isApplicable(req, pathPrefix)) {
await callGrpcServer(req, res, grpcClient, pathPrefix)
} else {
await next()
}
}
}
function isApplicable (req, pathPrefix) {
let prefixCondition = pathPrefix ? req.url.startsWith(pathPrefix) : true
let contentType = req.headers['content-type']
let grpcRequestCondition = contentType && contentType.toUpperCase() === 'application/grpc-web-text'.toUpperCase() && req.method === 'POST'
return grpcRequestCondition && prefixCondition
}
function callGrpcServer (req, res, hc, pathPrefix) {
let grpcPath = pathPrefix ? req.url.slice(pathPrefix.length) : req.url
return new Promise(function (resolve, reject) {
let hasResponse = false
res.setHeader('content-type', 'application/grpc-web-text')
// init http2 post request
let h2req = hc.request({
[http2.constants.HTTP2_HEADER_TE]: 'trailers',
[http2.constants.HTTP2_HEADER_METHOD]: http2.constants.HTTP2_METHOD_POST,
[http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc',
[http2.constants.HTTP2_HEADER_PATH]: grpcPath
})
h2req.on('response', (headers) => {
res.statusCode = headers[http2.constants.HTTP2_HEADER_STATUS]
hasResponse = true
})
h2req.on('data', (chunk) => {
res.write(Buffer.from(chunk).toString('base64'))
})
h2req.on('end', () => {
if (hasResponse) {
res.end()
resolve()
}
})
h2req.on('error', (err) => {
reject(err)
})
// decode and write request data to http2 request
req.on('data', function (chunk) {
h2req.write(Buffer.from(chunk.toString(), 'base64'))
})
req.on('end', function () {
h2req.end()
})
}).catch((error) => {
res.statusCode = 500
res.end(JSON.stringify(error))
})
}
module.exports = grpcWebMiddleware