forked from transitive-bullshit/nextjs-notion-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpreview-images.ts
76 lines (66 loc) · 2 KB
/
preview-images.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
import got from 'got'
import lqip from 'lqip-modern'
import { ExtendedRecordMap, PreviewImage, PreviewImageMap } from 'notion-types'
import { getPageImageUrls, normalizeUrl } from 'notion-utils'
import pMap from 'p-map'
import pMemoize from 'p-memoize'
import { defaultPageCover, defaultPageIcon } from './config'
import { db } from './db'
import { mapImageUrl } from './map-image-url'
export async function getPreviewImageMap(
recordMap: ExtendedRecordMap
): Promise<PreviewImageMap> {
const urls: string[] = getPageImageUrls(recordMap, {
mapImageUrl
})
.concat([defaultPageIcon, defaultPageCover])
.filter(Boolean)
const previewImagesMap = Object.fromEntries(
await pMap(
urls,
async (url) => {
const cacheKey = normalizeUrl(url)
return [cacheKey, await getPreviewImage(url, { cacheKey })]
},
{
concurrency: 8
}
)
)
return previewImagesMap
}
async function createPreviewImage(
url: string,
{ cacheKey }: { cacheKey: string }
): Promise<PreviewImage | null> {
try {
try {
const cachedPreviewImage = await db.get(cacheKey)
if (cachedPreviewImage) {
return cachedPreviewImage
}
} catch (err) {
// ignore redis errors
console.warn(`redis error get "${cacheKey}"`, err.message)
}
const { body } = await got(url, { responseType: 'buffer' })
const result = await lqip(body)
console.log('lqip', { ...result.metadata, url, cacheKey })
const previewImage = {
originalWidth: result.metadata.originalWidth,
originalHeight: result.metadata.originalHeight,
dataURIBase64: result.metadata.dataURIBase64
}
try {
await db.set(cacheKey, previewImage)
} catch (err) {
// ignore redis errors
console.warn(`redis error set "${cacheKey}"`, err.message)
}
return previewImage
} catch (err) {
console.warn('failed to create preview image', url, err.message)
return null
}
}
export const getPreviewImage = pMemoize(createPreviewImage)