-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
78 lines (60 loc) · 1.86 KB
/
api.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
'use strict';
const querystring = require('querystring');
const url = require('url');
const MAX_WIDTH = process.env.IMGSRV_MAX_WIDTH || 2400;
class NonCanonicalParamsError extends Error {
constructor(canonicalQs, actualQs) {
let message = `Params order and encoding is strict to enforce cachability\nCanonical: ${canonicalQs}\nActual:${actualQs}`;
super(message);
this.canonicalQs = canonicalQs;
this.actualQs = actualQs;
Error.captureStackTrace(this, NonCanonicalParamsError);
}
}
function getCanonicalQueryString(options) {
let canonicalQs = {
u: options.uri,
w: options.width
};
if (options.allowWebp) {
canonicalQs.webp = '1';
}
if (options.allowJp2) {
canonicalQs.jp2 = '1';
}
if (options.allowJxr) {
canonicalQs.jxr = '1';
}
return querystring.stringify(canonicalQs);
}
function validateCanonicalQuerystring(request, options) {
let canonicalQs = getCanonicalQueryString(options);
let actualQs = url.parse(request.url).query;
if (canonicalQs != actualQs) {
throw new NonCanonicalParamsError(canonicalQs, actualQs);
}
}
function parseParams(request) {
let options = {
uri: request.query.u,
width: parseInt(request.query.w) || 500,
allowWebp: request.query.webp == '1',
allowJp2: request.query.jp2 == '1',
allowJxr: request.query.jxr == '1'
};
if (!options.uri) {
throw new Error('u (uri) parameter required');
}
if (options.width > MAX_WIDTH) {
throw new Error('w parameter too large');
}
if (options.width < 2) {
throw new Error('w parameter too small');
}
// Ensure querystring format is consistent to maximize caching
validateCanonicalQuerystring(request, options);
return options;
}
exports.parseParams = parseParams;
exports.NonCanonicalParamsError = NonCanonicalParamsError;
exports.maxWidth = MAX_WIDTH;