forked from tangly1024/NotionNext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetSiteData.js
executable file
·594 lines (549 loc) · 15.2 KB
/
getSiteData.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import BLOG from '@/blog.config'
import { getDataFromCache, setDataToCache } from '@/lib/cache/cache_manager'
import { getAllCategories } from '@/lib/notion/getAllCategories'
import getAllPageIds from '@/lib/notion/getAllPageIds'
import { getAllTags } from '@/lib/notion/getAllTags'
import { getConfigMapFromConfigPage } from '@/lib/notion/getNotionConfig'
import getPageProperties, {
adjustPageProperties
} from '@/lib/notion/getPageProperties'
import { fetchInBatches, getPage } from '@/lib/notion/getPostBlocks'
import { compressImage, mapImgUrl } from '@/lib/notion/mapImage'
import { deepClone } from '@/lib/utils'
import { idToUuid } from 'notion-utils'
import { siteConfig } from '../config'
import { extractLangId, extractLangPrefix, getShortId } from '../utils/pageId'
export { getAllTags } from '../notion/getAllTags'
export { getPost } from '../notion/getNotionPost'
export { getPage as getPostBlocks } from '../notion/getPostBlocks'
/**
* 获取博客数据; 基于Notion实现
* @param {*} pageId
* @param {*} from
* @param {*} locale 语言 zh|en|jp 等等
* @returns
*
*/
export async function getGlobalData({
pageId = BLOG.NOTION_PAGE_ID,
from,
locale
}) {
// 获取站点数据 , 如果pageId有逗号隔开则分次取数据
const siteIds = pageId?.split(',') || []
let data = EmptyData(pageId)
try {
for (let index = 0; index < siteIds.length; index++) {
const siteId = siteIds[index]
const id = extractLangId(siteId)
const prefix = extractLangPrefix(siteId)
// 第一个id站点默认语言
if (index === 0 || locale === prefix) {
data = await getNotionPageData({
pageId: id,
from
})
}
}
} catch (error) {
console.error('异常', error)
}
return data
}
/**
* 获取指定notion的collection数据
* @param pageId
* @param from 请求来源
* @returns {Promise<JSX.Element|*|*[]>}
*/
export async function getNotionPageData({ pageId, from }) {
// 尝试从缓存获取
const cacheKey = 'page_block_' + pageId
let data = await getDataFromCache(cacheKey)
if (data && data.pageIds?.length > 0) {
// console.log('[API<<--缓存]', `from:${from}`, `root-page-id:${pageId}`)
// return data
} else {
// 从接口读取
data = await getDataBaseInfoByNotionAPI({ pageId, from })
// 存入缓存
if (data) {
await setDataToCache(cacheKey, data)
}
}
// 返回给前端的数据做处理
return handleDataBeforeReturn(deepClone(data))
}
/**
* 返回给浏览器前端的数据处理
* 适当脱敏
* 减少体积
* 其它处理
* @param {*} db
*/
function handleDataBeforeReturn(db) {
// 清理多余数据
delete db.block
delete db.schema
delete db.rawMetadata
delete db.pageIds
delete db.viewIds
delete db.collection
delete db.collectionQuery
delete db.collectionId
delete db.collectionView
// 清理多余的块
if (db?.notice) {
db.notice = cleanBlock(db?.notice)
delete db.notice?.id
}
db.tagOptions = cleanIds(db?.tagOptions)
db.categoryOptions = cleanIds(db?.categoryOptions)
db.customMenu = cleanIds(db?.customMenu)
// db.latestPosts = shortenIds(db?.latestPosts)
db.allNavPages = shortenIds(db?.allNavPages)
// db.allPages = cleanBlocks(db?.allPages)
return db
}
/**
* 清理一组数据的id
* @param {*} items
* @returns
*/
function shortenIds(items) {
if (items && Array.isArray(items)) {
return deepClone(
items.map(item => {
item.short_id = getShortId(item.id)
delete item.id
return item
})
)
}
return items
}
/**
* 清理一组数据的id
* @param {*} items
* @returns
*/
function cleanIds(items) {
if (items && Array.isArray(items)) {
return deepClone(
items.map(item => {
delete item.id
return item
})
)
}
return items
}
/**
* 清理block数据
*/
function cleanBlock(item) {
const post = deepClone(item)
const pageBlock = post?.blockMap?.block
// delete post?.id
// delete post?.blockMap?.collection
if (pageBlock) {
for (const i in pageBlock) {
pageBlock[i] = cleanBlock(pageBlock[i])
delete pageBlock[i]?.role
delete pageBlock[i]?.value?.version
delete pageBlock[i]?.value?.created_by_table
delete pageBlock[i]?.value?.created_by_id
delete pageBlock[i]?.value?.last_edited_by_table
delete pageBlock[i]?.value?.last_edited_by_id
delete pageBlock[i]?.value?.space_id
delete pageBlock[i]?.value?.version
delete pageBlock[i]?.value?.format?.copied_from_pointer
delete pageBlock[i]?.value?.format?.block_locked_by
delete pageBlock[i]?.value?.parent_table
delete pageBlock[i]?.value?.copied_from_pointer
delete pageBlock[i]?.value?.copied_from
delete pageBlock[i]?.value?.created_by_table
delete pageBlock[i]?.value?.created_by_id
delete pageBlock[i]?.value?.last_edited_by_table
delete pageBlock[i]?.value?.last_edited_by_id
delete pageBlock[i]?.value?.permissions
delete pageBlock[i]?.value?.alive
}
}
return post
}
/**
* 获取最新文章 根据最后修改时间倒序排列
* @param {*}} param0
* @returns
*/
function getLatestPosts({ allPages, from, latestPostCount }) {
const allPosts = allPages?.filter(
page => page.type === 'Post' && page.status === 'Published'
)
const latestPosts = Object.create(allPosts).sort((a, b) => {
const dateA = new Date(a?.lastEditedDate || a?.publishDate)
const dateB = new Date(b?.lastEditedDate || b?.publishDate)
return dateB - dateA
})
return latestPosts.slice(0, latestPostCount)
}
/**
* 获取用户自定义单页菜单
* 旧版本,不读取Menu菜单,而是读取type=Page生成菜单
* @param notionPageData
* @returns {Promise<[]|*[]>}
*/
function getCustomNav({ allPages }) {
const customNav = []
if (allPages && allPages.length > 0) {
allPages.forEach(p => {
p.to = p.slug
customNav.push({
icon: p.icon || null,
name: p.title,
href: p.href,
target: p.target,
show: true
})
})
}
return customNav
}
/**
* 获取自定义菜单
* @param {*} allPages
* @returns
*/
function getCustomMenu({ collectionData, NOTION_CONFIG }) {
const menuPages = collectionData.filter(
post =>
post.status === 'Published' &&
(post?.type === BLOG.NOTION_PROPERTY_NAME.type_menu ||
post?.type === BLOG.NOTION_PROPERTY_NAME.type_sub_menu)
)
const menus = []
if (menuPages && menuPages.length > 0) {
menuPages.forEach(e => {
e.show = true
if (e.type === BLOG.NOTION_PROPERTY_NAME.type_menu) {
menus.push(e)
} else if (e.type === BLOG.NOTION_PROPERTY_NAME.type_sub_menu) {
const parentMenu = menus[menus.length - 1]
if (parentMenu) {
if (parentMenu.subMenus) {
parentMenu.subMenus.push(e)
} else {
parentMenu.subMenus = [e]
}
}
}
})
}
return menus
}
/**
* 获取标签选项
* @param schema
* @returns {undefined}
*/
function getTagOptions(schema) {
if (!schema) return {}
const tagSchema = Object.values(schema).find(
e => e.name === BLOG.NOTION_PROPERTY_NAME.tags
)
return tagSchema?.options || []
}
/**
* 获取分类选项
* @param schema
* @returns {{}|*|*[]}
*/
function getCategoryOptions(schema) {
if (!schema) return {}
const categorySchema = Object.values(schema).find(
e => e.name === BLOG.NOTION_PROPERTY_NAME.category
)
return categorySchema?.options || []
}
/**
* 站点信息
* @param notionPageData
* @param from
* @returns {Promise<{title,description,pageCover,icon}>}
*/
function getSiteInfo({ collection, block, NOTION_CONFIG }) {
const defaultTitle = NOTION_CONFIG?.TITLE || BLOG.TITLE
const defaultDescription = NOTION_CONFIG?.DESCRIPTION || BLOG.DESCRIPTION
const defaultPageCover =
NOTION_CONFIG?.HOME_BANNER_IMAGE || BLOG.HOME_BANNER_IMAGE
const defaultIcon = NOTION_CONFIG?.AVATAR || BLOG.AVATAR
const defaultLink = NOTION_CONFIG?.LINK || BLOG.LINK
if (!collection && !block) {
return {
title: defaultTitle,
description: defaultDescription,
pageCover: defaultPageCover,
icon: defaultIcon,
link: defaultLink
}
}
const title = collection?.name?.[0][0] || defaultTitle
const description = collection?.description
? Object.assign(collection).description[0][0]
: defaultDescription
const pageCover = collection?.cover
? mapImgUrl(collection?.cover, collection, 'collection')
: defaultPageCover
// 用户头像压缩一下
let icon = compressImage(
collection?.icon
? mapImgUrl(collection?.icon, collection, 'collection')
: defaultIcon
)
// 站点网址
const link = NOTION_CONFIG?.LINK || defaultLink
// 站点图标不能是emoji
const emojiPattern = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g
if (!icon || emojiPattern.test(icon)) {
icon = defaultIcon
}
return { title, description, pageCover, icon, link }
}
/**
* 获取导航用的精减文章列表
* gitbook主题用到,只保留文章的标题分类标签分类信息,精减掉摘要密码日期等数据
* 导航页面的条件,必须是Posts
* @param {*} param0
*/
export function getNavPages({ allPages }) {
const allNavPages = allPages?.filter(post => {
return (
post &&
post?.slug &&
post?.type === 'Post' &&
post?.status === 'Published'
)
})
return allNavPages.map(item => ({
id: item.id,
title: item.title || '',
pageCoverThumbnail: item.pageCoverThumbnail || '',
category: item.category || null,
tags: item.tags || null,
summary: item.summary || null,
slug: item.slug,
href: item.href,
pageIcon: item.pageIcon || '',
lastEditedDate: item.lastEditedDate,
publishDate: item.publishDate,
ext: item.ext || {}
}))
}
/**
* 获取公告
*/
async function getNotice(post) {
if (!post) {
return null
}
post.blockMap = await getPage(post.id, 'data-notice')
return post
}
// 没有数据时返回
const EmptyData = pageId => {
const empty = {
notice: null,
siteInfo: getSiteInfo({}),
allPages: [
{
id: 1,
title: `无法获取Notion数据,请检查Notion_ID: \n 当前 ${pageId}`,
summary:
'访问文档获取帮助→ https://tangly1024.com/article/vercel-deploy-notion-next',
status: 'Published',
type: 'Post',
slug: '13a171332816461db29d50e9f575b00d',
pageCoverThumbnail: BLOG.HOME_BANNER_IMAGE,
date: {
start_date: '2023-04-24',
lastEditedDay: '2023-04-24',
tagItems: []
}
}
],
allNavPages: [],
collection: [],
collectionQuery: {},
collectionId: null,
collectionView: {},
viewIds: [],
block: {},
schema: {},
tagOptions: [],
categoryOptions: [],
rawMetadata: {},
customNav: [],
customMenu: [],
postCount: 1,
pageIds: [],
latestPosts: []
}
return empty
}
/**
* 调用NotionAPI获取Page数据
* @returns {Promise<JSX.Element|null|*>}
*/
async function getDataBaseInfoByNotionAPI({ pageId, from }) {
console.log('[Fetching Data]', pageId, from)
const pageRecordMap = await getPage(pageId, from)
if (!pageRecordMap) {
console.error('can`t get Notion Data ; Which id is: ', pageId)
return {}
}
pageId = idToUuid(pageId)
let block = pageRecordMap.block || {}
const rawMetadata = block[pageId]?.value
// Check Type Page-Database和Inline-Database
if (
rawMetadata?.type !== 'collection_view_page' &&
rawMetadata?.type !== 'collection_view'
) {
console.error(`pageId "${pageId}" is not a database`)
return EmptyData(pageId)
}
const collection = Object.values(pageRecordMap.collection)[0]?.value || {}
const collectionId = rawMetadata?.collection_id
const collectionQuery = pageRecordMap.collection_query
const collectionView = pageRecordMap.collection_view
const schema = collection?.schema
const viewIds = rawMetadata?.view_ids
const collectionData = []
const pageIds = getAllPageIds(
collectionQuery,
collectionId,
collectionView,
viewIds
)
if (pageIds?.length === 0) {
console.error(
'获取到的文章列表为空,请检查notion模板',
collectionQuery,
collection,
collectionView,
viewIds,
pageRecordMap
)
} else {
// console.log('有效Page数量', pageIds?.length)
}
// 抓取主数据库最多抓取1000个blocks,溢出的数block这里统一抓取一遍
const blockIdsNeedFetch = []
for (let i = 0; i < pageIds.length; i++) {
const id = pageIds[i]
const value = block[id]?.value
if (!value) {
blockIdsNeedFetch.push(id)
}
}
const fetchedBlocks = await fetchInBatches(blockIdsNeedFetch)
block = Object.assign({}, block, fetchedBlocks)
// 获取每篇文章基础数据
for (let i = 0; i < pageIds.length; i++) {
const id = pageIds[i]
const value = block[id]?.value || fetchedBlocks[id]?.value
const properties =
(await getPageProperties(
id,
value,
schema,
null,
getTagOptions(schema)
)) || null
if (properties) {
collectionData.push(properties)
}
}
// 站点配置优先读取配置表格,否则读取blog.config.js 文件
const NOTION_CONFIG = (await getConfigMapFromConfigPage(collectionData)) || {}
// 处理每一条数据的字段
collectionData.forEach(function (element) {
adjustPageProperties(element, NOTION_CONFIG)
})
// 站点基础信息
const siteInfo = getSiteInfo({ collection, block, pageId })
// 文章计数
let postCount = 0
// 查找所有的Post和Page
const allPages = collectionData.filter(post => {
if (post?.type === 'Post' && post.status === 'Published') {
postCount++
}
return (
post &&
post?.slug &&
// !post?.slug?.startsWith('http') &&
(post?.status === 'Invisible' || post?.status === 'Published')
)
})
// Sort by date
if (siteConfig('POSTS_SORT_BY', '', NOTION_CONFIG) === 'date') {
allPages.sort((a, b) => {
return b?.publishDate - a?.publishDate
})
}
const notice = await getNotice(
collectionData.filter(post => {
return (
post &&
post?.type &&
post?.type === 'Notice' &&
post.status === 'Published'
)
})?.[0]
)
// 所有分类
const categoryOptions = getAllCategories({
allPages,
categoryOptions: getCategoryOptions(schema)
})
// 所有标签
const tagOptions = getAllTags({
allPages,
tagOptions: getTagOptions(schema),
NOTION_CONFIG
})
// 旧的菜单
const customNav = getCustomNav({
allPages: collectionData.filter(
post => post?.type === 'Page' && post.status === 'Published'
)
})
// 新的菜单
const customMenu = await getCustomMenu({ collectionData, NOTION_CONFIG })
const latestPosts = getLatestPosts({ allPages, from, latestPostCount: 6 })
const allNavPages = getNavPages({ allPages })
return {
NOTION_CONFIG,
notice,
siteInfo,
allPages,
allNavPages,
collection,
collectionQuery,
collectionId,
collectionView,
viewIds,
block,
schema,
tagOptions,
categoryOptions,
rawMetadata,
customNav,
customMenu,
postCount,
pageIds,
latestPosts
}
}