import { Hono } from 'hono';
// In-memory data store (in production, use D1, KV, or R2)
interface Product {
id: string;
name: string;
price: number;
description: string;
category: string;
inStock: boolean;
}
const products: Product[] = [
{
id: '1',
name: 'Wireless Headphones',
price: 99.99,
description: 'High-quality wireless headphones with noise cancellation',
category: 'Electronics',
inStock: true,
},
{
id: '2',
name: 'Coffee Maker',
price: 79.99,
description: 'Programmable coffee maker with thermal carafe',
category: 'Home',
inStock: true,
},
{
id: '3',
name: 'Running Shoes',
price: 129.99,
description: 'Lightweight running shoes with excellent cushioning',
category: 'Sports',
inStock: false,
},
];
export const apiRoutes = new Hono();
// GET /api/products - List all products (with optional filtering)
apiRoutes.get('/products', (c) => {
const category = c.req.query('category');
const inStock = c.req.query('inStock');
let filtered = [...products];
if (category) {
filtered = filtered.filter((p) => p.category.toLowerCase() === category.toLowerCase());
}
if (inStock !== undefined) {
const stockFilter = inStock === 'true';
filtered = filtered.filter((p) => p.inStock === stockFilter);
}
return c.json({
success: true,
data: filtered,
count: filtered.length,
});
});
// GET /api/products/:id - Get a single product
apiRoutes.get('/products/:id', (c) => {
const id = c.req.param('id');
const product = products.find((p) => p.id === id);
if (!product) {
return c.json({ success: false, error: 'Product not found' }, 404);
}
return c.json({ success: true, data: product });
});
// POST /api/products - Create a new product
apiRoutes.post('/products', async (c) => {
const body = await c.req.json();
const newProduct: Product = {
id: String(products.length + 1),
name: body.name,
price: body.price,
description: body.description,
category: body.category,
inStock: body.inStock ?? true,
};
products.push(newProduct);
return c.json({ success: true, data: newProduct }, 201);
});
// PUT /api/products/:id - Update a product
apiRoutes.put('/products/:id', async (c) => {
const id = c.req.param('id');
const body = await c.req.json();
const index = products.findIndex((p) => p.id === id);
if (index === -1) {
return c.json({ success: false, error: 'Product not found' }, 404);
}
products[index] = { ...products[index], ...body };
return c.json({ success: true, data: products[index] });
});
// DELETE /api/products/:id - Delete a product
apiRoutes.delete('/products/:id', (c) => {
const id = c.req.param('id');
const index = products.findIndex((p) => p.id === id);
if (index === -1) {
return c.json({ success: false, error: 'Product not found' }, 404);
}
const deleted = products.splice(index, 1)[0];
return c.json({ success: true, data: deleted });
});