Build an API gateway that routes requests, handles authentication, and aggregates responses from multiple services
Create an API gateway that acts as a single entry point for multiple backend services, handling routing, authentication, request aggregation, and load balancing.
const services = {
users: 'http://user-service:3001',
products: 'http://product-service:3002',
orders: 'http://order-service:3003'
};
app.use('/api/*', authenticate);
app.get('/api/users/:id', async (req, res) => {
const response = await fetch(`${services.users}/users/${req.params.id}`);
res.json(await response.json());
});
app.get('/api/user-orders/:userId', async (req, res) => {
const [user, orders] = await Promise.all([
fetch(`${services.users}/users/${req.params.userId}`),
fetch(`${services.orders}/orders?userId=${req.params.userId}`)
]);
res.json({ user: await user.json(), orders: await orders.json() });
});