-
Notifications
You must be signed in to change notification settings - Fork 13
/
client.ts
175 lines (153 loc) · 5.07 KB
/
client.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import {
isString,
TSError,
isPlainObject,
isTest
} from '@terascope/job-components';
import { STATUS_CODES } from 'http';
import { URL } from 'url';
import got from 'got';
import { ClientConfig, SearchOptions, RequestOptions } from './interfaces';
export default class Client {
private readonly _apiVersion: string;
private readonly _request: got.GotInstance;
protected readonly _config: ClientConfig;
constructor(config: ClientConfig = {}) {
const configUrl = new URL(config.host || config.baseUrl || 'http://localhost:5678');
configUrl.pathname = '';
configUrl.hash = '';
const baseUrl = configUrl.toString();
const { apiVersion = '/v1' } = config;
this._config = config;
this._apiVersion = apiVersion;
this._request = got.extend({
baseUrl,
headers: {
'User-Agent': 'Teraslice Client',
Accept: 'application/json',
},
retry: {
retries: isTest ? 0 : 3,
maxRetryAfter: 15000 // 15 seconds
},
timeout: config.timeout,
json: true
});
}
async get(endpoint: string, options?: SearchOptions) {
return this._makeRequest('get', endpoint, options);
}
async post(endpoint: string, data: any, options?: RequestOptions) {
return this._makeRequest('post', endpoint, options, data);
}
async put(endpoint: string, data: any, options?: RequestOptions) {
return this._makeRequest('put', endpoint, options, data);
}
async delete(endpoint: string, options?: SearchOptions) {
return this._makeRequest('delete', endpoint, options);
}
private async _makeRequest(
method: string,
endpoint: string,
searchOptions: SearchOptions = {},
data?: any
) {
const errorMsg = validateRequestOptions(endpoint, searchOptions);
if (errorMsg) return Promise.reject(new TSError(errorMsg));
let options;
if (data) {
options = getRequestOptionsWithData(data, searchOptions);
} else {
options = searchOptions;
}
const newEndpoint = getAPIEndpoint(endpoint, this._apiVersion);
try {
const response = await this._request[method](newEndpoint, options);
const { body } = response;
return body;
} catch (err) {
const { statusCode } = err;
if (statusCode >= 400) {
const error = makeErrorFromResponse(err);
throw error;
}
// TODO: what additional parameters should we return here?
throw new TSError(err);
}
}
protected parse(results: any) {
if (typeof results === 'string') return JSON.parse(results);
return results;
}
// TODO: make better types for this
protected makeOptions(query: any, options: RequestOptions | SearchOptions) {
const formattedOptions = Object.assign({}, options, { query });
return formattedOptions;
}
}
function getAPIEndpoint(uri: string, apiVersion: string) {
// remove start and ending slash
const endpoint = uri ? uri.trim().replace(/(^\/)|(\/$)/, '') : '';
if (!apiVersion) return endpoint;
const txtIndex = endpoint.indexOf('txt');
const isTxt = txtIndex < 2 && txtIndex > -1;
if (isTxt) return endpoint;
if (endpoint.indexOf(apiVersion) > -1) return endpoint;
return `${apiVersion}/${endpoint}`;
}
function getErrorFromResponse(response: any) {
let { body } = response;
if (body && isString(body)) {
try {
body = JSON.parse(body);
} catch (err) {
return { message: body };
}
}
if (body && isPlainObject(body)) {
if (isString(body.error)) {
return {
message: body.error
};
}
return {
message: body.message,
code: body.error
};
}
return {};
}
interface OldErrorOutput extends TSError {
error: number;
code: string;
statusCode: number;
}
function makeErrorFromResponse(response: any): OldErrorOutput {
const { statusCode } = response;
const stuff = getErrorFromResponse(response);
const {
message = STATUS_CODES[statusCode],
code = statusCode
} = stuff;
const error: Partial<OldErrorOutput> = new TSError(message);
error.error = code; // for legacy support
error.code = code;
error.statusCode = code;
return error as OldErrorOutput;
}
// TODO: do more validations
function validateRequestOptions(endpoint: string, _options?: SearchOptions) {
if (!endpoint) {
return 'endpoint must not be empty';
}
if (!isString(endpoint)) {
return 'endpoint must be a string';
}
return null;
}
function getRequestOptionsWithData(data: any, options: SearchOptions) {
if (isPlainObject(data) || Array.isArray(data)) {
return Object.assign({}, options, { body: data });
}
return Object.assign({}, options, { body: data, json: false });
}