Skip to content

Instantly share code, notes, and snippets.

@WhereJuly
Last active February 20, 2024 14:39
Show Gist options
  • Save WhereJuly/f4911312e46d56567a8192710a008705 to your computer and use it in GitHub Desktop.
Save WhereJuly/f4911312e46d56567a8192710a008705 to your computer and use it in GitHub Desktop.
fastify-http-proxy (fastify/reply-from) replyOptions.onResponse getting the original response body example
'use strict';
import fastify, { FastifyReply, FastifyRequest, RawReplyDefaultExpression, RawServerBase, RequestGenericInterface } from 'fastify';
import proxy from '@fastify/http-proxy';
const server = fastify();
server.register(proxy, {
upstream: 'http://proxied.tld',
prefix: '/proxied',
replyOptions: {
onResponse: onResponse
}
});
async function onResponse(request: FastifyRequest<RequestGenericInterface, RawServerBase>, reply: FastifyReply<RawServerBase>, res: RawReplyDefaultExpression<RawServerBase>): Promise<void> {
/**
* Get the original response from the proxied server.
*/
const result = await new Promise((resolve, reject) => {
let originalResponse: string = '';
// We assume response is a buffer that can be converted to a string.
res.on('data', (args: Buffer) => { originalResponse += args.toString(); });
res.on('end', () => {
/**
* Then assume that string is JSON-parseable.
* Here we get the response body (type {statusCode: number, uuid: string}) from original response `res`
*/
const json = JSON.parse(originalResponse);
// Assume the 200 status code is the only we want to process. For others return early.
if (json.statusCode !== 200) { return resolve(200); }
// At last call the domain function.
createUser(json.uuid)
.then(() => { return resolve(201); })
.catch((error) => { return reject(error); });
});
res.on('error', (error: Error) => {
return reject(error);
});
});
/**
* Finally respond from the local server with something appropriate.
* Here result should be 200 or 201 status code from the `resolve`'s above.
*
*/
reply.send(result);
}
/**
* The domain function doing something meaningful.
*/
async function createUser(uuid: string): Promise<void> {
console.log(uuid);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment