-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
index.js
44 lines (41 loc) · 1.21 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
const {get} = require('https');
const {URL, URLSearchParams} = require('url');
const endpoints = require('./endpoints.json');
function getContent(url) {
return new Promise((resolve, reject) => {
get(url, (res) => {
const {statusCode} = res;
if(statusCode !== 200) {
res.resume();
reject(`Request failed. Status code: ${statusCode}`);
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {rawData += chunk});
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
resolve(parsedData);
} catch(e) {
reject(`Error: ${e.message}`);
}
});
}).on('error', (err) => {
reject(`Error: ${err.message}`);
})
});
}
class NekoClient {
constructor() {
let self = this;
let baseURL = 'https://nekos.life/api/v2';
Object.keys(endpoints).forEach(async (endpoint) => {
self[endpoint] = async function (queryParams = '') {
let url = new URL(`${baseURL}${endpoints[endpoint]}`);
queryParams !== '' ? url.search = new URLSearchParams(queryParams) : '';
return await getContent(url.toString());
};
});
}
}
module.exports = NekoClient;