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

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