Browse Source

[feat] Don't hardcode database block IDs

Sergio Mattei 2 years ago
parent
commit
b80978635f
3 changed files with 44 additions and 15 deletions
  1. 0
    2
      config.ts
  2. 20
    0
      lib/notion.ts
  3. 24
    13
      pages/api/getTopicList.ts

+ 0
- 2
config.ts View File

@@ -1,3 +1 @@
1 1
 export const NOTION_KEY = process.env.NOTION_KEY;
2
-export const LAWS_BLOCK_ID =
3
-  process.env.LAWS_BLOCK_ID ?? "d02fa51eda254c9fa4b97e5f9beb1a86";

+ 20
- 0
lib/notion.ts View File

@@ -3,3 +3,23 @@ import { NOTION_KEY } from "../config";
3 3
 const { Client } = require("@notionhq/client");
4 4
 
5 5
 export const notion = new Client({ auth: NOTION_KEY });
6
+
7
+export type DatabaseType = "laws" | "advice";
8
+
9
+/**
10
+ * Translates incoming GET parameters into a valid block ID.
11
+ * @param type
12
+ * @returns string
13
+ */
14
+export function getDatabaseId(type: DatabaseType): string | undefined {
15
+  switch (type) {
16
+    case "laws":
17
+      return "d02fa51eda254c9fa4b97e5f9beb1a86";
18
+
19
+    case "advice":
20
+      return "9515c0f02e454e968c44336bd1beb463";
21
+
22
+    default:
23
+      return undefined;
24
+  }
25
+}

+ 24
- 13
pages/api/getTopicList.ts View File

@@ -1,13 +1,16 @@
1 1
 // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
2 2
 import type { NextApiRequest, NextApiResponse } from "next";
3
-import { LAWS_BLOCK_ID } from "../../config";
4
-import { notion } from "../../lib/notion";
3
+import { DatabaseType, getDatabaseId, notion } from "../../lib/notion";
5 4
 
6 5
 interface Topic {
7 6
   blockId: string;
8 7
   name: string;
9 8
 }
10 9
 
10
+interface Error {
11
+  status: string;
12
+}
13
+
11 14
 function getTopicsInDatabase(notionResp: any): Topic[] {
12 15
   return notionResp.results.map((block: any) => ({
13 16
     blockId: block.id,
@@ -17,16 +20,24 @@ function getTopicsInDatabase(notionResp: any): Topic[] {
17 20
 
18 21
 export default async function handler(
19 22
   req: NextApiRequest,
20
-  res: NextApiResponse<Topic[]>
23
+  res: NextApiResponse<Topic[] | Error>
21 24
 ) {
22
-  const resp = await notion.databases.query({
23
-    database_id: LAWS_BLOCK_ID,
24
-    sorts: [
25
-      {
26
-        property: "Created",
27
-        direction: "ascending",
28
-      },
29
-    ],
30
-  });
31
-  res.status(200).json(getTopicsInDatabase(resp));
25
+  const {
26
+    query: { type },
27
+  } = req;
28
+  const blockId = getDatabaseId(type as DatabaseType);
29
+  if (!blockId) {
30
+    res.status(404).json({ status: "Not found." });
31
+  } else {
32
+    const resp = await notion.databases.query({
33
+      database_id: blockId,
34
+      sorts: [
35
+        {
36
+          property: "Created",
37
+          direction: "ascending",
38
+        },
39
+      ],
40
+    });
41
+    res.status(200).json(getTopicsInDatabase(resp));
42
+  }
32 43
 }