-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathclient.js
88 lines (81 loc) · 2.28 KB
/
client.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
import { fileURLToPath } from 'url';
import createDebug from 'debug';
import got from 'got';
import { readPackageUpSync } from 'read-pkg-up';
import RateLimit from '../rate-limit.js';
import { filterObjectValues, getTypeName } from '../util.js';
const debug = createDebug('graphbrainz:api/client');
const { packageJson: pkg } = readPackageUpSync({
cwd: fileURLToPath(import.meta.url),
});
export default class Client {
constructor({
baseURL,
userAgent = `${pkg.name}/${pkg.version} ` +
`( ${pkg.homepage || pkg.author.url || pkg.author.email} )`,
extraHeaders = {},
timeout = 60000,
limit = 1,
period = 1000,
concurrency = 10,
retry,
} = {}) {
this.baseURL = baseURL;
this.userAgent = userAgent;
this.extraHeaders = extraHeaders;
this.timeout = timeout;
this.limiter = new RateLimit({ limit, period, concurrency });
this.retryOptions = retry;
}
parseErrorMessage(err) {
return err;
}
/**
* Send a request without any rate limiting.
* Use `get` instead.
*/
async _get(path, { searchParams, ...options } = {}) {
const url = new URL(path, this.baseURL);
if (searchParams) {
if (getTypeName(searchParams) === 'Object') {
searchParams = filterObjectValues(
searchParams,
(value) => value != null
);
}
const moreSearchParams = new URLSearchParams(searchParams);
moreSearchParams.forEach((value, key) => {
url.searchParams.set(key, value);
});
}
options = {
responseType: 'json',
timeout: this.timeout,
retry: this.retryOptions,
...options,
headers: {
'User-Agent': this.userAgent,
...this.extraHeaders,
...options.headers,
},
};
let response;
try {
debug(`Sending request. url=%s`, url);
response = await got(url.toString(), options);
debug(`Success: %s url=%s`, response.statusCode, url);
return response;
} catch (err) {
const parsedError = this.parseErrorMessage(err) || err;
debug(`Error: “%s” url=%s`, parsedError, url);
throw parsedError;
}
}
/**
* Send a request with rate limiting.
*/
get(path, options = {}) {
const fn = this._get.bind(this);
return this.limiter.enqueue(fn, [path, options]);
}
}