UNPKG

1.72 kBJavaScriptView Raw
1var request = require('request');
2var funkit = require('funkit');
3
4function api(url, cb) {
5 getMeta(url, function(err, d) {
6 if(err) cb(err);
7 else cb(null, constructAPI(url.split('?')[0], d));
8 });
9}
10exports.api = api;
11
12function getMeta(url, cb) {
13 request.get(url, function(err, d) {
14 if(err || d.statusCode != 200) cb(err || d.body);
15 else cb(null, JSON.parse(d.body));
16 });
17}
18exports.getMeta = getMeta;
19
20function constructAPI(url, d) {
21 url = funkit.rtrim(url, '/') + '/';
22 var ret = {};
23
24 for(var k in d) {
25 var v = d[k];
26 var r = url + k;
27
28 // TODO: collection ops (ie. boards(id).columns.<op>)
29 ret[k] = {};
30 ret[k].get = op('get', r);
31 ret[k].count = op('get', r + '/count');
32 ret[k].create = op('post', r);
33 ret[k].update = op('put', r);
34 ret[k]['delete'] = op('del', r);
35 }
36
37 return ret;
38}
39
40function op(method, r) {
41 return function(o, cb) {
42 if(funkit.isObject(o)) {
43 o.method = method;
44 var id = o.id || '';
45 delete o.id;
46
47 request.get({url: r + '/' + id, qs: o},
48 handle(cb));
49 }
50 else {
51 o = o? o: '';
52 request.get({url: r + o, qs: {method: method}},
53 handle(cb));
54 }
55 };
56}
57
58function handle(cb) {
59 return function(err, d) {
60 if(err || d.statusCode != 200) cb(err || d.body);
61 else cb(null, JSON.parse(d.body));
62 };
63}
64
65function toQ(o) {
66 var fields = o.fields? o.fields.join(','): '';
67 delete o.fields;
68
69 return fields + funkit.otozip(o).map(function(v) {
70 return v[0] + '=' + v[1].split(' ').join('+');
71 }).join('&');
72}
73