-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
88 lines (69 loc) · 1.92 KB
/
Copy pathindex.js
File metadata and controls
88 lines (69 loc) · 1.92 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
const { parse } = require('url');
const app = require('express')();
const crypto = require('crypto');
const fs = require('fs');
const request = require('request');
const sharp = require('sharp');
const path = require('path');
const { PORT = 8080 } = process.env;
// build transform function
function addProcess(transform, [key, value]) {
let json;
try {
json = JSON.parse(value);
} catch (error) {
json = value;
}
const args = Array.isArray(json) ? json : [json];
try {
return transform[key](...args);
} catch (error) {
throw new Error(`invalid parameters for "${key}": ${error.message}`);
}
}
const sharpHas = sharp();
function makeTransform(params = {}) {
const invalid = Object.keys(params).filter((x) => !sharpHas[x]);
if (invalid.length) {
throw new Error(`Invalid transforms: ${invalid.join(', ')}`);
}
return Object.entries(params).reduce(addProcess, sharp());
}
function getImage(url) {
if (url) {
console.log(`getting image: "${url}"`);
return request(decodeURIComponent(url));
}
console.log(`returning default image`);
return fs.createReadStream(path.resolve(__dirname, './theavengers_lob_crd_03.jpg'));
}
function setCache({ method }, res, next) {
if (method == 'GET') {
res.set('Cache-control', `public, max-age=${60 * 5}`);
} else {
res.set('Cache-control', `no-store`);
}
next();
}
app
.use(setCache)
.get('/', (req, res) => {
const url = parse(req.url, true);
const { href = '', ...query } = url.query;
res.type(query.toFormat || 'jpg');
const image = getImage(href);
// send image response
image
.pipe(makeTransform(query))
.on('error', (error) => {
console.error(error);
res.type('json');
res.send({
message: '"href" query parameter invalid',
error: error.message,
});
})
.pipe(res);
})
.listen(PORT);
console.log(`running on PORT: ${PORT}`);