0

Is there a possibility in Fastify to avoid writing the similar handler always?

My handler looks like (a proxy sort of):

handler: async (request, reply) => { reply.from(proxyMap[request.url]); return reply; } 

where the proxyMap is just a mapping of my proxy routes to target/upstream route path. However the handler is always same.

Say a sample proxyMap content can be:

 const proxyMap = { "/api/path1/proxy1" : "/api/backend/api1", "/api/path2/proxy2" : "/api/backend/api2", .... }; 

How can I move to handler somewhere common (say in some lifecycle hook or somewhere appropriate) such that every route I need not to write it. Like when I will write the route, it will be executed based on the proxyMap look up.

Is there a way in fastify to achieve that?

1 Answer 1

1

You can automate it with some coding:

async function handler(request, reply) { reply.from(proxyMap[request.url]) return reply } const proxyMap = { '/api/path1/proxy1': '/api/backend/api1', '/api/path2/proxy2': '/api/backend/api2', } Object.keys(proxyMap).forEach((url) => { fastify.get(url, { handler }) }) 
Sign up to request clarification or add additional context in comments.

1 Comment

Preety 👍 Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.