notion.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { cache } from "react";
  2. import { NotionAPI } from "notion-client";
  3. import { Block } 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. export const getPageContent = cache(async (pageId: string) => {
  9. const recordMap = await notion.getPage(pageId);
  10. const title = getPageTitle(recordMap);
  11. const blocks = recordMap.block;
  12. return { title, blocks, recordMap };
  13. });
  14. export async function getAllBlogPosts(pageId: string) {
  15. const recordMap = await notion.getPage(pageId);
  16. const blocks = recordMap.block;
  17. let blogPosts: Blog[] = [];
  18. Object.entries(blocks).map(([key, value]) => {
  19. if (key !== notionBlogConfig.blogParentId) {
  20. blogPosts.push({
  21. id: key,
  22. block: value.value,
  23. pageCover: value.value.format?.page_cover,
  24. title: value.value.properties?.title[0][0],
  25. createdAt: new Date(value.value.created_time),
  26. });
  27. }
  28. });
  29. // Sort by newest first
  30. blogPosts.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
  31. return blogPosts;
  32. }
  33. export const customMapImageUrl = (url: string, block: Block): string => {
  34. if (!url) {
  35. throw new Error("URL can't be empty");
  36. }
  37. if (url.startsWith("data:")) {
  38. return url;
  39. } // more recent versions of notion don't proxy unsplash images
  40. if (url.startsWith("https://images.unsplash.com")) {
  41. return url;
  42. }
  43. try {
  44. const u = new URL(url);
  45. if (
  46. u.pathname.startsWith("/secure.notion-static.com") &&
  47. u.hostname.endsWith(".amazonaws.com")
  48. ) {
  49. if (
  50. u.searchParams.has("X-Amz-Credential") &&
  51. u.searchParams.has("X-Amz-Signature") &&
  52. u.searchParams.has("X-Amz-Algorithm")
  53. ) {
  54. // if the URL is already signed, then use it as-is
  55. url = u.origin + u.pathname;
  56. }
  57. }
  58. } catch {
  59. // ignore invalid urls
  60. }
  61. if (url.startsWith("/images")) {
  62. url = `https://www.notion.so${url}`;
  63. }
  64. url = `https://www.notion.so${
  65. url.startsWith("/image") ? url : `/image/${encodeURIComponent(url)}`
  66. }`;
  67. const notionImageUrlV2 = new URL(url);
  68. let table = block.parent_table === "space" ? "block" : block.parent_table;
  69. if (table === "collection" || table === "team") {
  70. table = "block";
  71. }
  72. notionImageUrlV2.searchParams.set("table", table);
  73. notionImageUrlV2.searchParams.set("id", block.id);
  74. notionImageUrlV2.searchParams.set("cache", "v2");
  75. url = notionImageUrlV2.toString();
  76. return url;
  77. };