123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
- import type { NextApiRequest, NextApiResponse } from "next";
- import NextCors from "nextjs-cors";
- import { getDatabaseId, notion } from "../../lib/notion";
- import { DatabaseType, Error, Topic } from "../../types";
-
- function getTopicsInDatabase(notionResp: any): Topic[] {
- return notionResp.results.map((block: any) => ({
- blockId: block.id,
- name: block.properties.Name?.title?.[0]?.plain_text ?? "Untitled",
- }));
- }
-
- export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse<Topic[] | Error>
- ) {
- await NextCors(req, res, {
- methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
- origin: "*",
- optionsSuccessStatus: 200,
- });
-
- const {
- query: { type, category },
- } = req;
- const blockId = getDatabaseId(type as DatabaseType);
- if (!blockId) {
- res.status(404).json({ status: "Not found." });
- } else {
- const categoryFilter = category
- ? {
- filter: {
- property: "Category",
- select: {
- equals: category,
- },
- },
- }
- : {};
- const resp = await notion.databases.query({
- database_id: blockId,
- sorts: [
- {
- property: "Created",
- direction: "ascending",
- },
- ],
- ...categoryFilter,
- });
- console.log(resp);
- res.status(200).json(getTopicsInDatabase(resp));
- }
- }
|