notion.ts 2.5 KB

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