forked from amanintech/amansharma.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-preview-images.ts
58 lines (50 loc) · 1.37 KB
/
get-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
import crypto from 'crypto'
import got from 'got'
import pMap from 'p-map'
import { api, isPreviewImageSupportEnabled } from './config'
import * as types from './types'
import * as db from './db'
function sha256(input: Buffer | string) {
const buffer = Buffer.isBuffer(input) ? input : Buffer.from(input)
return crypto.createHash('sha256').update(buffer).digest('hex')
}
export async function getPreviewImages(
images: string[]
): Promise<types.PreviewImageMap> {
if (!isPreviewImageSupportEnabled) {
return {}
}
const imageDocRefs = images.map((url) => {
const id = sha256(url)
return db.images.doc(id)
})
if (!imageDocRefs.length) {
return {}
}
const imageDocs = await db.db.getAll(...imageDocRefs)
const results = await pMap(imageDocs, async (model, index) => {
if (model.exists) {
return model.data() as types.PreviewImage
} else {
const json = {
url: images[index],
id: model.id
}
console.log('createPreviewImage server-side', json)
// TODO: should we fire and forget here to speed up builds?
return got
.post(api.createPreviewImage, { json })
.json() as Promise<types.PreviewImage>
}
})
return results
.filter(Boolean)
.filter((image) => !image.error)
.reduce(
(acc, result) => ({
...acc,
[result.url]: result
}),
{}
)
}