-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
75 lines (65 loc) · 2.19 KB
/
app.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
var fetch = require('./fetch');
var finalhandler = require('finalhandler');
var http = require('http');
var log = require('./log');
var Router = require('router');
var StatsD = require('node-statsd');
var url = require('url');
var util = require('util');
var statsd = new StatsD({
prefix: 'price-for-asin.api.',
host: process.env.STATSD_HOST || 'localhost'
});
var PORT = process.env.PRICE_FOR_ASIN_PORT || 3000;
function handleClientError(code, msg, req, res) {
statsd.increment('error_responses');
log.info({status_code: code, method: req.method, url: req.url}, util.format("BAD REQUEST: %s", msg));
res.statusCode = code;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({error: msg}));
}
function handleBadRequest(errorMsg, req, res) {
handleClientError(400, errorMsg, req, res);
}
function handleNotFound(req, res) {
handleClientError(404, "Resource not found: " + req.url, req, res);
}
var router = Router();
router.get('/price', function (req, res) {
statsd.increment('requests');
if (req.method != "GET") {
var errorMsg = "Method not accepted: " + req.method;
return handleBadRequest(errorMsg, req, res);
}
var asin;
try {
asin = url.parse(req.url, true).query.asin;
log.info({asin: asin}, "ASIN in query string: ");
} catch (e) {
return handleBadRequest("Bad query string", req, res);
}
if (!asin) {
return handleBadRequest("No ASIN in query string", req, res);
} else {
fetch.fetchPriceForAsin(asin, function(err, result) {
if (err) {
log.error(err, "fetchPriceForAsin returned err");
return handleNotFound(req, res);
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
var responseJson = {
price: result.price,
currency: result.currency
};
var responseBody = JSON.stringify(responseJson, null, 4) + '\n';
res.end(responseBody);
log.info({status_code: res.statusCode, method: req.method, url: req.url}, "Successful request");
});
}
});
var server = http.createServer(function(req, res) {
router(req, res, finalhandler(req, res));
});
server.listen(PORT);
log.info({}, "Server price-to-asin listening on port " + PORT);