This repository was archived by the owner on May 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 333
/
Copy pathimg.ts
executable file
·52 lines (40 loc) · 1.52 KB
/
img.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
// @ts-check
import CacheFactory from '../image/cache/factory';
import ActionFactory from '../image/action/factory';
const asyncMiddleware = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
export default ({ config, db }) =>
asyncMiddleware(async (req, res, next) => {
if (!(req.method === 'GET')) {
res.set('Allow', 'GET');
return res.status(405).send('Method Not Allowed');
}
const cacheFactory = new CacheFactory(config, req)
req.socket.setMaxListeners(config.imageable.maxListeners || 50);
let imageBuffer
const actionFactory = new ActionFactory(req, res, next, config)
const imageAction = actionFactory.getAdapter(config.imageable.action.type)
imageAction.getOption()
imageAction.validateOptions()
imageAction.isImageSourceHostAllowed()
imageAction.validateMIMEType()
if (res.headersSent) return
const cache = cacheFactory.getAdapter(config.imageable.caching.type)
if (config.imageable.caching.active && await cache.check()) {
await cache.getImageFromCache()
imageBuffer = cache.image
} else {
await imageAction.prossesImage()
if (config.imageable.caching.active && !imageAction.error) {
cache.image = imageAction.imageBuffer
await cache.save()
}
imageBuffer = imageAction.imageBuffer
}
if (res.headersSent) return
return res
.type(imageAction.mimeType)
.set({ 'Cache-Control': `max-age=${imageAction.maxAgeForResponse}` })
.send(imageBuffer);
});