-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatopera.js
90 lines (79 loc) · 2.09 KB
/
chatopera.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
const debug = require('debug')('chatopera:sdk:chatopera');
const request = require('superagent');
const BASE_PATH = '/api/v1';
/**
* 机器人管理
*/
class Chatopera {
constructor(accessToken, host = 'https://bot.chatopera.com') {
if (!accessToken) {
throw new Error('ChatoperaAdmin: Unexpected accessToken');
}
if (host) {
if (host.endsWith('/')) host = host.substr(0, host.length - 1);
this.host = host;
} else {
throw new Error('ChatoperaAdmin: Unexpected host');
}
this.accessToken = accessToken;
this.host = host;
this.baseEndpoint = BASE_PATH;
debug('constructor: host %s, accessToken %s', this.host, this.accessToken);
}
command(method, path, payload, headers) {
// debug("[command] method %s, path %s", method, path, payload);
let endpoint = this.baseEndpoint + path;
/**
* 增加参数 sdklang
*/
method = method.toUpperCase();
if (path) {
let splits = path.split('&');
if (splits.length > 1 && path.includes('?')) {
path += '&sdklang=nodejs';
} else {
path += '?sdklang=nodejs';
}
} else {
path = '/?sdklang=nodejs';
}
/**
* 请求
*/
let req = request(method, this.host + endpoint);
req
.set('X-Requested-With', 'XMLHttpRequest')
.set('Expires', '-1')
.set(
'Cache-Control',
'no-cache,no-store,must-revalidate,max-age=-1,private'
)
.set(
'Content-Type',
headers && headers['Content-Type']
? headers['Content-Type']
: 'application/json'
)
.set('Authorization', `Bearer ${this.accessToken}`)
.set(
'Accept',
headers && headers['Accept'] ? headers['Accept'] : 'application/json'
);
if (payload) {
req.send(payload);
}
return req.then(
(res) => {
return res.body;
},
(err) => {
debug('[command] method %s, path %s, Error %s', method, path, err);
throw {
rc: 100,
error: err,
};
}
);
}
}
module.exports = exports = Chatopera;