-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentstackHTTPClient.js
More file actions
87 lines (79 loc) · 2.2 KB
/
Copy pathcontentstackHTTPClient.js
File metadata and controls
87 lines (79 loc) · 2.2 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
78
79
80
81
82
83
84
85
86
87
import axios from 'axios'
import clonedeep from 'lodash/cloneDeep'
import Qs from 'qs'
import { ConcurrencyQueue } from './concurrency-queue'
import { isHost } from './Util'
export default function contentstackHttpClient (options) {
const defaultConfig = {
insecure: false,
retryOnError: true,
logHandler: (level, data) => {
if (level === 'error' && data) {
const title = [data.name, data.message].filter((a) => a).join(' - ')
console.error(`[error] ${title}`)
return
}
console.log(`[${level}] ${data}`)
},
retryCondition: (error) => {
if (error.response && error.response.status === 429) {
return true
}
return false
},
headers: {},
basePath: '',
proxy: false,
httpAgent: false,
httpsAgent: false,
adapter: false,
timeout: 30000
}
const config = {
...defaultConfig,
...clonedeep(options)
}
if (config.apiKey) {
config.headers['apiKey'] = config.apiKey
}
if (config.accessToken) {
config.headers['accessToken'] = config.accessToken
}
const protocol = config.insecure ? 'http' : 'https'
let hostname = config.defaultHostName
let port = config.port || 443
let baseUrlPath = ''
if (isHost(config.host)) {
const parsed = config.host.split(':')
if (parsed.length === 2) {
[hostname, port] = parsed
} else {
hostname = parsed[0]
}
}
if (config.basePath) {
config.basePath = `/${config.basePath.split('/').filter(Boolean).join('/')}`
}
baseUrlPath = `${protocol}://${hostname}:${port}${config.basePath}`
const baseURL = config.endpoint || baseUrlPath
const axiosOptions = {
// Axios
baseURL,
...config,
paramsSerializer: function (params) {
var query = params.query
delete params.query
var qs = Qs.stringify(params, { arrayFormat: 'brackets' })
if (query) {
qs = qs + `&query=${encodeURIComponent(JSON.stringify(query))}`
}
params.query = query
return qs
},
versioningStrategy: 'path'
}
const instance = axios.create(axiosOptions)
instance.httpClientParams = options
instance.concurrencyQueue = new ConcurrencyQueue({ axios: instance, config })
return instance
}