mirror of
https://github.com/d0zingcat/nextjs-notion-starter-kit.git
synced 2026-05-13 15:09:47 +00:00
79 lines
1.9 KiB
TypeScript
79 lines
1.9 KiB
TypeScript
import pMemoize from 'p-memoize'
|
|
import { getAllPagesInSpace, uuidToId } from 'notion-utils'
|
|
|
|
import { includeNotionIdInUrls } from './config'
|
|
import { notion } from './notion-api'
|
|
import { getCanonicalPageId } from './get-canonical-page-id'
|
|
import * as config from './config'
|
|
import * as types from './types'
|
|
|
|
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
|
|
}
|
|
}
|