| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154 |
- import { cache } from "react";
- import { NotionAPI } from "notion-client";
- import { Block, ExtendedRecordMap } from "notion-types";
- import { getPageTitle } from "notion-utils";
- import { Blog } from "@/types/blog";
- import { notionBlogConfig } from "@/config/site";
- const notion = new NotionAPI();
- // The Notion API now wraps block entries in an extra layer:
- // block[id] = { spaceId, value: { value: Block, role } }
- // react-notion-x expects the older shape:
- // block[id] = { value: Block, role }
- // This type covers both shapes so we can unwrap safely.
- type NestedBlockEntry = {
- spaceId?: string;
- value: { value: Block; role: string };
- };
- function normalizeRecordMap(recordMap: ExtendedRecordMap): ExtendedRecordMap {
- const block = { ...recordMap.block };
- 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;
- }
- }
- return { ...recordMap, block };
- }
- export const getPageContent = cache(async (pageId: string) => {
- const raw = await notion.getPage(pageId);
- const recordMap = normalizeRecordMap(raw);
- const title = getPageTitle(recordMap);
- const blocks = recordMap.block;
- return { title, blocks, recordMap };
- });
- export async function getAllBlogPosts(pageId: string) {
- const recordMap = normalizeRecordMap(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?.["\\u2O5F"]?.[0]?.[0] ?? "",
- });
- });
- 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;
- };
|