(request, env, ctx)
| 7 | |
| 8 | export default { |
| 9 | async fetch(request, env, ctx): Promise<Response> { |
| 10 | const url = new URL(request.url) |
| 11 | const path = url.pathname |
| 12 | const method = request.method |
| 13 | |
| 14 | if (path === '/favicon.ico') |
| 15 | return new Response('Resource not found', { |
| 16 | status: 404, |
| 17 | headers: { |
| 18 | 'Content-Type': 'application/json', |
| 19 | }, |
| 20 | }) |
| 21 | |
| 22 | const adapter = new PrismaPg({ |
| 23 | connectionString: env.DATABASE_URL, |
| 24 | }) |
| 25 | |
| 26 | const prisma = new PrismaClient({ |
| 27 | adapter, |
| 28 | }) |
| 29 | |
| 30 | try { |
| 31 | // CREATE - Create a new user |
| 32 | if (path === '/users' && method === 'POST') { |
| 33 | const body = (await request.json()) as { email: string; name: string } |
| 34 | const user = await prisma.user.create({ |
| 35 | data: { |
| 36 | email: body.email || `user-${Date.now()}@example.com`, |
| 37 | name: body.name || 'Anonymous User', |
| 38 | }, |
| 39 | }) |
| 40 | return new Response(JSON.stringify({ success: true, user }), { |
| 41 | headers: { 'Content-Type': 'application/json' }, |
| 42 | }) |
| 43 | } |
| 44 | |
| 45 | // READ - Get all users |
| 46 | if (path === '/users' && method === 'GET') { |
| 47 | const users = await prisma.user.findMany() |
| 48 | return new Response( |
| 49 | JSON.stringify({ success: true, users, count: users.length }), |
| 50 | { |
| 51 | headers: { 'Content-Type': 'application/json' }, |
| 52 | }, |
| 53 | ) |
| 54 | } |
| 55 | |
| 56 | // READ - Get a specific user by ID |
| 57 | if (path.startsWith('/users/') && method === 'GET') { |
| 58 | const id = parseInt(path.split('/')[2]) |
| 59 | if (isNaN(id)) { |
| 60 | return new Response( |
| 61 | JSON.stringify({ success: false, error: 'Invalid user ID' }), |
| 62 | { |
| 63 | status: 400, |
| 64 | headers: { 'Content-Type': 'application/json' }, |
| 65 | }, |
| 66 | ) |
no test coverage detected