-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathindex.js
More file actions
443 lines (375 loc) · 12.5 KB
/
index.js
File metadata and controls
443 lines (375 loc) · 12.5 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
const axios = require('axios')
const pluralize = require('pluralize')
// Import only what we use from lodash.
const _isUndefined = require('lodash/isUndefined')
const _isString = require('lodash/isString')
const _isPlainObject = require('lodash/isPlainObject')
const _isArray = require('lodash/isArray')
const _defaultsDeep = require('lodash/defaultsDeep')
const _forOwn = require('lodash/forOwn')
const _clone = require('lodash/clone')
const _get = require('lodash/get')
const _set = require('lodash/set')
const _hasIn = require('lodash/hasIn')
const _last = require('lodash/last')
const _map = require('lodash/map')
const _findIndex = require('lodash/findIndex')
require('es6-promise').polyfill()
const deserialize = require('./middleware/json-api/_deserialize')
const serialize = require('./middleware/json-api/_serialize')
const Logger = require('./logger')
/*
* == JsonApiMiddleware
*
* Here we construct the middleware stack that will handle building and making
* requests, as well as serializing and deserializing our payloads. Users can
* easily construct their own middleware layers that adhere to different
* standards.
*
*/
const httpBasicAuthMiddleware = require('./middleware/json-api/req-http-basic-auth')
const postMiddleware = require('./middleware/json-api/req-post')
const patchMiddleware = require('./middleware/json-api/req-patch')
const deleteMiddleware = require('./middleware/json-api/req-delete')
const getMiddleware = require('./middleware/json-api/req-get')
const headersMiddleware = require('./middleware/json-api/req-headers')
const railsParamsSerializerMiddleware = require('./middleware/json-api/req-rails-params-serializer')
const sendAxiosRequestMiddleware = require('./middleware/req-axios-request')
const deserializeMiddleware = require('./middleware/json-api/res-deserialize')
const processErrors = require('./middleware/json-api/res-process-errors')
let jsonApiMiddleware = [
httpBasicAuthMiddleware,
postMiddleware,
patchMiddleware,
deleteMiddleware,
getMiddleware,
headersMiddleware,
railsParamsSerializerMiddleware,
sendAxiosRequestMiddleware,
deserializeMiddleware,
processErrors
]
class JsonApi {
constructor (options = {}) {
if (!(arguments.length === 2 && _isString(arguments[0]) && _isArray(arguments[1])) && !(arguments.length === 1 && (_isPlainObject(arguments[0]) || _isString(arguments[0])))) {
throw new Error('Invalid argument, initialize Devour with an object.')
}
let defaults = {
middleware: jsonApiMiddleware,
logger: true,
resetBuilderOnCall: true,
auth: {},
trailingSlash: {collection: false, resource: false}
}
let deprecatedConstructors = (args) => {
return (args.length === 2 || (args.length === 1 && _isString(args[0])))
}
if (deprecatedConstructors(arguments)) {
defaults.apiUrl = arguments[0]
if (arguments.length === 2) {
defaults.middleware = arguments[1]
}
}
options = _defaultsDeep(options, defaults)
let middleware = options.middleware
this._originalMiddleware = middleware.slice(0)
this.middleware = middleware.slice(0)
this.headers = {}
this.axios = axios
this.auth = options.auth
this.apiUrl = options.apiUrl
this.models = {}
this.deserialize = deserialize
this.serialize = serialize
this.builderStack = []
this.resetBuilderOnCall = !!options.resetBuilderOnCall
if (options.pluralize === false) {
this.pluralize = s => s
this.pluralize.singular = s => s
} else if ('pluralize' in options) {
this.pluralize = options.pluralize
} else {
this.pluralize = pluralize
}
this.trailingSlash = options.trailingSlash === true ? _forOwn(_clone(defaults.trailingSlash), (v, k, o) => { _set(o, k, true) }) : options.trailingSlash
options.logger ? Logger.enable() : Logger.disable()
if (deprecatedConstructors(arguments)) {
Logger.warn('Constructor (apiUrl, middleware) has been deprecated, initialize Devour with an object.')
}
}
enableLogging (enabled = true) {
enabled ? Logger.enable() : Logger.disable()
}
one (model, id) {
this.builderStack.push({model: model, id: id, path: this.resourcePathFor(model, id)})
return this
}
all (model) {
this.builderStack.push({model: model, path: this.collectionPathFor(model)})
return this
}
relationships (relationshipName) {
let lastRequest = _last(this.builderStack)
this.builderStack.push({ path: 'relationships' })
if (!relationshipName) return this
let modelName = _get(lastRequest, 'model')
if (!modelName) {
throw new Error('Relationships must be called with a preceeding model.')
}
let relationship = this.relationshipFor(modelName, relationshipName)
this.builderStack.push({ path: relationshipName, model: relationship.type })
return this
}
resetBuilder () {
this.builderStack = []
}
stackForResource () {
return _hasIn(_last(this.builderStack), 'id')
}
addSlash () {
return this.stackForResource() ? this.trailingSlash.resource : this.trailingSlash.collection
}
buildPath () {
return _map(this.builderStack, 'path').join('/')
}
buildUrl () {
let path = this.buildPath()
let slash = path !== '' && this.addSlash() ? '/' : ''
return `${this.apiUrl}/${path}${slash}`
}
get (params = {}) {
let req = {
method: 'GET',
url: this.urlFor(),
data: {},
params
}
if (this.resetBuilderOnCall) {
this.resetBuilder()
}
return this.runMiddleware(req)
}
post (payload, params = {}, meta = {}) {
let lastRequest = _last(this.builderStack)
let req = {
method: 'POST',
url: this.urlFor(),
model: _get(lastRequest, 'model'),
data: payload,
params,
meta
}
if (this.resetBuilderOnCall) {
this.resetBuilder()
}
return this.runMiddleware(req)
}
patch (payload, params = {}, meta = {}) {
let lastRequest = _last(this.builderStack)
let req = {
method: 'PATCH',
url: this.urlFor(),
model: _get(lastRequest, 'model'),
data: payload,
params,
meta
}
if (this.resetBuilderOnCall) {
this.resetBuilder()
}
return this.runMiddleware(req)
}
destroy () {
let req = null
if (arguments.length >= 2) { // destroy (modelName, id, [payload], [meta])
const [model, id, data, meta] = [...arguments]
console.assert(model, 'No model specified')
console.assert(id, 'No ID specified')
req = {
method: 'DELETE',
url: this.urlFor({model, id}),
model: model,
data: data || {},
meta: meta || {}
}
} else { // destroy ([payload])
// TODO: find a way to pass meta
const lastRequest = _last(this.builderStack)
req = {
method: 'DELETE',
url: this.urlFor(),
model: _get(lastRequest, 'model'),
data: arguments.length === 1 ? arguments[0] : {}
}
if (this.resetBuilderOnCall) {
this.resetBuilder()
}
}
return this.runMiddleware(req)
}
insertMiddlewareBefore (middlewareName, newMiddleware) {
this.insertMiddleware(middlewareName, 'before', newMiddleware)
}
insertMiddlewareAfter (middlewareName, newMiddleware) {
this.insertMiddleware(middlewareName, 'after', newMiddleware)
}
insertMiddleware (middlewareName, direction, newMiddleware) {
let middleware = this.middleware.filter(middleware => (middleware.name === middlewareName))
if (middleware.length > 0) {
let index = this.middleware.indexOf(middleware[0])
if (direction === 'after') {
index = index + 1
}
this.middleware.splice(index, 0, newMiddleware)
}
}
replaceMiddleware (middlewareName, newMiddleware) {
let index = _findIndex(this.middleware, ['name', middlewareName])
this.middleware[index] = newMiddleware
}
define (modelName, attributes, options = {}) {
this.models[modelName] = {
attributes: attributes,
options: options
}
}
resetMiddleware () {
this.middleware = this._originalMiddleware.slice(0)
}
applyRequestMiddleware (promise) {
let requestMiddlewares = this.middleware.filter(middleware => middleware.req)
requestMiddlewares.forEach((middleware) => {
promise = promise.then(middleware.req)
})
return promise
}
applyResponseMiddleware (promise) {
let responseMiddleware = this.middleware.filter(middleware => middleware.res)
responseMiddleware.forEach((middleware) => {
promise = promise.then(middleware.res)
})
return promise
}
applyErrorMiddleware (promise) {
let errorsMiddleware = this.middleware.filter(middleware => middleware.error)
errorsMiddleware.forEach((middleware) => {
promise = promise.then(middleware.error)
})
return promise
}
runMiddleware (req) {
let payload = {req: req, jsonApi: this}
let requestPromise = Promise.resolve(payload)
requestPromise = this.applyRequestMiddleware(requestPromise)
return requestPromise
.then((res) => {
payload.res = res
let responsePromise = Promise.resolve(payload)
return this.applyResponseMiddleware(responsePromise)
})
.catch((err) => {
Logger.error(err)
let errorPromise = Promise.resolve(err)
return this.applyErrorMiddleware(errorPromise).then(err => {
return Promise.reject(err)
})
})
}
request (url, method = 'GET', params = {}, data = {}) {
let req = { url, method, params, data }
return this.runMiddleware(req)
}
find (modelName, id, params = {}) {
let req = {
method: 'GET',
url: this.urlFor({model: modelName, id: id}),
model: modelName,
data: {},
params: params
}
return this.runMiddleware(req)
}
findAll (modelName, params = {}) {
let req = {
method: 'GET',
url: this.urlFor({model: modelName}),
model: modelName,
params: params,
data: {}
}
return this.runMiddleware(req)
}
create (modelName, payload, params = {}, meta = {}) {
let req = {
method: 'POST',
url: this.urlFor({model: modelName}),
model: modelName,
params: params,
data: payload,
meta: meta
}
return this.runMiddleware(req)
}
update (modelName, payload, params = {}, meta = {}) {
let req = {
method: 'PATCH',
url: this.urlFor({model: modelName, id: payload.id}),
model: modelName,
data: payload,
params: params,
meta: meta
}
return this.runMiddleware(req)
}
modelFor (modelName) {
if (!this.models[modelName]) {
throw new Error(`API resource definition for model "${modelName}" not found. Available models: ${Object.keys(this.models)}`)
}
return this.models[modelName]
}
relationshipFor (modelName, relationshipName) {
let model = this.modelFor(modelName)
let relationship = model.attributes[relationshipName]
if (!relationship) {
throw new Error(`API resource definition on model "${modelName}" for relationship "${relationshipName}" not found. Available attributes: ${Object.keys(model.attributes)}`)
}
return relationship
}
collectionPathFor (modelName) {
let collectionPath = _get(this.models[modelName], 'options.collectionPath') || this.pluralize(modelName)
return `${collectionPath}`
}
resourcePathFor (modelName, id) {
let collectionPath = this.collectionPathFor(modelName)
return `${collectionPath}/${encodeURIComponent(id)}`
}
collectionUrlFor (modelName) {
let collectionPath = this.collectionPathFor(modelName)
let trailingSlash = this.trailingSlash['collection'] ? '/' : ''
return `${this.apiUrl}/${collectionPath}${trailingSlash}`
}
resourceUrlFor (modelName, id) {
let resourcePath = this.resourcePathFor(modelName, id)
let trailingSlash = this.trailingSlash['resource'] ? '/' : ''
return `${this.apiUrl}/${resourcePath}${trailingSlash}`
}
urlFor (options = {}) {
if (!_isUndefined(options.model) && !_isUndefined(options.id)) {
return this.resourceUrlFor(options.model, options.id)
} else if (!_isUndefined(options.model)) {
return this.collectionUrlFor(options.model)
} else {
return this.buildUrl()
}
}
pathFor (options = {}) {
if (!_isUndefined(options.model) && !_isUndefined(options.id)) {
return this.resourcePathFor(options.model, options.id)
} else if (!_isUndefined(options.model)) {
return this.collectionPathFor(options.model)
} else {
return this.buildPath()
}
}
}
module.exports = JsonApi