Last active
January 11, 2021 14:24
-
-
Save jameswragg/91de61bde927bc2599c71754e86f20cb to your computer and use it in GitHub Desktop.
Using trumpet to read/modify/write the IncomingMessage stream in @hapi/h2o2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Hapi = require("@hapi/hapi"); | |
const H2o2 = require("@hapi/h2o2"); | |
const { PassThrough } = require("stream"); | |
const trumpet = require("trumpet"); | |
const start = async function () { | |
const server = Hapi.server({ | |
host: "localhost", | |
port: 8000, | |
}); | |
try { | |
await server.register(H2o2); | |
server.route({ | |
method: "GET", | |
path: "/", | |
handler: async (request, h) => { | |
return h.proxy({ | |
uri: "https://hapi.dev", | |
onResponse: async function (err, res, request, h, settings, ttl) { | |
const tr = trumpet(); | |
const ws = tr.select("a.index-button").createWriteStream(); | |
ws.end("Make me hapi"); | |
const response = h | |
.response(res.pipe(tr).pipe(new PassThrough())) | |
.ttl(ttl) | |
.code(res.statusCode) | |
.passThrough(!!settings.passThrough); | |
response.headers = res.headers; | |
return response; | |
}, | |
}); | |
}, | |
}); | |
server.start(); | |
console.log(`Server started at: ${server.info.uri}`); | |
} catch (e) { | |
console.log("Failed to load h2o2"); | |
} | |
}; | |
start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because trumpet is returning an old-style Node.js stream you can convert via a
PassThrough()
which is an in/out Transform to a new-style stream.