notion.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import { cache } from "react";
  2. import { NotionAPI } from "notion-client";
  3. import { Block, ExtendedRecordMap } from "notion-types";
  4. import { getBlockValue, getPageTitle } from "notion-utils";
  5. import { Blog } from "@/types/blog";
  6. import { notionBlogConfig } from "@/config/site";
  7. // notion-client 8 sends a browser-acceptable User-Agent and understands Notion's
  8. // nested { value: { value, role } } block entries, so no workarounds are needed.
  9. const notion = new NotionAPI();
  10. /** A block's value, whether Notion returned it flat or nested. */
  11. export const blockOf = (entry: ExtendedRecordMap["block"][string] | undefined) =>
  12. getBlockValue<Block>(entry);
  13. export const getPageContent = cache(async (pageId: string) => {
  14. const recordMap = await notion.getPage(pageId);
  15. const title = getPageTitle(recordMap);
  16. const blocks = recordMap.block;
  17. return { title, blocks, recordMap };
  18. });
  19. export async function getAllBlogPosts(pageId: string) {
  20. const recordMap = await notion.getPage(pageId);
  21. const blocks = recordMap.block;
  22. const blogPosts: Blog[] = [];
  23. Object.entries(blocks).forEach(([key, value]) => {
  24. const block = blockOf(value);
  25. if (
  26. !block ||
  27. key === notionBlogConfig.blogParentId ||
  28. block.type !== "page" ||
  29. !block.properties?.title
  30. ) {
  31. return;
  32. }
  33. blogPosts.push({
  34. id: key,
  35. block,
  36. pageCover: block.format?.page_cover ?? "",
  37. title: block.properties.title[0][0],
  38. createdAt: block.created_time ? new Date(block.created_time) : null,
  39. lastEditedAt: block.last_edited_time
  40. ? new Date(block.last_edited_time)
  41. : null,
  42. description:
  43. (block.properties as Record<string, unknown[][]>)?.["\\u2O5F"]?.[0]?.[0]?.toString() ?? "",
  44. });
  45. });
  46. blogPosts.sort(
  47. (a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0),
  48. );
  49. return blogPosts;
  50. }
  51. /** Extract a plain-text excerpt from a Notion recordMap (first ~160 chars). */
  52. export function extractDescription(recordMap: ExtendedRecordMap): string {
  53. const blocks = Object.values(recordMap.block);
  54. for (const block of blocks) {
  55. const value = blockOf(block);
  56. if (!value) continue;
  57. if (value.type !== "text" && value.type !== "quote") continue;
  58. const text = value.properties?.title
  59. ?.map((chunk: unknown[]) => chunk[0])
  60. .join("")
  61. .trim();
  62. if (text && text.length > 0) {
  63. return text.length > 160 ? text.slice(0, 157) + "..." : text;
  64. }
  65. }
  66. return "";
  67. }
  68. export const customMapImageUrl = (url: string, block: Block): string => {
  69. if (!url) {
  70. throw new Error("URL can't be empty");
  71. }
  72. if (url.startsWith("data:")) {
  73. return url;
  74. } // more recent versions of notion don't proxy unsplash images
  75. if (url.startsWith("https://images.unsplash.com")) {
  76. return url;
  77. }
  78. try {
  79. const u = new URL(url);
  80. if (
  81. u.pathname.startsWith("/secure.notion-static.com") &&
  82. u.hostname.endsWith(".amazonaws.com")
  83. ) {
  84. if (
  85. u.searchParams.has("X-Amz-Credential") &&
  86. u.searchParams.has("X-Amz-Signature") &&
  87. u.searchParams.has("X-Amz-Algorithm")
  88. ) {
  89. // if the URL is already signed, then use it as-is
  90. url = u.origin + u.pathname;
  91. }
  92. }
  93. } catch {
  94. // ignore invalid urls
  95. }
  96. if (url.startsWith("/images")) {
  97. url = `https://www.notion.so${url}`;
  98. }
  99. url = `https://www.notion.so${
  100. url.startsWith("/image") ? url : `/image/${encodeURIComponent(url)}`
  101. }`;
  102. const notionImageUrlV2 = new URL(url);
  103. let table = block.parent_table === "space" ? "block" : block.parent_table;
  104. if (table === "collection" || table === "team") {
  105. table = "block";
  106. }
  107. notionImageUrlV2.searchParams.set("table", table);
  108. notionImageUrlV2.searchParams.set("id", block.id);
  109. notionImageUrlV2.searchParams.set("cache", "v2");
  110. url = notionImageUrlV2.toString();
  111. return url;
  112. };
  113. const NOTION_HOST =
  114. /(^|\.)(notion\.so|notion\.com|notion-static\.com|notionusercontent\.com|amazonaws\.com)$/;
  115. /**
  116. * A page cover's URL. Covers linked from other sites (Wikimedia, Unsplash, ...)
  117. * load from where they live: Notion's image proxy gets rate-limited by some of
  118. * them. Covers uploaded to Notion still go through Notion.
  119. */
  120. export const coverImageUrl = (url: string, block: Block): string => {
  121. try {
  122. const { protocol, hostname } = new URL(url);
  123. if (protocol === "https:" && !NOTION_HOST.test(hostname)) return url;
  124. } catch {
  125. // A Notion path such as /images/page-cover/..., handled below.
  126. }
  127. return customMapImageUrl(url, block);
  128. };