notion.ts 4.4 KB

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