notion.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import { cache } from "react";
  2. import { NotionAPI } from "notion-client";
  3. import { Block, ExtendedRecordMap } from "notion-types";
  4. import { getPageTitle } from "notion-utils";
  5. import { Blog } from "@/types/blog";
  6. import { notionBlogConfig } from "@/config/site";
  7. const notion = new NotionAPI();
  8. // The Notion API now wraps block entries in an extra layer:
  9. // block[id] = { spaceId, value: { value: Block, role } }
  10. // react-notion-x expects the older shape:
  11. // block[id] = { value: Block, role }
  12. // This type covers both shapes so we can unwrap safely.
  13. type NestedBlockEntry = {
  14. spaceId?: string;
  15. value: { value: Block; role: string };
  16. };
  17. function normalizeRecordMap(recordMap: ExtendedRecordMap): ExtendedRecordMap {
  18. const block = { ...recordMap.block };
  19. for (const [id, entry] of Object.entries(block)) {
  20. const nested = entry as unknown as NestedBlockEntry;
  21. if (nested?.value?.value !== undefined && nested?.value?.role !== undefined) {
  22. block[id] = nested.value;
  23. }
  24. }
  25. return { ...recordMap, block };
  26. }
  27. export const getPageContent = cache(async (pageId: string) => {
  28. const raw = await notion.getPage(pageId);
  29. const recordMap = normalizeRecordMap(raw);
  30. const title = getPageTitle(recordMap);
  31. const blocks = recordMap.block;
  32. return { title, blocks, recordMap };
  33. });
  34. export async function getAllBlogPosts(pageId: string) {
  35. const recordMap = normalizeRecordMap(await notion.getPage(pageId));
  36. const blocks = recordMap.block;
  37. let blogPosts: Blog[] = [];
  38. Object.entries(blocks).forEach(([key, value]) => {
  39. const block = value.value;
  40. if (
  41. key === notionBlogConfig.blogParentId ||
  42. block?.type !== "page" ||
  43. !block?.properties?.title
  44. ) {
  45. return;
  46. }
  47. blogPosts.push({
  48. id: key,
  49. block,
  50. pageCover: block.format?.page_cover,
  51. title: block.properties.title[0][0],
  52. createdAt: block.created_time ? new Date(block.created_time) : null,
  53. lastEditedAt: block.last_edited_time
  54. ? new Date(block.last_edited_time)
  55. : null,
  56. description: block.properties?.["\\u2O5F"]?.[0]?.[0] ?? "",
  57. });
  58. });
  59. blogPosts.sort(
  60. (a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0),
  61. );
  62. return blogPosts;
  63. }
  64. /** Extract a plain-text excerpt from a Notion recordMap (first ~160 chars). */
  65. export function extractDescription(recordMap: ExtendedRecordMap): string {
  66. const blocks = Object.values(recordMap.block);
  67. for (const block of blocks) {
  68. const value = block?.value;
  69. if (!value) continue;
  70. if (value.type !== "text" && value.type !== "quote") continue;
  71. const text = value.properties?.title
  72. ?.map((chunk: unknown[]) => chunk[0])
  73. .join("")
  74. .trim();
  75. if (text && text.length > 0) {
  76. return text.length > 160 ? text.slice(0, 157) + "..." : text;
  77. }
  78. }
  79. return "";
  80. }
  81. export const customMapImageUrl = (url: string, block: Block): string => {
  82. if (!url) {
  83. throw new Error("URL can't be empty");
  84. }
  85. if (url.startsWith("data:")) {
  86. return url;
  87. } // more recent versions of notion don't proxy unsplash images
  88. if (url.startsWith("https://images.unsplash.com")) {
  89. return url;
  90. }
  91. try {
  92. const u = new URL(url);
  93. if (
  94. u.pathname.startsWith("/secure.notion-static.com") &&
  95. u.hostname.endsWith(".amazonaws.com")
  96. ) {
  97. if (
  98. u.searchParams.has("X-Amz-Credential") &&
  99. u.searchParams.has("X-Amz-Signature") &&
  100. u.searchParams.has("X-Amz-Algorithm")
  101. ) {
  102. // if the URL is already signed, then use it as-is
  103. url = u.origin + u.pathname;
  104. }
  105. }
  106. } catch {
  107. // ignore invalid urls
  108. }
  109. if (url.startsWith("/images")) {
  110. url = `https://www.notion.so${url}`;
  111. }
  112. url = `https://www.notion.so${
  113. url.startsWith("/image") ? url : `/image/${encodeURIComponent(url)}`
  114. }`;
  115. const notionImageUrlV2 = new URL(url);
  116. let table = block.parent_table === "space" ? "block" : block.parent_table;
  117. if (table === "collection" || table === "team") {
  118. table = "block";
  119. }
  120. notionImageUrlV2.searchParams.set("table", table);
  121. notionImageUrlV2.searchParams.set("id", block.id);
  122. notionImageUrlV2.searchParams.set("cache", "v2");
  123. url = notionImageUrlV2.toString();
  124. return url;
  125. };