标签加入颜色
This commit is contained in:
tangly1024
2021-11-30 17:48:57 +08:00
parent f5739dc51a
commit 1e24789a24
16 changed files with 217 additions and 156 deletions

View File

@@ -1,12 +1,18 @@
import { getCacheFromFile, setCacheToFile } from '@/lib/cache/local_file_cache'
import { getCacheFromMemory, setCacheToMemory } from '@/lib/cache/memory_cache'
import BLOG from '@/blog.config'
// 关闭本地缓存
const enableCache = true
/**
* 为减少频繁接口请求notion数据将被缓存
* @param {*} key
* @returns
* @param {*} key
* @returns
*/
export async function getDataFromCache (key) {
if (!enableCache) {
return null
}
let dataFromCache
if (BLOG.isProd) {
dataFromCache = await getCacheFromMemory(key)
@@ -17,6 +23,9 @@ export async function getDataFromCache (key) {
}
export async function setDataToCache (key, data) {
if (!enableCache) {
return
}
if (BLOG.isProd) {
await setCacheToMemory(key, data)
} else {

View File

@@ -1,73 +1,62 @@
import BLOG from '@/blog.config'
import { idToUuid } from 'notion-utils'
import getAllPageIds from './getAllPageIds'
import getPageProperties from './getPageProperties'
import { defaultMapImageUrl } from 'react-notion-x'
import { getDataFromCache, setDataToCache } from '@/lib/cache/cache_manager'
import { getPostBlocks } from '@/lib/notion/getPostBlocks'
export async function getAllPosts ({ from }) {
// 尝试从缓存获取
const data = await getDataFromCache('posts_list')
if (data) return data
const posts = await getPostsFromNotionAPI({ from })
// 存入缓存
if (posts) {
await setDataToCache('posts_list', posts)
}
return posts || []
}
import { getNotionPageData } from '@/lib/notion/getNotionData'
import TagItemMini from '@/components/TagItemMini'
import React from 'react'
/**
* 调用NotionAPI获取所有文章列表
* @returns {Promise<JSX.Element|null|*>}
* 获取所有文章列表
* @param notionPageData
* @param from
* @param includePage 是否包含Page类型
* @returns {Promise<*[]>}
*/
async function getPostsFromNotionAPI ({ from }) {
let id = BLOG.notionPageId
const pageRecordMap = await getPostBlocks(id, from)
if (!pageRecordMap) {
export async function getAllPosts ({ notionPageData, from, includePage = false }) {
if (!notionPageData) {
notionPageData = await getNotionPageData({ from })
}
if (!notionPageData) {
return []
}
id = idToUuid(id)
const collection = Object.values(pageRecordMap.collection)[0]?.value
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
}
const pageBlock = notionPageData.block
const schema = notionPageData.schema
const tagOptions = notionPageData.tagOptions
const collectionQuery = notionPageData.collectionQuery
// 获取每篇文章信息
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
properties.createdTime = new Date(
block[id].value?.created_time
).toString()
properties.lastEditedTime = new Date(
block[id].value?.last_edited_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 ?? []
const properties = (await getPageProperties(id, pageBlock, schema)) || null
const tagItems = properties?.tags?.map(tag => { return { name: tag, color: tagOptions.find(t => t.value === tag).color } }) || ['默认']
properties.createdTime = new Date(pageBlock[id].value?.created_time).toString()
properties.lastEditedTime = new Date(pageBlock[id].value?.last_edited_time).toString()
properties.fullWidth = pageBlock[id].value?.format?.page_full_width ?? false
properties.page_cover = getPostCover(id, pageBlock) ?? BLOG.defaultImgCover
properties.content = pageBlock[id].value?.content ?? []
properties.tagItems = tagItems
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')
)
if (includePage) {
return (
post.title && post.slug &&
post?.status?.[0] === 'Published' &&
(post?.type?.[0] === 'Post' || post?.type?.[0] === 'Page')
)
} else {
return (
post.title && post.slug &&
post?.status?.[0] === 'Published' &&
(post?.type?.[0] === 'Post')
)
}
})
// Sort by date
@@ -82,30 +71,10 @@ async function getPostsFromNotionAPI ({ from }) {
}
// 从Block获取封面图;优先取PageCover否则取内容图片
function getPostCover (id, block, pageRecordMap) {
function getPostCover (id, block) {
const pageCover = block[id].value?.format?.page_cover
if (pageCover) {
if (pageCover.startsWith('/')) return 'https://www.notion.so' + pageCover
if (pageCover.startsWith('http')) return defaultMapImageUrl(pageCover, block[id].value)
}
}
// 取文章的第一个图片内容作为封面
function getContentFirstImage (id, block, pageRecordMap) {
const pageBlock = block[id]?.value
const contentBlockId = pageBlock?.content?.find((blockId) => {
const block = pageRecordMap.block[blockId]?.value
if (block?.type === 'image') {
return true
}
})
if (contentBlockId) {
const contentBlock = pageRecordMap.block[contentBlockId]?.value
const source = contentBlock.properties?.source?.[0]?.[0] ??
contentBlock.format?.display_source
return defaultMapImageUrl(source, contentBlock)
}
return ''
}

View File

@@ -3,9 +3,10 @@
* 获取所有文章的标签
* @param allPosts
* @param sliceCount 默认截取数量为12若为0则返回全部
* @param tagOptions tags的下拉选项
* @returns {Promise<{}|*[]>}
*/
export async function getAllTags (allPosts, sliceCount = 12) {
export async function getAllTags ({ allPosts, sliceCount = 12, tagOptions }) {
if (!allPosts) {
return []
}
@@ -24,8 +25,9 @@ export async function getAllTags (allPosts, sliceCount = 12) {
})
// 按照标签数量排序
const list = Object.keys(tagObj).map((index) => {
return { name: index, count: tagObj[index] }
const list = Object.keys(tagObj).map((tag) => {
const color = tagOptions.find(option => option.value === tag).color
return { name: tag, count: tagObj[tag], color }
})
list.sort((a, b) => b.count - a.count)
if (sliceCount) {

View File

@@ -0,0 +1,66 @@
import BLOG from '@/blog.config'
import { idToUuid } from 'notion-utils'
import { getDataFromCache, setDataToCache } from '@/lib/cache/cache_manager'
import { getPostBlocks } from '@/lib/notion/getPostBlocks'
/**
* 获取指定notion的collection数据
* @param pageId
* @param from 请求来源
* @returns {Promise<JSX.Element|*|*[]>}
*/
export async function getNotionPageData ({ pageId = BLOG.notionPageId, from }) {
// 尝试从缓存获取
const data = await getDataFromCache('page_record_map_' + pageId)
if (data) return data
const pageRecordMap = await getPageRecordMapByNotionAPI({ pageId, from })
// 存入缓存
if (pageRecordMap) {
await setDataToCache('page_record_map', pageRecordMap)
}
return pageRecordMap
}
/**
* 获取标签选项
* @param schema
* @returns {undefined}
*/
function getTagOptions (schema) {
const tagSchema = Object.values(schema).find(e => e.name === 'tags')
return tagSchema?.options || {}
}
/**
* 调用NotionAPI获取Page数据
* @returns {Promise<JSX.Element|null|*>}
*/
async function getPageRecordMapByNotionAPI ({ pageId, from }) {
const pageRecordMap = await getPostBlocks(pageId, from)
if (!pageRecordMap) {
return []
}
pageId = idToUuid(pageId)
const collection = Object.values(pageRecordMap.collection)[0]?.value
const collectionQuery = pageRecordMap.collection_query
const block = pageRecordMap.block
const schema = collection?.schema
const rawMetadata = block[pageId].value
const tagOptions = getTagOptions(schema)
// Check Type Page-Database和Inline-Database
if (rawMetadata?.type !== 'collection_view_page' && rawMetadata?.type !== 'collection_view') {
console.warn(`pageId "${pageId}" is not a database`)
return null
}
return {
collection,
collectionQuery,
block,
schema,
tagOptions,
rawMetadata
}
}

View File

@@ -10,11 +10,11 @@ export async function getPostBlocks (id, from) {
const authToken = BLOG.notionAccessToken || null
const api = new NotionAPI({ authToken })
try {
console.log(id, '向Notion请求数据:', from)
console.log('[请求API]:', `from:${from}`, `id:${id}`)
pageBlock = await api.getPage(id)
console.log(id, '请求成功:', from)
console.log('[请求成功]', `from:${from}`, `id:${id}`)
} catch (error) {
console.error(id, '请求失败:', from, error)
console.error('[请求失败]', `from:${from}`, `id:${id}`, `error:${error}`)
return null
}