-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentstack-core.ts
More file actions
77 lines (65 loc) · 2.03 KB
/
contentstack-core.ts
File metadata and controls
77 lines (65 loc) · 2.03 KB
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
import _ from 'lodash';
import { serialize } from './param-serializer';
import axios, { AxiosRequestHeaders, getAdapter } from 'axios';
import { AxiosInstance, HttpClientParams } from './types';
import { ERROR_MESSAGES } from './error-messages';
export function httpClient(options: HttpClientParams): AxiosInstance {
const defaultConfig = {
insecure: false,
retryOnError: true,
headers: {} as AxiosRequestHeaders,
basePath: '',
proxy: false as const,
httpAgent: false,
httpsAgent: false,
timeout: 30000,
logHandler: (level: string, data?: any) => {
if (level === 'error') {
if (data) {
const title = [data.name, data.message].filter((a) => a).join(' - ');
console.error(ERROR_MESSAGES.CONSOLE.ERROR_WITH_TITLE(title));
}
return;
}
if (data !== undefined) {
console.log(ERROR_MESSAGES.CONSOLE.LEVEL_WITH_DATA(level, data));
}
},
retryCondition: (error: any) => {
if (error.response && error.response.status === 429) {
return true;
}
return false;
},
versioningStrategy: 'path',
};
const config: HttpClientParams = {
...defaultConfig,
..._.cloneDeep(options),
};
if (config.apiKey && config.headers) {
config.headers.api_key = config.apiKey;
}
if (config.accessToken && config.headers) {
config.headers.access_token = config.accessToken;
}
const protocol = config.insecure ? 'http' : 'https';
const hostname = config.defaultHostname;
const port = config.port || 443;
const version = config.version || 'v3';
const baseURL = config.endpoint || `${protocol}://${hostname}:${port}${config.basePath}/${version}`;
const instance = axios.create({
// Axios
baseURL,
adapter: getAdapter(axios.defaults.adapter),
...config,
paramsSerializer: {
serialize,
},
}) as AxiosInstance;
instance.httpClientParams = options;
if (config.onError) {
instance.interceptors.response.use((response) => response, config.onError);
}
return instance;
}