forked from strapi-community/strapi-plugin-local-image-sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrapi-server.js
More file actions
106 lines (91 loc) · 2.75 KB
/
strapi-server.js
File metadata and controls
106 lines (91 loc) · 2.75 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
'use strict'
const { decode } = require('ufo')
const getEtag = require('etag')
const Router = require('@koa/router')
const qs = require('qs')
const { createIPX } = require('ipx')
function createMiddleware(ipx) {
return async function ipxMiddleware(ctx, next) {
const [url, query] = ctx.req.url.replace('/uploads', '').split('?')
const [firstSegment = '', ...idSegments] = url.substr(1 /* leading slash */).split('/')
const allowType = ['JPEG', 'PNG', 'GIF', 'SVG', 'TIFF', 'ICO', 'DVU', 'JPG', 'WEBP'];
if(!allowType.includes(firstSegment.split('.').pop().toUpperCase())) {
await next()
return
}
let id
let modifiers
if (!idSegments.length && firstSegment) {
id = firstSegment
modifiers = qs.parse(query)
} else {
id = decode(idSegments.join('/'))
modifiers = Object.create(null)
if (firstSegment !== '_') {
for (const p of firstSegment.split(',')) {
const [key, value = ''] = p.split('_')
modifiers[key] = decode(value)
}
}
}
if (!id) {
await next()
return
}
if (!Object.keys(modifiers).length) {
await next()
return
}
// Create request
const img = ipx(id, modifiers, ctx.req.options)
// Get image meta from source
try {
const src = await img.src()
// Caching headers
if (src.mtime) {
if (ctx.req.headers['if-modified-since']) {
if (new Date(ctx.req.headers['if-modified-since']) >= src.mtime) {
ctx.status = 304
return
}
}
ctx.set('Last-Modified', `${+src.mtime}`)
}
if (src.maxAge !== undefined) {
ctx.set('Cache-Control', `max-age=${+src.maxAge}, public, s-maxage=${+src.maxAge}`)
}
// Get converted image
const { data, format } = await img.data()
// ETag
const etag = getEtag(data)
ctx.set('ETag', etag)
if (etag && ctx.req.headers['if-none-match'] === etag) {
ctx.status = 304
return
}
// Mime
if (format) {
ctx.set('Content-Type', `image/${format}`)
}
ctx.body = data
} catch (error) {
const statusCode = parseInt(error.statusCode, 10) || 500
const statusMessage = error.message ? `IPX Error (${error.message})` : `IPX Error (${statusCode})`
strapi.log.debug(statusMessage)
console.error(error)
ctx.status = statusCode
}
}
}
const plugin = {
register({ strapi }) {
const ipx = createIPX({
dir: `${strapi.dirs?.static?.public ?? strapi.dirs?.public}/uploads`,
})
const router = new Router()
const middeware = createMiddleware(ipx)
router.get('/uploads/(.*)', middeware)
strapi.server.use(router.routes())
},
}
module.exports = plugin