import { Database } from 'bun:sqlite'; const db = new Database('../data/data.db'); db.exec('PRAGMA journal_mode = WAL;'); Bun.serve({ fetch(req) { console.log('req object', req); const url = new URL(req.url); if (url.pathname === '/') return new Response('Home page!'); if (req.method === 'POST' && url.pathname === '/api') return handlePost(req, url); if (req.method === 'GET' && url.pathname.startsWith('/api')) return handleGet(req, url); return new Response('404!'); }, }); async function handleGet(_req: Request, url: URL) { if (url.pathname === '/api/resource') return handleGetResource(url); else return new Response('huh'); } function handleGetResource(url: URL) { const params = new URLSearchParams(url.search); console.log(params); const type = params.get('type'); const resource = params.get('res'); const data = fetchResource(type!, resource!); return Response.json({ ok: true, data }); } async function handlePost(req: Request, url: URL) { const data = await req.json(); if (url.pathname === '/api/user') return handlePostUser(data); else return new Response('huh'); } // https://bun.sh/guides/http/server type PostUser = { name: string; creds: string }; function handlePostUser(user: PostUser) { addUser(user.name, user.creds); return new Response('ok'); } function addUser(name: string, creds: string) { const query = db.query(` INSERT INTO users(name, creds) VALUES($name, $creds) `); query.run({ $name: name, $creds: creds }); } function fetchResource(type: string, resource: string) { if (type === 'word') return fetchWord(resource); else return {}; } function fetchWord(word: string) { const query = db.query(` SELECT spelling, ipa, languages.name AS language, GROUP_CONCAT(c.name, ',') AS category, ps.name AS pos FROM words JOIN languages ON languages.id = words.language_id JOIN word_categories wc ON words.id = wc.word_id JOIN categories c ON wc.category_id = c.id JOIN parts_of_speech ps ON ps.id = c.part_of_speech_id WHERE spelling = $spelling GROUP BY words.id `); return query.get({ $spelling: word }); }