-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
79 lines (64 loc) · 1.72 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
var request = require('request');
var mimeMagic = require('node-ee-mime-magic');
var isTest = function() {
return process.env.NODE_ENV === 'test';
};
var log = function() {
if (!isTest()) {
console.log.apply(console, arguments);
}
};
var imageCache = {};
var imageRequest = function(options) {
options = options || {};
var host = options.host || 'http://dummyimage.com';
var uri = host;
if (options.path) {
uri += options.path;
} else if (options.width && options.height) {
uri += '/' + options.width + 'x' + options.height;
} else if (options.width) {
uri += '/' + options.width;
}
return new Promise((resolve, reject) => {
request(
{
uri: uri,
encoding: 'binary'
},
function(error, response, body) {
if (error) {
return reject(error);
}
if (!error && response.statusCode === 200) {
var imageBuffer = Buffer.from(body, 'binary');
mimeMagic(imageBuffer, function(error, result) {
if (error) {
return reject(error);
}
resolve({
mimeType: result ? result.mime : null,
buffer: imageBuffer
});
});
}
}
);
});
};
var asMiddleware = function(req, res, next) {
var path = req.url.replace('/image', '');
log('[dyson-image] Resolving response for', req.url, imageCache[path] ? '(cached)' : '');
if (!imageCache[path]) {
imageCache[path] = imageRequest({ path: path });
}
imageCache[path].then(function(image) {
res.setHeader('Content-Type', image.mimeType);
res.write(image.buffer);
res.send();
});
};
module.exports = {
request: imageRequest,
asMiddleware: asMiddleware
};