111 lines
2.6 KiB
JavaScript
111 lines
2.6 KiB
JavaScript
import { dbHelpers } from '../../../backend/src/db.js'
|
|
|
|
const { query, queryOne, run } = dbHelpers
|
|
|
|
/**
|
|
* API routes for this drop
|
|
*
|
|
* Route pattern format: "METHOD /path/:param"
|
|
*
|
|
* Example routes:
|
|
* - "GET /items" - Get all items
|
|
* - "GET /items/:id" - Get single item by ID
|
|
* - "POST /items" - Create new item
|
|
* - "PUT /items/:id" - Update item
|
|
* - "DELETE /items/:id" - Delete item
|
|
*/
|
|
export const routes = {
|
|
/**
|
|
* Get all items
|
|
* GET /api/<drop-name>/items
|
|
*/
|
|
'GET /items': async (req) => {
|
|
const items = query(
|
|
`SELECT * FROM DROPNAME_items ORDER BY created_at DESC`,
|
|
)
|
|
|
|
return Response.json({
|
|
items,
|
|
count: items.length,
|
|
})
|
|
},
|
|
|
|
/**
|
|
* Get single item by ID
|
|
* GET /api/<drop-name>/items/:id
|
|
*/
|
|
'GET /items/:id': async (req, params) => {
|
|
const item = queryOne(`SELECT * FROM DROPNAME_items WHERE id = ?`, [
|
|
params.id,
|
|
])
|
|
|
|
if (!item) {
|
|
return Response.json({ error: 'Item not found' }, { status: 404 })
|
|
}
|
|
|
|
return Response.json(item)
|
|
},
|
|
|
|
/**
|
|
* Create new item
|
|
* POST /api/<drop-name>/items
|
|
*/
|
|
'POST /items': async (req) => {
|
|
const body = await req.json()
|
|
|
|
// Validate input
|
|
if (!body.data) {
|
|
return Response.json(
|
|
{ error: 'Missing required field: data' },
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
|
|
const result = run(`INSERT INTO DROPNAME_items (data) VALUES (?)`, [
|
|
JSON.stringify(body.data),
|
|
])
|
|
|
|
return Response.json(
|
|
{
|
|
id: result.lastInsertRowid,
|
|
success: true,
|
|
},
|
|
{ status: 201 },
|
|
)
|
|
},
|
|
|
|
/**
|
|
* Update item
|
|
* PUT /api/<drop-name>/items/:id
|
|
*/
|
|
'PUT /items/:id': async (req, params) => {
|
|
const body = await req.json()
|
|
|
|
const result = run(`UPDATE DROPNAME_items SET data = ? WHERE id = ?`, [
|
|
JSON.stringify(body.data),
|
|
params.id,
|
|
])
|
|
|
|
if (result.changes === 0) {
|
|
return Response.json({ error: 'Item not found' }, { status: 404 })
|
|
}
|
|
|
|
return Response.json({ success: true })
|
|
},
|
|
|
|
/**
|
|
* Delete item
|
|
* DELETE /api/<drop-name>/items/:id
|
|
*/
|
|
'DELETE /items/:id': async (req, params) => {
|
|
const result = run(`DELETE FROM DROPNAME_items WHERE id = ?`, [
|
|
params.id,
|
|
])
|
|
|
|
if (result.changes === 0) {
|
|
return Response.json({ error: 'Item not found' }, { status: 404 })
|
|
}
|
|
|
|
return Response.json({ success: true })
|
|
},
|
|
}
|