summaryrefslogtreecommitdiff
path: root/packages/db/src/server.ts
blob: 6479b7fa9efa1e7e4ecfef5f9211dff1c739f6d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import DB from ".";

const db = new DB();
const ready = db.init();

type Route = Partial<
  Record<
    Bun.Serve.HTTPMethod,
    Bun.Serve.Handler<Bun.BunRequest, Bun.Server<undefined>, Response>
  >
>;
export const handler: Route = {
  async GET(req: Bun.BunRequest) {
    await ready;
    if (!db.ready) return Response.json({ error: "DB failed to initialize" });
    // const db = new DB();
    console.log("Handling HTTP Request on DB", req.url);

    try {
      const url = new URL(req.url);
      const params = url.searchParams;
      const word = params.get("word");
      const lang = params.get("lang");
      if (!word) return Response.json({ error: "word param is required" });
      if (!lang) return Response.json({ error: "lang param is required" });
      const row = await db.fetchExpressionBySpelling(word, lang);
      if (!row) return Response.json({ error: "No data found" });
      else return Response.json({ ok: row });
    } catch (e) {
      return Response.json({ error: `${e}` });
    }
  },
  async POST(req: Bun.BunRequest) {
    await ready;
    if (!db.ready) return Response.json({ error: "DB failed to initialize" });
    // const db = new DB();
    console.log("Handling HTTP Request on DB", req.url);

    try {
      const reqBody = (await req.json()) as RequestBody;
      if (!reqBody) return Response.json({ error: "No request body" });
      const returnData =
        "getWordFull" in reqBody
          ? db.fetchExpressionBySpelling(
              reqBody.getWordFull.spelling,
              reqBody.getWordFull.lang,
            )
          : null;
      const row = await returnData;
      console.log({ row });
      if (!returnData || !row) return Response.json({ error: "No data found" });
      else return Response.json({ ok: row });
    } catch (e) {
      return Response.json({ error: `${e}` });
    }
  },
};

type BySpelling = { spelling: string; lang: string };
type ByLanguage = string; // iso6393
type RequestBody =
  | { getWordFull: BySpelling }
  | { getWordsenses: BySpelling }
  | { getWordPhonetics: BySpelling }
  | { getLanguages: null }
  | { getExpressions: ByLanguage };