-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (51 loc) · 1.5 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
"use strict";
var _ = require("lodash");
var HTTP_STATUS_CODES = require("http").STATUS_CODES;
var request = require("request");
var url = require("url");
function LamernewsAPI(root) {
this.root = root;
return this;
}
LamernewsAPI.prototype = {
getNews: function getNews(options, callback) {
var defaults = {
count: 30,
start: 0,
type: "latest"
};
var signature;
if (!callback && typeof options === "function") {
callback = options;
options = {};
}
options = _.defaults(options || {}, defaults);
signature = ["getnews", options.type, options.start, options.count];
this.query(signature.join("/"), callback);
return this;
},
query: function query(signature, callback) {
if (!this.root) {
throw new Error("No API root specified");
}
request(url.resolve(this.root, signature), function(err, res, body) {
var status;
if (err) {
return callback(err);
}
status = res.statusCode;
if (status !== 200) {
err = new Error(HTTP_STATUS_CODES[status]);
err.code = status;
return callback(err);
}
try {
body = JSON.parse(body);
} catch (err) {
callback(err);
}
callback(null, body);
});
}
};
module.exports = LamernewsAPI;