-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
294 lines (250 loc) · 7.28 KB
/
index.js
File metadata and controls
294 lines (250 loc) · 7.28 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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
'use strict'
/**
* Small composition utility
*
* @param {...Function} fns
* @returns {Function}
*/
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x)
/**
* Mixin to handle parameters replacement when an Object is provided
*
* @param {Object} o
* @returns {Object}
*/
const withParamsAsObject = o => {
return Object.assign({}, o, {
replaceParams () {
Object.keys(this.params).map(param => {
this.url = this.url.replace('{' + param + '}', this.params[param])
})
},
computeOptionalParamsNames (names) {
this.optionalParams = names.reduce((acc, name) => {
if (this.params[name] !== undefined) {
acc[name] = this.params[name]
}
return acc
}, {})
},
applyOptionalSubResources () {
this.url = Object.keys(this.params).reduce((url, name) => {
// provided param is not an optional sub-resource
if (this.subResources.indexOf(name) < 0) {
return url
}
const subresource = this.subResources.shift()
// a sub resource has not been replaced in params list
if (subresource !== name) {
throw new Error('Optional subresources must be provided from left to right. "' + subresource + '" is missing.')
}
return url.replace('{/' + subresource + '}', '/' + this.params[subresource])
}, this.url)
}
})
}
/**
* Mixin to handle parameters replacement when an Array is provided
*
* @param {Object} o
* @returns {Object}
*/
const withParamsAsArray = o => {
return Object.assign({}, o, {
replaceParams () {
this.params = this.params.reduce((result, param) => {
let placeholder = /\{([a-zA-Z0-9_]+)\}/.exec(this.url)
if (placeholder && placeholder[0]) {
this.url = this.url.replace(placeholder[0], param)
return result
}
result.push(param)
return result
}, [])
},
computeOptionalParamsNames (names) {
this.optionalParams = names.reduce((acc, name) => {
let value = this.params.shift()
if (this.params.length >= 0 && value !== undefined) {
acc[name] = value
}
return acc
}, {})
},
applyOptionalSubResources () {
this.url = this.params.reduce((url, value) => {
const subresource = this.subResources.shift()
return url.replace('{/' + subresource + '}', '/' + value)
}, this.url)
}
})
}
/**
* Main Factory. Contains all common methods to parse a HATEOAS url
*
* @param {String} url
* @param {Array|Object} params
* @returns {Object}
*/
const UrlParserFactory = ({ url = '', params }) => ({
optionalParams: {},
subResources: [],
url: url,
params: params,
getOptionalParamsPosition () {
let optionalPos = this.url.indexOf('{&')
if (optionalPos === -1) {
optionalPos = this.url.indexOf('{?')
}
return optionalPos
},
createOptionalParamsHash () {
const position = this.getOptionalParamsPosition()
if (position < 0) {
return
}
// generate an array with allowed optional paramaters names
const optionals = this.url.slice(position)
const optionalParametersNames = optionals.slice(2).slice(0, -1).split(',')
// compute array to a key-value Hash with provided values
this.computeOptionalParamsNames(optionalParametersNames)
},
createSubResourcesList () {
const subResources = this.url.match(/([^{]*?)\w(?=\})/gmi) || []
this.subResources = subResources
.filter(name => { return name.indexOf('/') === 0 })
.map(name => {
return name.slice(1)
})
},
removeQueryString () {
const querystringPosition = this.url.indexOf('?')
if (querystringPosition > -1) {
this.url = this.url.slice(0, querystringPosition)
}
},
removeOptionalParamsDefinition () {
const position = this.getOptionalParamsPosition()
if (position > -1) {
this.url = this.url.slice(0, position)
}
},
applyOptionalParams () {
if (Object.keys(this.optionalParams).length === 0) {
return
}
const connector = this.url.indexOf('?') > -1 ? '&' : '?'
const querystring = Object.keys(this.optionalParams).map(name => {
return name + '=' + this.optionalParams[name]
}).join('&')
this.url += connector + querystring
},
buildUrl () {
if (this.subResources.length > 0) {
this.applyOptionalSubResources()
// drop remaining not replaced optional params
this.url = this.url.replace(/([^{]*?)\w(?=\})/gmi, '').replace('{}', '')
}
const position = this.getOptionalParamsPosition();
if (position > -1) {
this.url = this.url.slice(0, position)
this.applyOptionalParams()
}
},
getUrl () {
return this.url
},
checkForErrors () {
const remainingParams = this.url.match(/([^{]*?)\w(?=\})/gmi)
if (remainingParams) {
throw new Error('Some parameters (' + remainingParams.join(', ') + ') must be supplied in URL (' + this.url + ')')
}
}
})
/**
* Factory to get a URL parser configured to handle parameters as a key-value Hash
*
* @param {String} url
* @param {Object} params
* @returns {Object}
*/
const createObjectParser = ({ url = '', params = {} } = {}) => pipe(
withParamsAsObject,
)(UrlParserFactory({ url, params }))
/**
* Factory to get a URL parser configured to handle parameters as an Array
*
* @param {String} url
* @param {Array} params
* @returns {Object}
*/
const createArrayParser = ({ url = '', params = [] } = {}) => pipe(
withParamsAsArray,
)(UrlParserFactory({ url, params }))
/**
* Simple function to convert a raw HATEOAS index result to a more usable key-value Hash
*
* @param {Object} result
* @returns {Object}
*/
export const parseLinks = function (result) {
result = result || {}
const indexArray = (result.index || result.links || [])
return indexArray.reduce((acc, value) => {
acc[value.rel] = value.href
return acc
}, {})
}
export const parseUrl = function (url, params) {
params = params || {}
let parser = Array.isArray(params) ? createArrayParser({url, params}) : createObjectParser({url, params})
// replace mandatory params
parser.replaceParams()
// handle optional params
parser.createOptionalParamsHash()
// handle optional sub-resources
parser.createSubResourcesList()
// generate final URL
parser.buildUrl()
// check if url is now well-formed
parser.checkForErrors()
return parser.getUrl()
}
/**
* Format an endpoint by resolving eventual required and optional parameters
*
* @param {Object} index
* @param {String} rel
* @param {Object|Array=} params
* @param {String=} version
* @returns {String}
*/
export const getEndpoint = function (index, rel, params, version) {
version = version || 'default'
let url = index[rel]
if (typeof url === 'object') {
url = url[version]
}
return parseUrl(url || '', params)
}
/**
* Format an endpoint by simply removing all optional or required paramaters in the querystring
*
* @param {Object} index
* @param {String} rel
* @returns {String}
*/
export const getCleanEndpoint = function (index, rel) {
let url = index[rel] || ''
let parser = createObjectParser({url})
parser.removeOptionalParamsDefinition()
parser.removeQueryString()
parser.checkForErrors()
return parser.getUrl()
}
export default {
parseLinks,
parseUrl,
getEndpoint,
getCleanEndpoint
}