-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
80 lines (64 loc) · 1.84 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
'use strict'
const https = require('https')
const { stringify } = require('querystring')
module.exports = class RarbgApi {
constructor () {
this.config = {
host: 'xbit.pw',
path: '/api?'
}
}
search (query) {
return this.validateParams(query).then(sanitizedQuery => this.apiRequest(sanitizedQuery))
}
recent () {
return this.apiRequest()
}
validateParams (query) {
return new Promise((resolve, reject) => {
const sanitizedQuery = {}
if (!query.search) {
return reject(new Error(`The search parameter is required`))
}
if (typeof query.search !== 'string') {
return reject(new Error(`The search parameter must be a string`))
}
sanitizedQuery.search = query.search
if (query.limit) {
if (isNaN(parseFloat(query.limit))) {
return reject(new Error(`The limit parameter must be a number`))
}
sanitizedQuery.limit = query.limit
}
resolve(sanitizedQuery)
})
}
apiRequest (query) {
return new Promise((resolve, reject) => {
this.sendRequest(query).then(({ dht_results: results }) => { // eslint-disable-line camelcase
// It always returns an extra empty entry at the end
// Do a desk pop and get rid of it
if (!results[results.length - 1].ID) {
results.pop()
}
resolve(results)
}).catch(err => reject(err))
})
}
sendRequest (query) {
return new Promise((resolve, reject) => {
const req = {
host: this.config.host,
path: this.config.path + stringify(query)
}
https.get(req, res => {
let body = ''
res.setEncoding('utf8')
res.on('data', d => {
body += d
})
res.on('end', () => resolve(JSON.parse(body)))
}).on('error', err => reject(err))
})
}
}