notion.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { getPageTitle } from "notion-utils";
  2. import { NotionAPI } from "notion-client";
  3. import { Block } from "notion-types";
  4. const notion = new NotionAPI();
  5. export async function getPageContent(pageId: string) {
  6. const recordMap = await notion.getPage(pageId);
  7. const title = getPageTitle(recordMap);
  8. const blocks = recordMap.block;
  9. return { title, blocks, recordMap };
  10. }
  11. export const customMapImageUrl = (url: string, block: Block): string => {
  12. if (!url) {
  13. throw new Error("URL can't be empty");
  14. }
  15. if (url.startsWith("data:")) {
  16. return url;
  17. } // more recent versions of notion don't proxy unsplash images
  18. if (url.startsWith("https://images.unsplash.com")) {
  19. return url;
  20. }
  21. try {
  22. const u = new URL(url);
  23. if (
  24. u.pathname.startsWith("/secure.notion-static.com") &&
  25. u.hostname.endsWith(".amazonaws.com")
  26. ) {
  27. if (
  28. u.searchParams.has("X-Amz-Credential") &&
  29. u.searchParams.has("X-Amz-Signature") &&
  30. u.searchParams.has("X-Amz-Algorithm")
  31. ) {
  32. // if the URL is already signed, then use it as-is
  33. url = u.origin + u.pathname;
  34. }
  35. }
  36. } catch {
  37. // ignore invalid urls
  38. }
  39. if (url.startsWith("/images")) {
  40. url = `https://www.notion.so${url}`;
  41. }
  42. url = `https://www.notion.so${
  43. url.startsWith("/image") ? url : `/image/${encodeURIComponent(url)}`
  44. }`;
  45. const notionImageUrlV2 = new URL(url);
  46. let table = block.parent_table === "space" ? "block" : block.parent_table;
  47. if (table === "collection" || table === "team") {
  48. table = "block";
  49. }
  50. notionImageUrlV2.searchParams.set("table", table);
  51. notionImageUrlV2.searchParams.set("id", block.id);
  52. notionImageUrlV2.searchParams.set("cache", "v2");
  53. url = notionImageUrlV2.toString();
  54. return url;
  55. };