forked from transitive-bullshit/nextjs-notion-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathget-site-map.ts
78 lines (66 loc) · 1.9 KB
/
get-site-map.ts
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
import { getAllPagesInSpace, uuidToId } from 'notion-utils'
import pMemoize from 'p-memoize'
import * as config from './config'
import * as types from './types'
import { includeNotionIdInUrls } from './config'
import { getCanonicalPageId } from './get-canonical-page-id'
import { notion } from './notion-api'
const uuid = !!includeNotionIdInUrls
export async function getSiteMap(): Promise<types.SiteMap> {
const partialSiteMap = await getAllPages(
config.rootNotionPageId,
config.rootNotionSpaceId
)
return {
site: config.site,
...partialSiteMap
} as types.SiteMap
}
const getAllPages = pMemoize(getAllPagesImpl, {
cacheKey: (...args) => JSON.stringify(args)
})
async function getAllPagesImpl(
rootNotionPageId: string,
rootNotionSpaceId: string
): Promise<Partial<types.SiteMap>> {
const getPage = async (pageId: string, ...args) => {
console.log('\nnotion getPage', uuidToId(pageId))
return notion.getPage(pageId, ...args)
}
const pageMap = await getAllPagesInSpace(
rootNotionPageId,
rootNotionSpaceId,
getPage
)
const canonicalPageMap = Object.keys(pageMap).reduce(
(map, pageId: string) => {
const recordMap = pageMap[pageId]
if (!recordMap) {
throw new Error(`Error loading page "${pageId}"`)
}
const canonicalPageId = getCanonicalPageId(pageId, recordMap, {
uuid
})
if (map[canonicalPageId]) {
// you can have multiple pages in different collections that have the same id
// TODO: we may want to error if neither entry is a collection page
console.warn('error duplicate canonical page id', {
canonicalPageId,
pageId,
existingPageId: map[canonicalPageId]
})
return map
} else {
return {
...map,
[canonicalPageId]: pageId
}
}
},
{}
)
return {
pageMap,
canonicalPageMap
}
}