notion.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. return blogPosts;
  29. }
  30. export const customMapImageUrl = (url: string, block: Block): string => {
  31. if (!url) {
  32. throw new Error("URL can't be empty");
  33. }
  34. if (url.startsWith("data:")) {
  35. return url;
  36. } // more recent versions of notion don't proxy unsplash images
  37. if (url.startsWith("https://images.unsplash.com")) {
  38. return url;
  39. }
  40. try {
  41. const u = new URL(url);
  42. if (
  43. u.pathname.startsWith("/secure.notion-static.com") &&
  44. u.hostname.endsWith(".amazonaws.com")
  45. ) {
  46. if (
  47. u.searchParams.has("X-Amz-Credential") &&
  48. u.searchParams.has("X-Amz-Signature") &&
  49. u.searchParams.has("X-Amz-Algorithm")
  50. ) {
  51. // if the URL is already signed, then use it as-is
  52. url = u.origin + u.pathname;
  53. }
  54. }
  55. } catch {
  56. // ignore invalid urls
  57. }
  58. if (url.startsWith("/images")) {
  59. url = `https://www.notion.so${url}`;
  60. }
  61. url = `https://www.notion.so${
  62. url.startsWith("/image") ? url : `/image/${encodeURIComponent(url)}`
  63. }`;
  64. const notionImageUrlV2 = new URL(url);
  65. let table = block.parent_table === "space" ? "block" : block.parent_table;
  66. if (table === "collection" || table === "team") {
  67. table = "block";
  68. }
  69. notionImageUrlV2.searchParams.set("table", table);
  70. notionImageUrlV2.searchParams.set("id", block.id);
  71. notionImageUrlV2.searchParams.set("cache", "v2");
  72. url = notionImageUrlV2.toString();
  73. return url;
  74. };