The serverless API for our final software engineering project.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 ?? "Untitled",
  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, category },
  23. } = req;
  24. const blockId = getDatabaseId(type as DatabaseType);
  25. if (!blockId) {
  26. res.status(404).json({ status: "Not found." });
  27. } else {
  28. const categoryFilter = category
  29. ? {
  30. filter: {
  31. property: "Category",
  32. select: {
  33. equals: category,
  34. },
  35. },
  36. }
  37. : {};
  38. const resp = await notion.databases.query({
  39. database_id: blockId,
  40. sorts: [
  41. {
  42. property: "Created",
  43. direction: "ascending",
  44. },
  45. ],
  46. ...categoryFilter,
  47. });
  48. console.log(resp);
  49. res.status(200).json(getTopicsInDatabase(resp));
  50. }
  51. }