You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

43 lines
1.2 KiB

/**
* GET /api/products
*
* Returns a list of all active products available for purchase.
* Products are sorted by category and name.
*
* Query Parameters:
* - category: Filter by category (optional, comma-separated for multiple)
*/
import { eq, and, inArray } from 'drizzle-orm'
import { products } from '../../database/schema'
export default defineEventHandler(async (event) => {
const db = useDatabase()
const query = getQuery(event)
const categoryParam = query.category as string | undefined
try {
// Build where conditions
const conditions = [eq(products.active, true)]
// Filter by category if provided
if (categoryParam) {
const categories = categoryParam.split(',').map((c) => c.trim())
conditions.push(inArray(products.category, categories))
}
// Fetch products with filters
const allProducts = await db.query.products.findMany({
where: and(...conditions),
orderBy: (products, { asc }) => [asc(products.category), asc(products.name)],
})
return allProducts
} catch (error) {
console.error('Error fetching products:', error)
throw createError({
statusCode: 500,
statusMessage: 'Failed to fetch products',
})
}
})