-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathjiraImagesHandler.ts
64 lines (57 loc) · 2.11 KB
/
jiraImagesHandler.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
import {promises as fsp} from 'fs'
import path from 'path'
import {HttpRequest, HttpResponse} from 'uWebSockets.js'
import jiraPlaceholder from '../../static/images/illustrations/imageNotFound.png'
import sleep from '../client/utils/sleep'
import uWSAsyncHandler from './graphql/uWSAsyncHandler'
import getRedis, {RedisPipelineResponse} from './utils/getRedis'
const getImageFromCache = async (
imgUrlHash: string,
tryAgain: boolean
): Promise<{imageBuffer: Buffer; contentType: string} | null> => {
const redis = getRedis()
const [[imageBufferErr, imageBuffer], [contentTypeErr, contentType]] = (await redis
.multi()
.hgetBuffer(`jira-image:${imgUrlHash}`, 'imageBuffer')
.hget(`jira-image:${imgUrlHash}`, 'contentType')
.exec()) as [RedisPipelineResponse<Buffer>, RedisPipelineResponse<string>]
if (imageBufferErr || contentTypeErr) return null
if (contentType === null || contentType.length === 0) return null
if (imageBuffer === null || imageBuffer.length === 0) return null
if (imageBuffer.length > 1) return {imageBuffer, contentType}
if (tryAgain) {
await sleep(500)
return getImageFromCache(imgUrlHash, false)
}
return null
}
let jiraPlaceholderBuffer: Buffer | undefined
const servePlaceholderImage = async (res: HttpResponse) => {
if (!jiraPlaceholderBuffer) {
jiraPlaceholderBuffer = await fsp.readFile(
path.join(__dirname, jiraPlaceholder.slice(__webpack_public_path__.length))
)
}
res.cork(() => {
res.writeStatus('200').writeHeader('Content-Type', 'image/png').end(jiraPlaceholderBuffer)
})
}
const jiraImagesHandler = uWSAsyncHandler(async (res: HttpResponse, req: HttpRequest) => {
const imgUrlHash = req.getParameter(0)
if (!imgUrlHash) {
await servePlaceholderImage(res)
return
}
const cachedImage = await getImageFromCache(imgUrlHash, true)
if (!cachedImage?.imageBuffer || !cachedImage?.contentType) {
await servePlaceholderImage(res)
return
}
res.cork(() => {
res
.writeStatus('200')
.writeHeader('Content-Type', cachedImage.contentType)
.end(cachedImage.imageBuffer)
})
})
export default jiraImagesHandler