-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.js
201 lines (176 loc) · 7.16 KB
/
client.js
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import 'isomorphic-fetch'
import status from './middlewares/status'
import mapToModel from './middlewares/map'
import mockSuccess from './middlewares/mock/success'
import mockError from './middlewares/mock/error'
import fallback from './middlewares/fallback'
import extractData from './middlewares/extractData'
import { getCaller } from './utils'
const URL_MATCHER_REGEXP = new RegExp('(\\:([^\\/]+))', 'g')
const ARRAY_SEPARATOR = ','
const DEFAULT_OPTIONS = {
middlewares: [],
debug: false,
fullResponse: false,
mergeHeaders: true,
mock: false,
headers: {}
}
const globalOptions = {}
/**
*
* @param {String} defaultHost
* @param {Function} getDefaultHeaders
* @param {Object} [options]
* @param {Function[]} [options.middlewares]
* @param {Number} [options.mockServerPort]
* @param {Boolean} [options.debug] debug mode: log enabled
* @param {Boolean} [options.mergeHeaders=true] if true, headers provided are merged with getDefaultHeaders() return object
*/
export function init (defaultHost, getDefaultHeaders, options = {}) {
hydrateBaseOpt(defaultHost, getDefaultHeaders, globalOptions, options)
}
/**
*
* @param {String} defaultHost
* @param {Function} getDefaultHeaders
* @param {Object} [options]
* @param {Function[]} [options.middlewares]
* @param {Number} [options.mockServerPort]
* @param {Boolean} [options.debug] debug mode: log enabled
* @param {Boolean} [options.mergeHeaders=true] if true, headers provided are merged with getDefaultHeaders() return object
*
* @return {Function} call function
*
*/
export function getClient (defaultHost, getDefaultHeaders, options = {}) {
const instanceOptions = hydrateBaseOpt(defaultHost, getDefaultHeaders, {}, options)
return (endpoint, options) => _call(endpoint, {...instanceOptions, ...options})
}
function hydrateBaseOpt (defaultHost, getDefaultHeaders, baseOpt, options) {
return Object.assign(baseOpt, DEFAULT_OPTIONS, {
host: defaultHost,
getDefaultHeaders,
...options
})
}
function wrapFetchWithTimeout (url, opt, timeout) {
if(timeout !== undefined) {
return new Promise((resolve, reject) => {
setTimeout(() => reject({status: 408, ok: false, statusText: `CLIENT TIMEOUT: ${timeout} elapsed and no response has been received`}), timeout)
fetch(url, opt).then(resolve).catch(reject)
})
} else return fetch(url, opt)
}
function _call (endpoint, options) {
const {host, mock, params, mergeHeaders, headers, body, method, debug, middlewares, getDefaultHeaders, mockServerPort} = options
const basePath = (mock === true) ? `http://localhost:${mockServerPort}` : host
const url = getUrl(basePath, endpoint, params)
const opt = {
headers: mergeHeaders ? {
...getDefaultHeaders(),
...headers
} : (headers || getDefaultHeaders()),
method: method || (body ? 'POST' : 'GET'),
...(body
? {body: (typeof body === 'string')
? body : JSON.stringify(body)} : {})
}
const req = { host, url, debug, fetchOpt: opt, options }
const middlewaresSequence = [
status,
fallback,
mapToModel,
...middlewares,
extractData
]
// TODO: to be uncommented the next line and commented the one below
debug && console.log('API-CLIENT CALL', getCaller(1), req)
const mockedFetch = wrapFetchWithTimeout(url, opt, options.timeout)
.then(mockSuccess.bind(this, req))
.catch(mockError.bind(this, req))
// middleware binding
return chainMiddlewares(mockedFetch, middlewaresSequence, req)
}
/**
*
* @param {String} endpoint
* @param {Object} [options] options that override the defaults
* @param {String} [options.host] target host for the request
* @param {Object} [options.body] body payload sent through the request
* @param {Object} [options.headers] they will override getDefaultHeaders() return object by default
* @param {Boolean} [options.mergeHeaders=true] if true, headers provided are merged with getDefaultHeaders() return object
* @param {Number} [options.timeout] timeout in ms: it will raise a client timeout error if response is not received
* before <timeout>ms.
* @param {Object} [options.mock=false] this object will be used as a temporary mock when an API endpoint is not ready yet.
* @param {Object} [options.mockServerPort] mocking server port.
* @param {Object} [options.fallback] this object will be used as response data when an API endpoint returns error (and no mock option is set).
* @param {Object} [options.model] this object will be used through object-mapper in order to map the API response to our model.
* If not defined, no mapping will be performed.
* @param {String} [options.method] if not defined, POST will be used if body is present, otherwise GET is used as default.
* @param {String} [options.parse] if 'blob', data will be extracted as a blob, if 'text', data will be extracted as a text, otherwise, it will default to a json encoding
* @param {Object} [options.params] this object is matched against the endpoint expression. All the parameters not present in it,
* @param {Boolean} [options.fullResponse=false] it returns the whole response object (not only the data received)
* will be attached as query string
*
* @return {Promise<Object, Error>}
*/
export function call (endpoint, options = {}) {
return _call(endpoint, {...globalOptions, ...options})
}
function chainMiddlewares (promise, middlewares, req) {
return middlewares.reduce((acc, fn) => acc.then(fn.bind(this, req)), promise)
}
// ?country_in=82&discounted=1&limit=10&sort_by=-relevance
/**
* @ignore
*
* @param {String} host
* @param {String} endpoint
* @param {Object} params this object is matched against the endpoint expression. All the parameters not present in it,
* will be attached as query string
*
* @return {string} url
*/
function getUrl (host, endpoint, params = {}) {
const toBePlaced = sanitizeParams(params)
// substitute the path placeholders
let path = (endpoint.match(URL_MATCHER_REGEXP) || [])
.reduce((acc, placeholder) => {
const key = placeholder.substr(1)
if (!toBePlaced[key]) {
throw new Error(`endpoint parameter "${key}" has to be defined for ${endpoint}`)
}
const replaced = acc.replace(placeholder, toBePlaced[key])
delete toBePlaced[key]
return replaced
}, endpoint)
const query = Object.keys(toBePlaced)
.map(key => [key, encodeQueryString(toBePlaced[key])].join('='))
.join('&')
const url = !query.length ? path : [path, query].join('?')
return [host, url].join('/')
}
function sanitizeParams (params) {
return Object.keys(params)
.reduce((acc, key) => {
// filter undefined values
return params[key] !== undefined ?
{...acc, [key]: params[key] } : acc
}, {})
}
/**
* serialize value for query string
*
* @ignore
* @param {String|String[]} obj
* @return {String} encoded string
*/
function encodeQueryString (obj) {
if (Array.isArray(obj)) {
return obj
.map(encodeURIComponent)
.join(ARRAY_SEPARATOR)
}
return encodeURIComponent(obj)
}