// examples/demo/api/product/[id]/route.ts
import { z } from "zod";
import type { BurgerRequest, BurgerResponse } from "burger-api";
// OpenAPI metadata for this route
export const openapi = {
get: {
summary: "Get Product Details",
description: "Retrieves product details by product ID.",
tags: ["Product"],
operationId: "getProductDetails",
},
put: {
summary: "Update Product",
description: "Updates an existing product by ID.",
tags: ["Product"],
operationId: "updateProduct",
},
delete: {
summary: "Delete Product",
description: "Deletes a product by ID.",
tags: ["Product"],
operationId: "deleteProduct",
}
};
// Validation Schemas for GET and POST requests
export const schema = {
get: {
params: z.object({
id: z.preprocess(
(val) => (typeof val === "string" ? parseInt(val, 10) : val),
z.number().min(1, "ID is required")
),
}),
query: z.object({
search: z.string().optional(),
includeDeleted: z.preprocess(
(val) => val === "true",
z.boolean().optional()
),
}),
},
post: {
body: z.object({
name: z.string().min(1, "Name is required"),
price: z.number().positive("Price must be positive"),
}),
},
};
// Route-specific middleware
export const middleware = [
async (
req: BurgerRequest,
res: BurgerResponse,
next: () => Promise<Response>
) => {
console.log("[Product Middleware] Executing product route middleware");
// You could add authentication or logging here
return next();
},
];
// GET handler: returns product details
export async function GET(
req: BurgerRequest,
res: BurgerResponse,
params: { id: number }
) {
console.log("[GET] Product route invoked");
const validatedParams = (req.validated?.params as { id: number }) || params;
const query = req.validated?.query || Object.fromEntries(req.query.entries());
// In a real app, you would fetch the product from a database
return res.json({
id: validatedParams.id,
query,
name: "Sample Product",
price: 99.99,
description: "This is a sample product",
});
}
// POST handler: creates a new product
export async function POST(req: BurgerRequest, res: BurgerResponse) {
console.log("[POST] Product route invoked");
const body = req.validated?.body || (await req.json());
// In a real app, you would save the product to a database
return res.json(body);
}
// PUT handler: updates a product
export async function PUT(
req: BurgerRequest,
res: BurgerResponse,
params: { id: number }
) {
const id = params.id;
const body = req.validated?.body || (await req.json());
// In a real app, you would update the product in a database
return res.json({
id,
...body,
updated: true,
});
}
// DELETE handler: deletes a product
export async function DELETE(
req: BurgerRequest,
res: BurgerResponse,
params: { id: number }
) {
const id = params.id;
// In a real app, you would delete the product from a database
return res.json({
id,
deleted: true,
});
}