-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
101 lines (84 loc) · 2 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
'use strict';
var url = require('url');
var contra = require('contra');
var request = require('request');
function createClient (o) {
var secret;
var auth;
if (!o.api) {
throw new Error('Required API endpoint not set!');
}
function resolve (endpoint) {
return url.resolve(o.api, endpoint);
}
// wrap response handlers for consistent error reporting
function handled (next) {
return function handler (err, res, body) {
if (body.status === 'err') {
next(new Error(body.error));
} else {
next(null, body);
}
};
}
function m (method, endpoint, data, next) {
// cookie for authentication
var authCookie;
var jar = request.jar();
if (auth) {
authCookie = request.cookie('auth=' + auth);
jar.setCookie(authCookie, o.api);
}
// api secret for form
if (data && secret) {
data.apisecret = secret;
}
request({
uri: url.resolve(o.api, endpoint),
form: data,
json: true,
method: method,
jar: jar
}, handled(next));
}
var get = m.bind(null, 'GET');
var post = m.bind(null, 'POST');
function login (data, done) {
function query (next) {
get('/api/login', data, next);
}
function response (body, next) {
if (body.apisecret && body.auth) {
secret = body.apisecret;
auth = body.auth;
}
next();
}
contra.waterfall([query, response], done);
}
function submit (data, done) {
if (!data.news_id) { data.news_id = -1; }
if (!data.url) { data.url = '' }
if (!data.text) { data.text = ''; }
post('/api/submit', data, done);
}
function remove (data, done) {
post('/api/delnews', data, done);
}
function list (data, done) {
var p = [
data.sort || 'latest',
data.start || 0,
data.count || 30
];
get('/api/getnews/' + p.join('/'), data, done);
}
return {
login: login,
submit: submit,
list: list
};
}
module.exports = {
createClient: createClient
};