Files
nextjs-notion-starter-kit/lib/get-all-pages.ts
Travis Fischer 89df7676a3
2022-04-08 10:49:18 -04:00

61 lines
1.5 KiB
TypeScript

import pMemoize from 'p-memoize'
import { getAllPagesInSpace } from 'notion-utils'
import * as types from './types'
import { includeNotionIdInUrls } from './config'
import { notion } from './notion-api'
import { getCanonicalPageId } from './get-canonical-page-id'
const uuid = !!includeNotionIdInUrls
export const getAllPages = pMemoize(getAllPagesImpl, {
cacheKey: (...args) => JSON.stringify(args)
})
export async function getAllPagesImpl(
rootNotionPageId: string,
rootNotionSpaceId: string
): Promise<Partial<types.SiteMap>> {
const pageMap = await getAllPagesInSpace(
rootNotionPageId,
rootNotionSpaceId,
notion.getPage.bind(notion)
)
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
}
}