-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.ts
91 lines (72 loc) · 2.15 KB
/
request.ts
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
89
90
91
import * as got from 'got';
import { IDelete } from '../params/i-delete';
import { IGet } from '../params/i-get';
import { IOptions } from '../params/i-options';
import { IPost } from '../params/i-post';
import { IPut } from '../params/i-put';
import { IRequest } from './i-request';
import {debug} from './debug';
interface IRequestOptions {
baseUrl: string;
body?: object;
encoding: string;
headers: object;
json?: boolean;
method?: string;
query?: object;
retry: number;
timeout: number;
}
export class Request implements IRequest {
private options: IOptions;
constructor(options: IOptions) {
this.options = options;
}
@debug
public get(params: IGet): any {
const options = this.getRequestOptions();
options.method = 'get';
options.query = params.query;
return this.request(params.url, options);
}
@debug
public post(params: IPost): any {
const options = this.getRequestOptions();
options.method = 'post';
options.body = params.body;
return this.request(params.url, options);
}
@debug
public put(params: IPut): any {
const options = this.getRequestOptions();
options.method = 'put';
options.body = params.body;
return this.request(params.url, options);
}
@debug
public delete(params: IDelete): any {
const options = this.getRequestOptions();
options.method = 'delete';
return this.request(params.url, options);
}
private request(url: string, options: IRequestOptions) {
return got[options.method](url, options as object)
.then(({body}) => body)
.catch((error) => {
throw error;
});
}
private getRequestOptions(): IRequestOptions {
return {
baseUrl: this.options.baseUrl,
encoding: 'utf-8',
json: true,
headers: this.getHeaders(),
retry: this.options.retry,
timeout: this.options.timeout,
};
}
private getHeaders(): object {
return {'x-api-token': this.options.token};
}
}