The serverless API for our final software engineering project.

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