-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
95 lines (76 loc) · 1.91 KB
/
index.js
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
const createHmac = require('create-hmac')
module.exports = class ImgProxy {
constructor({ key, salt, url }) {
this.options = {
config: { key, salt, url },
settings: {
enlarge: 1,
width: 1000,
height: 1000,
gravity: "ce",
resizeType: "fill",
extension: undefined,
originalImage: undefined
}
};
}
setOption(option, value) {
this.options.settings[option] = value
}
image(val) {
this.setOption("originalImage", val);
return this;
}
width(val) {
this.setOption("width", val);
return this;
}
height(val) {
this.setOption("height", val);
return this;
}
gravity(val) {
this.setOption("gravity", val);
return this;
}
enlarge(val) {
this.setOption("enlarge", val);
return this;
}
resizeType(val) {
this.setOption("resizeType", val);
return this;
}
extension(val) {
this.setOption("extension", val);
return this;
}
sign(target) {
const hexKey = this.hexDecode(this.options.config.key)
const hexSalt = this.hexDecode(this.options.config.salt)
const hmac = createHmac('sha256', hexKey)
hmac.update(hexSalt)
hmac.update(target)
return this.urlSafeBase64(hmac.digest())
}
hexDecode(hex) {
return Buffer.from(hex, 'hex')
}
urlSafeBase64 (string) {
return Buffer.from(string)
.toString('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_')
}
get() {
const settings = this.options.settings;
const config = this.options.config;
if (!settings.originalImage) {
throw `Missing required param: image`
}
const encoded_url = this.urlSafeBase64(settings.originalImage)
const path = `/${settings.resizeType}/${settings.width}/${settings.height}/${settings.gravity}/${settings.enlarge}/${encoded_url}`
return `${config.url}/${this.sign(path)}${path}`
}
}