|
| 1 | +import Fastify from "fastify"; |
| 2 | +import cors from "@fastify/cors"; |
| 3 | +import helmet from "@fastify/helmet"; |
| 4 | +import rateLimit from "@fastify/rate-limit"; |
| 5 | +import swagger from "@fastify/swagger"; |
| 6 | + |
| 7 | +const fastify = Fastify({ |
| 8 | + logger: { |
| 9 | + transport: { |
| 10 | + target: "pino-pretty", |
| 11 | + }, |
| 12 | + }, |
| 13 | +}); |
| 14 | + |
| 15 | +// Swagger documentation |
| 16 | +const swaggerConfig = { |
| 17 | + swagger: { |
| 18 | + info: { |
| 19 | + title: "API Documentation", |
| 20 | + version: "1.0.0", |
| 21 | + }, |
| 22 | + }, |
| 23 | +}; |
| 24 | + |
| 25 | +// Register plugins |
| 26 | +await fastify.register(cors); |
| 27 | +await fastify.register(helmet); |
| 28 | +await fastify.register(rateLimit, { |
| 29 | + max: 100, |
| 30 | + timeWindow: "1 minute", |
| 31 | +}); |
| 32 | +await fastify.register(swagger, swaggerConfig); |
| 33 | + |
| 34 | +// Example route with schema validation |
| 35 | +// fastify.get( |
| 36 | +// "/items", |
| 37 | +// { |
| 38 | +// schema: { |
| 39 | +// response: { |
| 40 | +// 200: { |
| 41 | +// type: "array", |
| 42 | +// items: { |
| 43 | +// type: "object", |
| 44 | +// properties: { |
| 45 | +// id: { type: "string" }, |
| 46 | +// name: { type: "string" }, |
| 47 | +// }, |
| 48 | +// }, |
| 49 | +// }, |
| 50 | +// }, |
| 51 | +// }, |
| 52 | +// }, |
| 53 | +// async (request, reply) => { |
| 54 | +// return [{ id: "1", name: "Item 1" }]; |
| 55 | +// }, |
| 56 | +// ); |
| 57 | + |
| 58 | +fastify.get( |
| 59 | + "/", |
| 60 | + { |
| 61 | + schema: { |
| 62 | + response: { |
| 63 | + 200: { |
| 64 | + type: "object", |
| 65 | + properties: { |
| 66 | + hello: { type: "string" }, |
| 67 | + }, |
| 68 | + }, |
| 69 | + }, |
| 70 | + }, |
| 71 | + }, |
| 72 | + async () => { |
| 73 | + return { hello: "world" }; |
| 74 | + }, |
| 75 | +); |
| 76 | + |
| 77 | +// Error handler |
| 78 | +fastify.setErrorHandler((error, request, reply) => { |
| 79 | + fastify.log.error(error); |
| 80 | + reply.status(500).send({ error: "Internal Server Error" }); |
| 81 | +}); |
| 82 | + |
| 83 | +try { |
| 84 | + await fastify.listen({ port: 3000 }); |
| 85 | +} catch (err) { |
| 86 | + fastify.log.error(err); |
| 87 | + process.exit(1); |
| 88 | +} |
0 commit comments