-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollectionService.mjs
450 lines (345 loc) · 14.2 KB
/
collectionService.mjs
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
444
445
446
447
448
449
450
import _ from 'underscore';
import Events from 'backbone-events-standalone';
import uuid from 'uuid-v4';
import $ from 'jquery';
import matchesWhereQuery from 'matches-where-query';
import BaseService from './baseService.mjs';
const CollectionService = BaseService.extend( {
initialize( options ) {
options = _.defaults( {}, options, {
idFieldName : 'id',
defaultAjaxErrorHandler : undefined,
ajax( options ) {
return new Promise( resolve => {
$.ajax( options ).done( ( data, textStatus, xhr ) => {
resolve( { success : true, xhr } );
} ).fail( xhr => {
resolve( { success : false, xhr } );
} );
} );
}
} );
if( _.isUndefined( this.collectionName ) ) throw new Error( 'The collectionName attribute must be defined on collection service instances.' );
this._idFieldName = options.idFieldName;
this._ajax = options.ajax;
// this._defaultAjaxErrorHandler = options.defaultAjaxErrorHandler;
this.empty();
Events.mixin( this );
// Underscore methods that take a property name as an argument.
const attributeMethods = [ 'groupBy', 'countBy' ]; // used to proxy sortBy, but unclear on use case here
// Use attributes instead of properties.
for( const method of attributeMethods ) {
CollectionService.prototype[ method ] = ( value, context ) => {
const iterator = _.isFunction( value ) ? value : thisRecordId => {
return this._recordsById[ thisRecordId ][ value ];
};
return _[ method ]( this._recordIds, iterator, context );
};
}
this._setupUnderscoreProxy();
BaseService.prototype.initialize( options );
},
create( initialFieldValues, options ) {
options = _.defaults( {}, options, { silent : false } );
if( ! initialFieldValues ) initialFieldValues = {};
else initialFieldValues = this._cloneRecord( initialFieldValues );
let newRecordId = initialFieldValues[ this._idFieldName ];
if( ! newRecordId ) {
initialFieldValues[ this._idFieldName ] = newRecordId = this._getUniqueId();
} else {
// ensure our provided id is unique. don't want to be writing over other records, clearly.
if( this._recordsById[ newRecordId ] ) {
throw new Error( 'Attempt to create duplicate record id ' + newRecordId + ' in table ' + this.collectionName );
}
}
_.defaults( initialFieldValues, this.fields );
this._mergeDTO( initialFieldValues );
this.trigger( 'create', initialFieldValues, options );
this._newRecordIds.push( newRecordId );
return newRecordId;
},
id() {
return this.get( this._idFieldName );
},
get( recordId, fieldName, options ) {
options = Object.assign( {
clone : false
}, options );
if( ! this._recordsById[ recordId ] ) throw new Error( 'Record id ' + recordId + ' is not present in table \'' + this.collectionName + '\'.' );
let fieldValue = this._recordsById[ recordId ][ fieldName ];
if( options.clone ) fieldValue = this._cloneFieldValue( fieldValue );
if( _.isUndefined( fieldValue ) ) throw new Error( 'Field \'' + fieldName + '\' is not present for record id ' + recordId + ' in table \'' + this.collectionName + '\'.' );
return fieldValue;
},
gets( recordId, fields, options ) {
options = Object.assign( {
clone : false
}, options );
if( ! this._recordsById[ recordId ] ) throw new Error( 'Record id ' + recordId + ' is not present in table \'' + this.collectionName + '\'.' );
if( _.isUndefined( fields ) ) fields = Object.keys( this._recordsById[ recordId ] );
if( ! Array.isArray( fields ) ) fields = Array.prototype.slice.apply( arguments, [ 1 ] );
const values = {};
for( const thisFieldName of fields ) {
values[ thisFieldName ] = this.get( recordId, thisFieldName, { clone : options.clone } );
}
return values;
},
// eslint-disable-next-line no-unused-vars
set( recordId, fieldName, fieldValue ) {
this.rawSet.apply( this, arguments );
},
sets( recordId, fields ) {
for( const thisFieldName in fields ) {
this.set( recordId, thisFieldName, fields[ thisFieldName ] );
}
},
rawSet( recordId, fieldName, fieldValue ) {
if( ! this._recordsById[ recordId ] ) throw new Error( 'Record id ' + recordId + ' is not present in table \'' + this.collectionName + '\'.' );
if( fieldName === this._idFieldName && this._recordsById[ recordId ][ fieldName ] !== fieldValue ) throw new Error( 'Changing the id field of an existing record is not supported.' );
// not sure we want to check if the data exists before setting it.. for example, we create a new record, and then want to fill
// in fields.. of course data will not be there (unless we initilize all fields to their default values, which might make sense,
// but jury is still out, so we will do it this way for now. we tried this more lax interpretation and doesn't seem to cause problems,
// let's keep it as is. (The alternative would be to force setting non-present fields through merge.)
// if( _.isUndefined( this._recordsById[ recordId ][ fieldName ] ) )
// throw new Error( 'Field \'' + fieldName + '\' not present for record id ' + recordId + ' in table \'' + this.collectionName + '\'.' );
if( _.isUndefined( fieldValue ) ) delete this._recordsById[ recordId ][ fieldName ];
else this._recordsById[ recordId ][ fieldName ] = this._cloneFieldValue( fieldValue );
if( _.isObject( this._recordsById[ recordId ][ fieldName ] ) ) this._deepFreeze( this._recordsById[ recordId ][ fieldName ] );
this.trigger( 'set', recordId, fieldName, fieldValue );
},
async destroy( recordId, options ) {
options = _.defaults( {}, options, {
sync : true,
ajax : {}
} );
const deleteLocally = () => {
if( ! this._recordsById[ recordId ] ) throw new Error( 'Record id ' + recordId + ' is not present in table \'' + this.collectionName + '\'.' );
this._recordIds = _.without( this._recordIds, recordId );
delete this._recordsById[ recordId ];
this.length--;
this.trigger( 'destroy', recordId, options );
};
if( options.sync && ! this.isNew( recordId ) ) {
const url = this._getRESTEndpoint( 'delete', recordId );
const result = await this._sync( url, 'DELETE', undefined, options.ajax );
if( result.success ) deleteLocally();
return result;
} else {
deleteLocally();
return Promise.resolve( { success : true } );
}
},
ids() {
// return a copy of the ids array
return this._recordIds.slice( 0 );
},
isPresent( recordId, fieldName ) {
// fieldName is optional.. if not supplied function will return true iff recordId is present
if( _.isUndefined( this._recordsById[ recordId ] ) ) return false;
if( ! _.isUndefined( fieldName ) && _.isUndefined( this._recordsById[ recordId ][ fieldName ] ) ) return false;
return true;
},
isNew( recordId ) {
return this._newRecordIds.includes( recordId );
},
empty() {
this.length = 0;
this._recordIds = [];
this._recordsById = {};
this._newRecordIds = [];
},
merge( newRecordDTOs ) {
if( ! Array.isArray( newRecordDTOs ) ) newRecordDTOs = [ newRecordDTOs ];
for( const thisDto of newRecordDTOs ) {
this._mergeDTO( thisDto );
}
},
toJSON( options ) {
options = _.defaults( {}, options, {
recordIds : this._recordIds,
fields : null,
clone : false
} );
if( options.recordIds === this._recordIds && ! options.clone && ! options.fields ) {
// optimization for simplest case
return Object.values( this._recordsById );
} else if( options.fields ) {
return options.recordIds.map( thisRecordId => {
if( ! this.isPresent( thisRecordId ) ) throw new Error( 'Record id ' + thisRecordId + ' is not present in table \'' + this.collectionName + '\'.' );
return this._cloneRecord( _.pick( this._recordsById[ thisRecordId ], options.fields ) );
} );
} else {
return options.recordIds.map( thisRecordId => {
if( ! this.isPresent( thisRecordId ) ) throw new Error( 'Record id ' + thisRecordId + ' is not present in table \'' + this.collectionName + '\'.' );
return this._cloneRecord( this._recordsById[ thisRecordId ] );
} );
}
},
async fetch( recordId, options ) {
options = _.defaults( {}, options, {
variablePartsOfEndpoint : {},
ajax : {}
} );
const url = this._getRESTEndpoint( 'get', recordId, options.variablePartsOfEndpoint );
const result = await this._sync( url, 'GET', null, options.ajax );
if( result.success ) this._mergeDTO( result.data );
return result;
},
async save( recordId, options ) {
options = _.defaults( {}, options, {
merge : true,
ajax : {}
} );
const method = this.isNew( recordId ) ? 'create' : 'update';
const isUpdate = ! this.isNew( recordId );
const url = this._getRESTEndpoint( method, recordId );
const dto = this._recordToDTO( recordId, method );
const result = await this._sync( url, isUpdate ? 'PUT' : 'POST', dto, options.ajax );
if( result.success ) {
if( ! isUpdate ) this._newRecordIds = _.without( this._newRecordIds, recordId );
if( options.merge ) this._mergeDTO( result.data );
this.trigger( 'save', recordId, isUpdate, options );
}
return result;
},
// Return records with matching attributes. Useful for simple cases of
// `filter`. Unlike in underscore, if values of attrs is an array, then
// a record will be included in the return if the corresponding attribute
// on the record is included in the elements of attrs.
where( attrs, options ) {
options = _.defaults( {}, options, {
first : false,
ignoreMissingData : false
} );
if( _.isEmpty( attrs ) ) {
return options.first ? _.first( this.ids() ) : this.ids();
}
return this[ options.first ? 'find' : 'filter' ]( thisRecordId => {
if( ! options.ignoreMissingData ) {
for( const key in attrs ) {
if( _.isUndefined( this._recordsById[ thisRecordId ][ key ] ) ) {
throw new Error( 'Field \'' + key + '\' is not present for record id ' + thisRecordId + ' in table \'' + this.collectionName + '\'.' );
}
}
}
return matchesWhereQuery( this._recordsById[ thisRecordId ], attrs );
} );
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere( attrs, options ) {
options = _.defaults( {}, options, {
ignoreMissingData : false
} );
return this.where( attrs, { first : true, ignoreMissingData : options.ignoreMissingData } );
},
pluck( propertyName ) {
return _.pluck( this._recordsById, propertyName );
},
_cloneRecord( record ) {
return JSON.parse( JSON.stringify( record ) );
},
_cloneFieldValue( fieldValue ) {
if( fieldValue instanceof Object ) {
return JSON.parse( JSON.stringify( fieldValue ) );
} else {
return fieldValue;
}
},
_getUniqueId() {
return uuid();
},
_getRESTEndpoint( method, recordIdOrIds, variableParts ) {
// eslint-disable-next-line no-unused-vars
if( _.isUndefined( variableParts ) ) variableParts = {};
let base = this.url;
if( _.isFunction( base ) ) base = base.call( this );
if( ! base ) throw new Error( 'A "url" property or function must be specified' );
let endpoint = base;
const recordId = recordIdOrIds;
// if we have any pre-supplied variable parts, fill those in. necessary for cases
// like fetching a record when we have no existing information in baseline regarding,
// that record, so we can't build the url internally.
for( const thisVariablePartKey in variableParts ) {
endpoint = endpoint.replace( ':' + thisVariablePartKey, variableParts[ thisVariablePartKey ] );
}
endpoint = this._fillInVariablePartsOfRESTEndpoint( recordId, endpoint );
if( [ 'update', 'delete', 'patch', 'get' ].includes( method ) && ! Array.isArray( recordIdOrIds ) ) {
endpoint = endpoint.replace( /([^/])$/, '$1/' ) + encodeURIComponent( recordId );
}
return endpoint;
},
_fillInVariablePartsOfRESTEndpoint( recordId, endpoint ) {
return endpoint.replace( /\/:(\w+)/g, ( match, fieldName ) => {
return '/' + this.get( recordId, fieldName );
} );
},
_recordToDTO( recordId, method ) {
const dto = this.gets( recordId );
if( method === 'update' ) delete dto.id;
return dto;
},
_mergeDTO( dto ) {
const recordId = dto[ this._idFieldName ];
if( _.isUndefined( recordId ) ) {
throw new Error( 'Each dto must define a unique id.' );
}
// make sure the attributes we end up storing are copies, in case
// somebody is using the original newRecordDTOs.
const recordIsNew = ! this._recordsById[ recordId ];
if( recordIsNew ) {
this._recordsById[ recordId ] = {};
this._recordIds.push( recordId );
this.length++;
}
for( const field in dto ) {
if( _.isObject( dto[ field ] ) ) {
if( field === '_id' && _.isObject( dto[ field ] ) ){
this._recordsById[ recordId ][ field ] = _.clone( dto[ field ].toString() );
} else {
this._recordsById[ recordId ][ field ] = _.clone( dto[ field ] );
}
this._deepFreeze( this._recordsById[ recordId ][ field ] );
} else this._recordsById[ recordId ][ field ] = dto[ field ];
}
},
_deepFreeze( obj ) {
Object.freeze( obj );
for( const attribute in obj ) {
if( obj[ attribute ] !== null && typeof obj[ attribute ] === 'object' ) {
this._deepFreeze( obj[ attribute ] );
}
}
return obj;
},
_sync( url, verb, payload, ajaxOptions = {} ) {
// Default JSON-request options.
const params = {
url,
type : verb,
dataType : 'json',
contentType : 'application/json',
data : _.isEmpty( payload ) ? undefined : JSON.stringify( payload )
};
// Make the request, allowing the user to override any Ajax options.
return this._ajax( _.extend( params, ajaxOptions ) );
},
_setupUnderscoreProxy() {
// Underscore methods that we want to implement for each table.
const underscoreTableMethodNames = [ 'forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
'max', 'min', 'sortedIndex', 'size', 'first', 'head', 'take',
'initial', 'rest', 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle',
'lastIndexOf', 'isEmpty' ];
// Mix in each Underscore method as a proxy to _recordIds.
for( const thisMethodName of underscoreTableMethodNames ) {
CollectionService.prototype[ thisMethodName ] = function() {
const args = Array.prototype.slice.call( arguments );
args.unshift( this.ids() );
return _[ thisMethodName ].apply( _, args );
};
}
}
} );
export default CollectionService;