Advertisement
Guest User

Untitled

a guest
May 2nd, 2022
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Client } from '@notionhq/client';
  2. import { NotionToMarkdown } from 'notion-to-md';
  3.  
  4. const client = new Client({
  5.   auth: process.env.NOTION_ACCESS_TOKEN,
  6. });
  7.  
  8. const n2m = new NotionToMarkdown({ notionClient: client });
  9.  
  10. export async function getPublishedBlogPosts() {
  11.   const database = process.env.NOTION_BLOG_DATABASE_ID ?? '';
  12.   // list blog posts
  13.   const response = await client.databases.query({
  14.     database_id: database,
  15.     filter: {
  16.       property: 'Published',
  17.       checkbox: {
  18.         equals: true,
  19.       },
  20.     },
  21.     sorts: [
  22.       {
  23.         property: 'Updated',
  24.         direction: 'descending',
  25.       },
  26.     ],
  27.   });
  28.  
  29.   return Promise.all(
  30.     response.results.map((res) => {
  31.       return pageToPostTransformer(res);
  32.     }),
  33.   );
  34. }
  35.  
  36. export async function getSingleBlogPost(slug) {
  37.   const database = process.env.NOTION_BLOG_DATABASE_ID ?? '';
  38.  
  39.   // list of blog posts
  40.   const response = await client.databases.query({
  41.     database_id: database,
  42.     filter: {
  43.       property: 'Slug',
  44.       formula: {
  45.         text: {
  46.           equals: slug, // slug
  47.         },
  48.       },
  49.       // add option for tags in the future
  50.     },
  51.     sorts: [
  52.       {
  53.         property: 'Updated',
  54.         direction: 'descending',
  55.       },
  56.     ],
  57.   });
  58.  
  59.   if (!response.results[0]) {
  60.     throw 'No results available';
  61.   }
  62.  
  63.   const page = response.results[0];
  64.   const mdBlocks = await n2m.pageToMarkdown(page.id);
  65.   const post = await pageToPostTransformer(page);
  66.   const markdown = n2m.toMarkdownString(mdBlocks);
  67.  
  68.   return {
  69.     post,
  70.     markdown,
  71.   };
  72. }
  73.  
  74. export async function pageToPostTransformer(page) {
  75.   let cover = page.cover.type;
  76.   switch (cover) {
  77.     case 'file':
  78.       cover = page.cover.file;
  79.       break;
  80.     case 'external':
  81.       cover = page.cover.external.url;
  82.       break;
  83.     default:
  84.       // Add default cover image if you want...
  85.       cover = '';
  86.   }
  87.  
  88.   return {
  89.     id: page.id,
  90.     cover: cover,
  91.     title: page.properties.Name.title[0].plain_text,
  92.     tags: page.properties.Tags.multi_select,
  93.     description: page.properties.Description.rich_text[0].plain_text,
  94.     date: page.properties.Updated.last_edited_time,
  95.     slug: page.properties.Slug.formula.string,
  96.   };
  97. }
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement