forked from webpro/dyson-image
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
84 lines (64 loc) · 1.94 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
var http = require('http'),
request = require('request'),
when = require('when'),
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://lorempixel.com',
uri = host,
deferred = when.defer();
if(options.path) {
uri += options.path;
}
request({
uri: uri,
encoding: 'binary'
}, function(error, response, body) {
if(error || response.statusCode !== 200) {
deferred.reject(error);
} else {
var imageBuffer = new Buffer(body, 'binary');
mimeMagic(imageBuffer, function(error, result) {
if(error) {
deferred.reject(error);
} else if(!result) {
deferred.reject("not an image");
} else {
deferred.resolve({
mimeType: result.mime,
buffer: imageBuffer
});
}
});
}
});
return deferred.promise;
};
var asMiddleware = function(req, res, next) {
var path = req.path.replace('/image', '');
if (req.query.width && req.query.height) {
path = '/' + req.query.width + '/' + req.query.height + path;
}
log('[dyson-lorempixel] Resolving response for', req.url, imageCache[req.url] ? '(cached)' : '');
if(!imageCache[req.url]) {
imageCache[req.url] = imageRequest({path: path});
}
imageCache[req.url].then(function(image) {
res.setHeader('Content-Type', image.mimeType);
res.write(image.buffer);
res.send();
});
};
module.exports = {
request: imageRequest,
asMiddleware: asMiddleware
};