UNPKG

2.03 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.Connection = void 0;
7const is_url_superb_1 = __importDefault(require("is-url-superb"));
8const ky_universal_1 = __importDefault(require("ky-universal"));
9const errors_1 = require("./errors");
10const resources_1 = require("./resources");
11class Connection {
12 constructor(host) {
13 this.host = host;
14 if (!is_url_superb_1.default(host)) {
15 throw new Error(`${host} is not a valid URL.`);
16 }
17 }
18 api(name) {
19 const selectedResourceClass = resources_1.Resources[name.toLowerCase()];
20 return new selectedResourceClass(this);
21 }
22 withOptions(opts) {
23 this.opts = opts;
24 return this;
25 }
26 async get(url, opts) {
27 return this.sendRequest("get", url, opts);
28 }
29 async post(url, opts) {
30 return this.sendRequest("post", url, opts);
31 }
32 async sendRequest(method, url, opts) {
33 opts = { ...this.opts, ...(opts || {}) };
34 if (!opts.retry) {
35 opts.retry = { retries: 0 };
36 }
37 if (!opts.timeout) {
38 opts.timeout = 1500;
39 }
40 try {
41 const response = await ky_universal_1.default(`${this.host}/${url}`, { ...opts, method, json: opts.body });
42 return {
43 body: await response.json(),
44 headers: response.headers,
45 status: response.status,
46 };
47 }
48 catch (error) {
49 if (error.response) {
50 error.response = {
51 body: await error.response.json(),
52 headers: error.response.headers,
53 status: error.response.status,
54 };
55 }
56 throw new errors_1.RequestError(error);
57 }
58 }
59}
60exports.Connection = Connection;
61//# sourceMappingURL=connection.js.map
\No newline at end of file