From c25fd702d16e4afb629ce2e274bdad725f40685b Mon Sep 17 00:00:00 2001 From: tangly1024 Date: Mon, 18 Oct 2021 17:09:35 +0800 Subject: [PATCH] =?UTF-8?q?NotionAPI=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/TocBar.js | 2 +- lib/notion/getAllPosts.js | 98 ++++++++++++++++++++----------------- lib/notion/getAllTags.js | 19 ++++--- lib/notion/getPostBlocks.js | 12 ++++- pages/article/[slug].js | 19 +++---- pages/feed.js | 2 +- pages/index.js | 2 +- pages/page/[page].js | 4 +- pages/tag/[tag].js | 2 +- 9 files changed, 86 insertions(+), 74 deletions(-) diff --git a/components/TocBar.js b/components/TocBar.js index 58d16c15..5bd7bb6f 100644 --- a/components/TocBar.js +++ b/components/TocBar.js @@ -62,7 +62,7 @@ const TocBar = ({ toc }) => { 'notion-table-of-contents-item px-5', `notion-table-of-contents-item-indent-level-${tocItem.indentLevel}`, activeSection === id && - ' font-bold text-black dark:text-white animate__animated animate__pulse' + ' font-bold text-black dark:text-white animate-pulse' )} > } + */ +async function getPostsFromNotionAPI ({ from }) { let id = BLOG.notionPageId - const pageRecordMap = await getPostBlocks(id) + const pageRecordMap = await getPostBlocks(id, from) if (!pageRecordMap) { - return <>获取数据异常 + return [] } id = idToUuid(id) @@ -22,53 +34,49 @@ export async function getAllPosts () { const collectionQuery = pageRecordMap.collection_query const block = pageRecordMap.block const schema = collection?.schema - const rawMetadata = block[id].value // Check Type 兼容Page-Database和Inline-Database if (rawMetadata?.type !== 'collection_view_page' && rawMetadata?.type !== 'collection_view') { console.warn(`pageId "${id}" is not a database`) return null - } else { - // Construct Data - const pageIds = getAllPageIds(collectionQuery) - const data = [] - for (let i = 0; i < pageIds.length; i++) { - const id = pageIds[i] - const properties = (await getPageProperties(id, block, schema)) || null - - // Add fullwidth, createdtime to properties - properties.createdTime = new Date( - block[id].value?.created_time - ).toString() - properties.fullWidth = block[id].value?.format?.page_full_width ?? false - properties.page_cover = getPostCover(id, block, pageRecordMap) ?? getContentFirstImage(id, block, pageRecordMap) - properties.content = block[id].value?.content ?? [] - data.push(properties) - } - // remove all the the items doesn't meet requirements - const posts = data.filter(post => { - return ( - post.title && - post.slug && - post?.status?.[0] === 'Published' && - (post?.type?.[0] === 'Post' || post?.type?.[0] === 'Page') - ) - }) - - // Sort by date - if (BLOG.sortByDate) { - posts.sort((a, b) => { - const dateA = new Date(a?.date?.start_date || a.createdTime) - const dateB = new Date(b?.date?.start_date || b.createdTime) - return dateB - dateA - }) - } - if (posts) { - await setDataToCache('posts_list', posts) - } - return posts } + + // 获取每篇文章信息 + const data = [] + const pageIds = getAllPageIds(collectionQuery) + for (let i = 0; i < pageIds.length; i++) { + const id = pageIds[i] + const properties = (await getPageProperties(id, block, schema)) || null + // Add fullwidth, createdtime to properties + properties.createdTime = new Date( + block[id].value?.created_time + ).toString() + properties.fullWidth = block[id].value?.format?.page_full_width ?? false + properties.page_cover = getPostCover(id, block, pageRecordMap) ?? getContentFirstImage(id, block, pageRecordMap) + properties.content = block[id].value?.content ?? [] + data.push(properties) + } + + // remove all the the items doesn't meet requirements + const posts = data.filter(post => { + return ( + post.title && + post.slug && + post?.status?.[0] === 'Published' && + (post?.type?.[0] === 'Post' || post?.type?.[0] === 'Page') + ) + }) + + // Sort by date + if (BLOG.sortByDate) { + posts.sort((a, b) => { + const dateA = new Date(a?.date?.start_date || a.createdTime) + const dateB = new Date(b?.date?.start_date || b.createdTime) + return dateB - dateA + }) + } + return posts } // 从Block获取封面图;优先取PageCover,否则取内容图片 diff --git a/lib/notion/getAllTags.js b/lib/notion/getAllTags.js index 79704dba..7b2d8a5e 100644 --- a/lib/notion/getAllTags.js +++ b/lib/notion/getAllTags.js @@ -1,15 +1,14 @@ -import { getAllPosts } from './getAllPosts' - -export async function getAllTags (posts) { - if (!posts) { - const response = await getAllPosts() - posts = response.filter( - post => - post.status[0] === 'Published' && post.type[0] === 'Post' && post.tags - ) +/** + * 获取所有文章的标签 + * @param allPosts + * @returns {Promise<{}|*[]>} + */ +export async function getAllTags (allPosts) { + if (!allPosts) { + return [] } - let tags = posts.map(p => p.tags) + let tags = allPosts.map(p => p.tags) tags = [...tags.flat()] const tagObj = {} tags.forEach(tag => { diff --git a/lib/notion/getPostBlocks.js b/lib/notion/getPostBlocks.js index 3f402d54..c9cbfa50 100644 --- a/lib/notion/getPostBlocks.js +++ b/lib/notion/getPostBlocks.js @@ -2,14 +2,22 @@ import BLOG from '@/blog.config' import { NotionAPI } from 'notion-client' import { getDataFromCache, setDataToCache } from '@/lib/cache/cache_manager' -export async function getPostBlocks (id) { +export async function getPostBlocks (id, from) { let pageBlock = await getDataFromCache('page_block_' + id) if (pageBlock) { return pageBlock } const authToken = BLOG.notionAccessToken || null const api = new NotionAPI({ authToken }) - pageBlock = await api.getPage(id) + try { + console.log(id, '向Notion请求数据:', from) + pageBlock = await api.getPage(id) + console.log(id, '请求成功:', from) + } catch (error) { + console.error(id, '请求失败:', from, error) + return null + } + if (pageBlock) { await setDataToCache('page_block_' + id, pageBlock) } diff --git a/pages/article/[slug].js b/pages/article/[slug].js index 86a76189..ed709ae2 100644 --- a/pages/article/[slug].js +++ b/pages/article/[slug].js @@ -164,23 +164,16 @@ const BlogPost = ({ post, blockMap, tags, prev, next }) => { } export async function getStaticPaths () { - // if (BLOG.isProd) { - let posts = await getAllPosts() + let posts = await getAllPosts({ from: 'slug - paths' }) posts = posts.filter(post => post.status[0] === 'Published') return { paths: posts.map(row => `${BLOG.path}/article/${row.slug}`), fallback: true } - // } else { - // return { - // paths: [], - // fallback: true - // } - // } } export async function getStaticProps ({ params: { slug } }) { - let posts = await getAllPosts() + let posts = await getAllPosts({ from: 'slug-props' }) posts = posts.filter(post => post.status[0] === 'Published') const post = posts.find(t => t.slug === slug) if (!post) { @@ -190,8 +183,12 @@ export async function getStaticProps ({ params: { slug } }) { } } - const blockMap = await getPostBlocks(post.id) - post.toc = getPageTableOfContents(post, blockMap) + const blockMap = await getPostBlocks(post.id, 'slug') + if (blockMap) { + post.toc = getPageTableOfContents(post, blockMap) + } else { + post.toc = [] + } posts = posts.filter(post => post.type[0] === 'Post') const tags = await getAllTags(posts) // 获取推荐文章 diff --git a/pages/feed.js b/pages/feed.js index 6ec08c4c..98811da9 100644 --- a/pages/feed.js +++ b/pages/feed.js @@ -3,7 +3,7 @@ import { generateRss } from '@/lib/rss' export async function getServerSideProps ({ res }) { res.setHeader('Content-Type', 'text/xml') - let posts = await getAllPosts() + let posts = await getAllPosts({ from: 'feed' }) posts = posts .filter(post => post.status[0] === 'Published' && post.type[0] === 'Post') .slice(0, 10) diff --git a/pages/index.js b/pages/index.js index d692f2ec..64d80dbc 100644 --- a/pages/index.js +++ b/pages/index.js @@ -5,7 +5,7 @@ import TagsBar from '@/components/TagsBar' import BlogPostListScroll from '@/components/BlogPostListScroll' export async function getStaticProps () { - let posts = await getAllPosts() + let posts = await getAllPosts({ from: 'index' }) posts = posts.filter( post => post.status[0] === 'Published' && post.type[0] === 'Post' ) diff --git a/pages/page/[page].js b/pages/page/[page].js index 318a23fb..a9f62fe1 100644 --- a/pages/page/[page].js +++ b/pages/page/[page].js @@ -19,7 +19,7 @@ const Page = ({ posts, tags, page }) => { } export async function getStaticPaths () { - let posts = await getAllPosts() + let posts = await getAllPosts({ from: 'page-path' }) posts = posts.filter( post => post.status[0] === 'Published' && post.type[0] === 'Post' ) @@ -35,7 +35,7 @@ export async function getStaticPaths () { export async function getStaticProps (context) { const { page } = context.params // Get Current Page No. - let posts = await getAllPosts() + let posts = await getAllPosts({ from: 'page-props' }) posts = posts.filter( post => post.status[0] === 'Published' && post.type[0] === 'Post' ) diff --git a/pages/tag/[tag].js b/pages/tag/[tag].js index 3cde4b61..51207f17 100644 --- a/pages/tag/[tag].js +++ b/pages/tag/[tag].js @@ -20,7 +20,7 @@ export default function Tag ({ tags, posts, currentTag }) { export async function getStaticProps ({ params }) { const currentTag = params.tag - let posts = await getAllPosts() + let posts = await getAllPosts({ from: 'tag-props' }) posts = posts.filter( post => post.status[0] === 'Published' && post.type[0] === 'Post' )