| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 |
- import { cache } from "react";
- import { NotionAPI } from "notion-client";
- import { Block, BlockMap, ExtendedRecordMap, Role } from "notion-types";
- import { getPageTitle } from "notion-utils";
- import { Blog } from "@/types/blog";
- import { notionBlogConfig } from "@/config/site";
- // Notion now returns { spaceId, value: { value, role } }; notion-client 7.x expects { value, role }.
- type NestedBlockEntry = {
- spaceId?: string;
- value: { value: Block; role: Role };
- };
- function unwrapBlocks(block: BlockMap) {
- for (const [id, entry] of Object.entries(block)) {
- const nested = entry as unknown as NestedBlockEntry;
- if (
- nested?.value?.value !== undefined &&
- nested?.value?.role !== undefined
- ) {
- block[id] = nested.value;
- }
- }
- }
- const notion = new NotionAPI({
- ofetchOptions: {
- // Notion's Cloudflare rejects Node's default "node" User-Agent with a 403.
- headers: {
- "User-Agent":
- "notion-client (+https://github.com/NotionX/react-notion-x)",
- },
- // Must run before notion-client walks the page, or it never fetches blocks past the first chunk.
- onResponse({ response }) {
- const block = response._data?.recordMap?.block;
- if (block) unwrapBlocks(block);
- },
- },
- });
- export const getPageContent = cache(async (pageId: string) => {
- const recordMap = await notion.getPage(pageId);
- const title = getPageTitle(recordMap);
- const blocks = recordMap.block;
- return { title, blocks, recordMap };
- });
- export async function getAllBlogPosts(pageId: string) {
- const recordMap = await notion.getPage(pageId);
- const blocks = recordMap.block;
- let blogPosts: Blog[] = [];
- Object.entries(blocks).forEach(([key, value]) => {
- const block = value.value;
- if (
- key === notionBlogConfig.blogParentId ||
- block?.type !== "page" ||
- !block?.properties?.title
- ) {
- return;
- }
- blogPosts.push({
- id: key,
- block,
- pageCover: block.format?.page_cover ?? "",
- title: block.properties.title[0][0],
- createdAt: block.created_time ? new Date(block.created_time) : null,
- lastEditedAt: block.last_edited_time
- ? new Date(block.last_edited_time)
- : null,
- description:
- (block.properties as Record<string, unknown[][]>)?.["\\u2O5F"]?.[0]?.[0]?.toString() ?? "",
- });
- });
- blogPosts.sort(
- (a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0),
- );
- return blogPosts;
- }
- /** Extract a plain-text excerpt from a Notion recordMap (first ~160 chars). */
- export function extractDescription(recordMap: ExtendedRecordMap): string {
- const blocks = Object.values(recordMap.block);
- for (const block of blocks) {
- const value = block?.value;
- if (!value) continue;
- if (value.type !== "text" && value.type !== "quote") continue;
- const text = value.properties?.title
- ?.map((chunk: unknown[]) => chunk[0])
- .join("")
- .trim();
- if (text && text.length > 0) {
- return text.length > 160 ? text.slice(0, 157) + "..." : text;
- }
- }
- return "";
- }
- export const customMapImageUrl = (url: string, block: Block): string => {
- if (!url) {
- throw new Error("URL can't be empty");
- }
- if (url.startsWith("data:")) {
- return url;
- } // more recent versions of notion don't proxy unsplash images
- if (url.startsWith("https://images.unsplash.com")) {
- return url;
- }
- try {
- const u = new URL(url);
- if (
- u.pathname.startsWith("/secure.notion-static.com") &&
- u.hostname.endsWith(".amazonaws.com")
- ) {
- if (
- u.searchParams.has("X-Amz-Credential") &&
- u.searchParams.has("X-Amz-Signature") &&
- u.searchParams.has("X-Amz-Algorithm")
- ) {
- // if the URL is already signed, then use it as-is
- url = u.origin + u.pathname;
- }
- }
- } catch {
- // ignore invalid urls
- }
- if (url.startsWith("/images")) {
- url = `https://www.notion.so${url}`;
- }
- url = `https://www.notion.so${
- url.startsWith("/image") ? url : `/image/${encodeURIComponent(url)}`
- }`;
- const notionImageUrlV2 = new URL(url);
- let table = block.parent_table === "space" ? "block" : block.parent_table;
- if (table === "collection" || table === "team") {
- table = "block";
- }
- notionImageUrlV2.searchParams.set("table", table);
- notionImageUrlV2.searchParams.set("id", block.id);
- notionImageUrlV2.searchParams.set("cache", "v2");
- url = notionImageUrlV2.toString();
- return url;
- };
|