Skip to content

Instantly share code, notes, and snippets.

@jameswragg
Last active January 11, 2021 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameswragg/91de61bde927bc2599c71754e86f20cb to your computer and use it in GitHub Desktop.
Save jameswragg/91de61bde927bc2599c71754e86f20cb to your computer and use it in GitHub Desktop.
Using trumpet to read/modify/write the IncomingMessage stream in @hapi/h2o2
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();
@jameswragg
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment