-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.js
82 lines (64 loc) · 1.57 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
79
80
81
82
'use strict';
var fs = require('fs'),
_ = require('underscore');
module.exports = function(app) {
app.get('/api', function(req, res) {
var data;
if(req.query.query == 'estados') {
data = app.get('estados');
} else {
data = app.get('municipios');
}
var limit = parseInt(req.query.limit) || 20;
var page = parseInt(req.query.page) || 1;
var results = {
data: data.slice(0)
};
if(req.query) {
for(var key in req.query) {
results.data = _.filter(results.data, function(i) {
if(!i[key])
return true;
return i[key] == req.query[key];
});
}
if(req.query.orderby) {
if(req.query.order == 'ASC') {
results.data = _.sortBy(results.data, function(item) {
return item[req.query.orderby];
});
} else {
results.data = _.sortBy(results.data, function(item) {
return -item[req.query.orderby];
});
}
}
}
results.total = results.data.length;
if(page*limit > results.total && page !== 1)
res.send([]);
else {
if(limit !== -1)
results.data = results.data.slice(((page-1)*limit), ((page-1)*limit) + limit);
res.send(results);
}
});
app.get('/api/municipios', function(req, res) {
if(req.query.format == 'csv') {
fs.readFile('data/municipios.csv', function(err, data) {
res.send(data);
});
} else {
res.send(app.get('municipios'));
}
});
app.get('/api/estados', function(req, res) {
if(req.query.format == 'csv') {
fs.readFile('data/estados.csv', function(err, data) {
res.send(data);
});
} else {
res.send(app.get('estados'));
}
});
};