forked from transitive-bullshit/nextjs-notion-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathresolve-notion-page.ts
91 lines (76 loc) · 2.82 KB
/
resolve-notion-page.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
79
80
81
82
83
84
85
86
87
88
89
90
91
import { ExtendedRecordMap } from 'notion-types'
import { parsePageId } from 'notion-utils'
import * as acl from './acl'
import { environment, pageUrlAdditions, pageUrlOverrides, site } from './config'
import { db } from './db'
import { getSiteMap } from './get-site-map'
import { getPage } from './notion'
export async function resolveNotionPage(domain: string, rawPageId?: string) {
let pageId: string
let recordMap: ExtendedRecordMap
if (rawPageId && rawPageId !== 'index') {
pageId = parsePageId(rawPageId)
if (!pageId) {
// check if the site configuration provides an override or a fallback for
// the page's URI
const override =
pageUrlOverrides[rawPageId] || pageUrlAdditions[rawPageId]
if (override) {
pageId = parsePageId(override)
}
}
const useUriToPageIdCache = true
const cacheKey = `uri-to-page-id:${domain}:${environment}:${rawPageId}`
// TODO: should we use a TTL for these mappings or make them permanent?
// const cacheTTL = 8.64e7 // one day in milliseconds
const cacheTTL = undefined // disable cache TTL
if (!pageId && useUriToPageIdCache) {
try {
// check if the database has a cached mapping of this URI to page ID
pageId = await db.get(cacheKey)
// console.log(`redis get "${cacheKey}"`, pageId)
} catch (err) {
// ignore redis errors
console.warn(`redis error get "${cacheKey}"`, err.message)
}
}
if (pageId) {
recordMap = await getPage(pageId)
} else {
// handle mapping of user-friendly canonical page paths to Notion page IDs
// e.g., /developer-x-entrepreneur versus /71201624b204481f862630ea25ce62fe
const siteMap = await getSiteMap()
pageId = siteMap?.canonicalPageMap[rawPageId]
if (pageId) {
// TODO: we're not re-using the page recordMap from siteMaps because it is
// cached aggressively
// recordMap = siteMap.pageMap[pageId]
recordMap = await getPage(pageId)
if (useUriToPageIdCache) {
try {
// update the database mapping of URI to pageId
await db.set(cacheKey, pageId, cacheTTL)
// console.log(`redis set "${cacheKey}"`, pageId, { cacheTTL })
} catch (err) {
// ignore redis errors
console.warn(`redis error set "${cacheKey}"`, err.message)
}
}
} else {
// note: we're purposefully not caching URI to pageId mappings for 404s
return {
error: {
message: `Not found "${rawPageId}"`,
statusCode: 404
}
}
}
}
} else {
pageId = site.rootNotionPageId
console.log(site)
recordMap = await getPage(pageId)
}
const props = { site, recordMap, pageId }
return { ...props, ...(await acl.pageAcl(props)) }
}