/** * Example: using backend-toolkit inside a Fastify app. * * Requires fastify to be installed separately: * npm install fastify * * Run with: node examples/fastify.js */ const Fastify = require("fastify"); const { z } = require("zod"); const { success, error, validate, paginate, getPaginationParams, logger } = require("../src/index"); const fastify = Fastify(); const posts = [ { id: 1, title: "Hello world" }, { id: 2, title: "backend-toolkit" }, ]; const createPostSchema = z.object({ title: z.string().min(1) }); fastify.post("/posts", async (request, reply) => { const result = validate(createPostSchema, request.body); if (!result.success) { return reply.status(400).send(error("Validation failed", 400, result.errors)); } const post = { id: posts.length + 1, title: result.data.title }; posts.push(post); return reply.status(201).send(success(post, "Post created", 201)); }); fastify.get("/posts", async (request) => { const { page, limit } = getPaginationParams(request.query); const meta = paginate({ page, limit, totalItems: posts.length }); const items = posts.slice(meta.offset, meta.offset + meta.limit); return success({ items, meta }, "Posts fetched"); }); fastify.get("/posts/:id", async (request, reply) => { const post = posts.find((p) => String(p.id) === request.params.id); if (!post) { return reply.status(404).send(error("Post not found", 404)); } return success(post, "Post fetched"); }); const port = process.env.PORT || 3001; fastify .listen({ port }) .then(() => logger.info(`Example app listening on port ${port}`)) .catch((err) => { logger.error(err.message); process.exit(1); });