|
| 1 | +import { Handler } from '@netlify/functions'; |
| 2 | +import fastify, { FastifyInstance, FastifyRequest } from 'fastify'; |
| 3 | +import awsLambdaFastify from '@fastify/aws-lambda'; |
| 4 | +import sensible from '@fastify/sensible'; |
| 5 | +import { products } from '@nx-example/shared/product/data'; |
| 6 | +import cors from '@fastify/cors'; |
| 7 | +import { randomUUID } from 'crypto'; |
| 8 | + |
| 9 | +async function routes(fastify: FastifyInstance) { |
| 10 | + fastify.get('/products', async () => { |
| 11 | + return products; |
| 12 | + }); |
| 13 | + fastify.post( |
| 14 | + '/checkout', |
| 15 | + async ( |
| 16 | + request: FastifyRequest<{ |
| 17 | + Body: { productId: string; quanntity: number }[]; |
| 18 | + }> |
| 19 | + ) => { |
| 20 | + const items = request.body; |
| 21 | + console.log(request.body); |
| 22 | + const price = items.reduce((acc, item) => { |
| 23 | + const product = products.find((p) => p.id === item.productId); |
| 24 | + return acc + product.price * item.quanntity; |
| 25 | + }, 0); |
| 26 | + |
| 27 | + // gotta think real hard |
| 28 | + await new Promise((resolve) => setTimeout(resolve, Math.random() * 1000)); |
| 29 | + |
| 30 | + return { success: true, orderId: randomUUID(), total: price }; |
| 31 | + } |
| 32 | + ); |
| 33 | +} |
| 34 | + |
| 35 | +function init() { |
| 36 | + const app = fastify(); |
| 37 | + app.register(sensible); |
| 38 | + app.register(cors); |
| 39 | + // set the prefix for the netlify functions url |
| 40 | + app.register(routes, { |
| 41 | + prefix: `${process.env.BASE_API_PATH || ''}/api`, |
| 42 | + }); |
| 43 | + return app; |
| 44 | +} |
| 45 | + |
| 46 | +// Note: Netlify deploys this function at the endpoint /.netlify/functions/api |
| 47 | +export const handler: Handler = awsLambdaFastify(init()); |
0 commit comments