The serverless API for our final software engineering project.

getTopicList.ts 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
  2. import type { NextApiRequest, NextApiResponse } from "next";
  3. import NextCors from "nextjs-cors";
  4. import { getDatabaseId, notion } from "../../lib/notion";
  5. import { DatabaseType, Error, Topic } from "../../types";
  6. function getTopicsInDatabase(notionResp: any): Topic[] {
  7. return notionResp.results.map((block: any) => ({
  8. blockId: block.id,
  9. name: block.properties.Name.title[0].plain_text,
  10. }));
  11. }
  12. export default async function handler(
  13. req: NextApiRequest,
  14. res: NextApiResponse<Topic[] | Error>
  15. ) {
  16. await NextCors(req, res, {
  17. methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
  18. origin: "*",
  19. optionsSuccessStatus: 200,
  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. }