-
Notifications
You must be signed in to change notification settings - Fork 0
/
trello.js
72 lines (62 loc) · 1.69 KB
/
trello.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
'use strict';
const { URL } = require('url');
class ApiError extends Error {
constructor(message, method, statusCode, data) {
super(message);
this.name = 'ApiError';
this.method;
this.statusCode = statusCode;
this.data = data;
}
toString () {
return [this.message, this.method, this.statusCode, this.data].join('::');
}
}
class Trello {
constructor ({ apiKey, apiToken }) {
this.apiKey = apiKey;
this.apiToken = apiToken;
}
async getBoardLists ({
board,
}) {
return JSON.parse((await this.request('GET', `/boards/${board}/lists`)).data);
}
async createCard ({
listId,
name,
description,
position = 'bottom',
labelIds = [],
}) {
await this.request('POST', '/cards', {
idList: listId,
name,
desc: description,
pos: position,
idLabels: labelIds.join(','),
});
}
async request (method, url, params = {}) {
const trelloUrl = new URL(`https://api.trello.com/1${url}`);
for (const name in params) {
trelloUrl.searchParams.append(name, params[name]);
}
trelloUrl.searchParams.append('key', this.apiKey);
trelloUrl.searchParams.append('token', this.apiToken);
const result = await new Promise((resolve, reject) =>
require(trelloUrl.protocol.split(':')[0]).request(trelloUrl, { method }, (res) => {
const data = [];
res.on('data', (chunk) => data.push(chunk));
res.on('end', () => resolve({ statusCode: res.statusCode, data: data.join('') }));
}).on('error', (err) => reject(err))
.end()
);
if (result.statusCode < 200 || result.statusCode > 399) {
throw new ApiError('Trello API Error', method, result.statusCode, result.data);
}
return result;
}
}
Trello.CARD_DESCRIPTION_MAX_LENGTH = 10000;
module.exports = Trello;