NotionAPI调整

This commit is contained in:
tangly1024
2021-10-18 17:09:35 +08:00
parent 7480cef805
commit c25fd702d1
9 changed files with 86 additions and 74 deletions

View File

@@ -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'
)}
>
<span

View File

@@ -6,15 +6,27 @@ import { defaultMapImageUrl } from 'react-notion-x'
import { getDataFromCache, setDataToCache } from '@/lib/cache/cache_manager'
import { getPostBlocks } from '@/lib/notion/getPostBlocks'
export async function getAllPosts () {
export async function getAllPosts ({ from }) {
// 尝试从缓存获取
const data = await getDataFromCache('posts_list')
if (data) {
return data
if (data) return data
const posts = await getPostsFromNotionAPI({ from })
// 存入缓存
if (posts) {
await setDataToCache('posts_list', posts)
}
return posts || []
}
/**
* 调用NotionAPI获取所有文章列表
* @returns {Promise<JSX.Element|null|*>}
*/
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否则取内容图片

View File

@@ -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 => {

View File

@@ -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)
}

View File

@@ -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)
// 获取推荐文章

View File

@@ -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)

View File

@@ -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'
)

View File

@@ -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'
)

View File

@@ -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'
)