-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathJsonApiSerializer.ts
1675 lines (1379 loc) · 78.7 KB
/
JsonApiSerializer.ts
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference path="../scripts/typings/js-data/js-data.d.ts" />
/// <reference path="../scripts/typings/js-data/JsonApiAdapter.d.ts" />
/// <reference path="JsonApi.ts" />
import JSDataLib = require('js-data');
import JsonApi = require('./JsonApi');
//import JSDataLib = require('js-data');
//var jsdata: Function = require('js-data');
export const JSONAPI_META: string = '$_JSONAPIMETA_';
const jsonApiContentType: string = 'application/vnd.api+json';
export const JSONAPI_RELATED_LINK: string = 'related';
export const JSONAPI_PARENT_LINK: string = 'parent';
const jsDataBelongsTo : string = 'belongsTo';
const jsDataHasMany: string = 'hasMany';
const jsDataHasOne: string = 'hasOne';
let DSUTILS: JSData.DSUtil = JSDataLib['DSUtils'];
/**
* @name IJSDataManyToManyMeta
* @desc Type def for custom meta data used to tag many-to-many relations in jsdata config
*/
interface IJSDataManyToManyMeta {
/**
* @name type
* @desc JsData data type of foreign type that we are joining to
*/
type: string;
/**
* @name joinType
* @desc The JsData type name for the joining table used to join many to many data
*/
joinType: string;
}
class MetaLinkDataImp implements JsonApiAdapter.MetaLinkData {
type: string;
url: string;
meta: any;
constructor(type: string, url: string) {
this.type = type;
this.url = url;
}
}
export class MetaData implements JsonApiAdapter.JsonApiMetaData {
selfType: string;
selfLink: string;
isJsonApiReference: boolean;
relationships: { [relation: string]: JsonApiAdapter.MetaLink };
links: { [link: string]: JsonApiAdapter.MetaLinkData };
private referenceCount: number;
constructor(type: string) {
this.selfType = type;
this.selfLink = null;
this.isJsonApiReference = true;
this.relationships = {};
this.links = {};
this.referenceCount = 0;
}
/**
* @name getPath
* @desc Override DSHttpAdapter get path to use stored JsonApi self link if available
* @param {string} relationName The name or rel attribute of relationship
* @param {string} linkType, related, self etc..
* @param {string} url Link url
* @return {MetaData} this e.g. fluent method
* @memberOf MetaData
**/
WithRelationshipLink(relationName: string, linkType: string, dataType: string, url: string): MetaData {
this.relationships[relationName] = this.relationships[relationName] || {};
this.relationships[relationName][linkType] = new MetaLinkDataImp(dataType, url);
return this;
}
WithLink(linkName: string, url: string, meta: any): MetaData {
var link = new MetaLinkDataImp(linkName, url);
link.meta = meta;
this.links[linkName] = link;
return this;
}
getLinks(linkName: string): JsonApiAdapter.MetaLinkData {
return this.links[linkName];
}
incrementReferenceCount(): number {
this.referenceCount++;
return this.referenceCount;
}
public getRelationshipLink(relationName: string, linkType: string): JsonApiAdapter.MetaLinkData {
if (this.relationships[relationName]) {
return this.relationships[relationName][linkType];
} else {
return undefined;
}
}
static TryGetMetaData(obj: Object): MetaData {
if (obj) {
return DSUTILS.get<MetaData>(obj, JSONAPI_META);
} else {
return undefined;
}
}
}
class ModelPlaceHolder {
type: string;
id: string;
keyType: string;
keyName: string;
keyValue: string;
constructor(type: string, id: string) {
this.type = type;
this.id = id;
if (!type || !id) {
throw new Error('Type or Id missing');
}
}
WithForeignKey(keyName: string, keyValue: string, keyType: string): ModelPlaceHolder {
this.keyName = keyName;
this.keyValue = keyValue;
this.keyType = keyType;
return this;
}
}
export class SerializationOptions {
get type(): string { return this.resourceDef.name; };
get idAttribute(): string { return this.resourceDef.idAttribute; };
relationType(): string { return this.resourceDef['type']; };
constructor(def: JSData.DSResourceDefinitionConfiguration) {
this.resourceDef = def;
}
private resourceDef: JSData.DSResourceDefinitionConfiguration;
def(): JSData.DSResourceDefinitionConfiguration {
return this.resourceDef;
}
getResource(resourceName: string): SerializationOptions {
var resource = this.resourceDef.getResource(resourceName);
return resource ? new SerializationOptions(resource) : null;
}
getBelongsToRelation(parentType: string, relationName? : string): JSData.RelationDefinition {
if (this.resourceDef.relations && this.resourceDef.relations.belongsTo) {
if (relationName) {
return this.resourceDef.relations.belongsTo[parentType];
}else {
return this.resourceDef.relations.belongsTo[parentType];
}
}
return null;
}
getParentRelationByLocalKey(localKey: string): JSData.RelationDefinition {
var match: JSData.RelationDefinition = null;
if (this.resourceDef.relations && this.resourceDef.relations.belongsTo) {
for (var r in this.resourceDef.relations.belongsTo) {
if (this.resourceDef.relations.belongsTo[r]) {
DSUTILS.forEach(this.resourceDef.relations.belongsTo[r], (relation: JSData.RelationDefinition) => {
if (relation.localKey === localKey) {
match = relation;
return false;
}
});
}
}
}
return match;
}
getParentRelationByLocalField(localField: string): JSData.RelationDefinition {
var match: JSData.RelationDefinition = null;
if (this.resourceDef.relations && this.resourceDef.relations.belongsTo) {
for (var r in this.resourceDef.relations.belongsTo) {
if (this.resourceDef.relations.belongsTo[r]) {
DSUTILS.forEach(this.resourceDef.relations.belongsTo[r], (relation: JSData.RelationDefinition) => {
if (relation.localField === localField) {
match = relation;
return false;
}
});
}
}
}
return match;
}
/**
* @name getChildRelation
* @desc Get the child relationship for a resorce of a given type defined by relationType,
* NOTE: Their can be more than one relation of a type. This just returns the first, or null if non found
* @param relationType The relationship type to find
*/
getChildRelation(relationType: string): JSData.RelationDefinition {
let relation = this.getChildRelations(relationType);
return (relation && relation[0]) ? relation[0] : null;
}
/**
* @name getChildRelationWithLocalField
* @desc Given the relationType, find relationship by localFielName name
* @param relationType The type the relationship represents
* @param localFieldName The local field name for the relationship, incase there is more than one relationship on the object of the given type
*/
getChildRelationWithLocalField(relationType: string, localFieldName: string): JSData.RelationDefinition {
relationType = relationType.toLowerCase();
localFieldName = localFieldName.toLowerCase();
let relations = this.getChildRelations(relationType);
var match: JSData.RelationDefinition = null;
DSUTILS.forEach(relations, (relation: JSData.RelationDefinition) => {
if (relation.localField === localFieldName) {
match = relation;
// Exit the for loop
return false;
}
});
return match;
}
/**
* @name getChildRelationWithForeignKey
* @desc Given the relationType, find relationship by foreignKey name
* @param relationType The type the relationship represents
* @param foreignKeyName Theforeign key name for the relationship, incase there is more than one relationship on the object of the given type
*/
getChildRelationWithForeignKey(relationType: string, foreignKeyName: string): JSData.RelationDefinition {
relationType = relationType.toLowerCase();
foreignKeyName = foreignKeyName.toLowerCase();
let relations = this.getChildRelations(relationType);
var match: JSData.RelationDefinition = null;
DSUTILS.forEach(relations, (relation: JSData.RelationDefinition) => {
if (relation.foreignKey === foreignKeyName) {
match = relation;
return false;
}
});
return match;
}
/**
* @name enumerateAllChildRelations
* @desc Encapsulates enumerating child relationships
* @param callback A function tobe called back with child relationship data
*/
enumerateAllChildRelations(callback: (relation: JSData.RelationDefinition, index?: number, source?: Object) => boolean): void {
DSUTILS.forEach(this.resourceDef.relationList, (relation: JSData.RelationDefinition, index?: number, source?: Object) => {
if (relation.type === jsDataHasMany || relation.type === jsDataHasOne) {
return callback(relation, index, source);
}
});
}
/**
* @name enumerateAllParentRelations
* @desc Encapsulates enumerating child relationships
* @param callback A function tobe called back with child relationship data
*/
enumerateAllParentRelations(callback: (relation: JSData.RelationDefinition, index?: number, source?: Object) => boolean): void {
DSUTILS.forEach(this.resourceDef.relationList, (relation: JSData.RelationDefinition, index?: number, source?: Object) => {
if (relation.type === jsDataBelongsTo) {
return callback(relation, index, source);
}
});
}
/**
* @name enumerateRelations
* @desc Encapsulates enumerating child relationships
* @param callback A function tobe called back with child relationship data
*/
enumerateRelations(callback: (relation: JSData.RelationDefinition, index?: number, source?: Object) => boolean): void {
DSUTILS.forEach(this.resourceDef.relationList, (relation: JSData.RelationDefinition, index?: number, source?: Object) => {
return callback(relation, index, source);
});
}
//Find relationship by relationship name
private getChildRelations(relationType: string): Array<JSData.RelationDefinition> {
relationType = relationType.toLowerCase();
if (this.resourceDef.relations) {
if (this.resourceDef.relations.hasOne) {
if (this.resourceDef.relations.hasOne[relationType]) {
return this.resourceDef.relations.hasOne[relationType];
}
}
if (this.resourceDef.relations.hasMany) {
if (this.resourceDef.relations.hasMany[relationType]) {
return this.resourceDef.relations.hasMany[relationType];
}
}
let relationlower = relationType.toLowerCase();
let matches: Array<JSData.RelationDefinition> = [];
let relationList = this.resourceDef.relationList;
DSUTILS.forEach<JSData.RelationDefinition>(relationList, (relation: JSData.RelationDefinition) => {
if (relation.type === jsDataHasMany || relation.type === jsDataHasOne) {
if (relationlower === relation.relation) {
matches.push(relation);
}
}
});
LogInfo('Relation Case Insensitive match made of ' + relationType, matches);
return matches;
}
return null;
}
//Find relationship by localField
//private getChildRelationWithLocalField(relationType:string, localFieldName: string): JSData.RelationDefinition {
// var match: JSData.RelationDefinition = null;
// if (this.resourceDef.relations) {
// if (this.resourceDef.relations.hasOne) {
// for (var resourceType in this.resourceDef.relations.hasOne) {
// if (this.resourceDef.relations.hasOne[resourceType]) {
// DSUTILS.forEach(this.resourceDef.relations.hasOne[resourceType], (relationDef: JSData.RelationDefinition) => {
// if (relationDef.localField && relationDef.localField === localFieldName) {
// match = relationDef;
// return false;
// }
// });
// }
// }
// }
// if (!match && this.resourceDef.relations.hasMany) {
// for (var resourceType in this.resourceDef.relations.hasMany) {
// if (this.resourceDef.relations.hasMany[resourceType]) {
// DSUTILS.forEach(this.resourceDef.relations.hasMany[resourceType], (relationDef: JSData.RelationDefinition) => {
// if (relationDef.localField && relationDef.localField === localFieldName) {
// match = relationDef;
// return false;
// }
// });
// }
// }
// }
// if (!match) {
// let localFieldNamelower = localFieldName.toLowerCase();
// let relationList = this.resourceDef['relationlist'];
// DSUTILS.forEach<JSData.RelationDefinition>(relationList, (relation: JSData.RelationDefinition) => {
// if (relation.type === jsDataHasMany || relation.type === jsDataHasOne) {
// if (relation.localField && relation.localField === localFieldName) {
// //if (relationlower === relation.relation) {
// match = relation;
// return false;
// }
// }
// });
// if (match) {
// LogInfo('Relation Case Insensitive match made of ' + localFieldName, [match]);
// }
// }
// }
// return match;
//}
/**
* @name getRelationByLocalField
* @desc Get the relationship for a resorce of a given local field name,
* which should be unique and match payload relationships keys.
* This method returns both parent and child relationship types
* @param relationName The relationship name to find
*/
getRelationByLocalField(relationName: string): JSData.RelationDefinition {
let relationlower = relationName.toLowerCase();
let relationList = this.resourceDef.relationList;
var match: JSData.RelationDefinition = null;
DSUTILS.forEach(relationList, (relation: JSData.RelationDefinition) => {
if (relation.localField === relationlower) {
match = relation;
return false;
}
});
return match;
}
}
class DeSerializeResult {
data: any;
response: JsonApi.JsonApiRequest;
constructor(data: any, response: JsonApi.JsonApiRequest) {
this.data = data;
this.response = response;
}
}
function LogInfo(message: string, data?: any[]): void {
if (console) {
(<Console>console).log(message, data);
}
}
function LogWarning(message: string, data?: any[]): void {
if (console) {
(<Console>console).warn(message, data);
}
}
export class JsonApiHelper {
/*
@Merge Meta data from newly recieved 'data with that of cached data from datastore
*/
private static MergeMetaData(res: JSData.DSResourceDefinition<any>, data: Object) {
if (res) {
var dataMeta = MetaData.TryGetMetaData(data);
if (!dataMeta) {
throw new Error('MergeMetaData failed, target object missing meta data Type:' + res.name);
} else {
let id = data[res.idAttribute];
var exiting = res.get(id);
if (exiting) {
var existingMeta = MetaData.TryGetMetaData(exiting);
if (existingMeta) {
dataMeta.isJsonApiReference = dataMeta.isJsonApiReference || existingMeta.isJsonApiReference;
}
}
// NOTE : This did not do what it was supposed to do...
// Just skip for now
// Should compare new object to existing and update metadata
// If resource is already fully loaded then do not reset flag!!
//dataMeta.isJsonApiReference = dataFullyLoaded;
// see: http://www.js-data.io/docs/dsdefaults#onconflict, onConflict default value is merge
// NOT sure if this is necessary. Not sure if jsdata updates be merging e.g. doing this or by replacing?
//if (resourceFullyLoaded === true && dataFullyLoaded == false) {
// DSUTILS.deepMixIn(data, res);
//}
}
}
}
// Checks if a response contains a header that matches value.
// The comparison is case insensitive, which is a REQUIREMENT
// of http headers but is not implemented by angular.
private static ContainsHeader(headers: { [name: string]: string }, header: string, value: string) {
if (headers) {
for (var key in headers) {
if (key.toLocaleLowerCase() === header.toLocaleLowerCase()) {
var h: string = headers[key];
if (h.toLocaleLowerCase().indexOf(value) > -1) {
return true;
}
}
}
}
return false;
}
public static ContainsJsonApiContentTypeHeader(headers: { [name: string]: string }): boolean {
return JsonApiHelper.ContainsHeader(headers, 'Content-Type', jsonApiContentType);
}
public static AddJsonApiContentTypeHeader(headers: { [name: string]: string }): void {
headers['Content-Type'] = jsonApiContentType;
}
public static AddJsonApiAcceptHeader(headers: { [name: string]: string }): void {
headers['Accept'] = jsonApiContentType;
}
public static FromJsonApiError(response: JsonApi.JsonApiRequest): JsonApi.JsonApiRequest {
var responseObj: JsonApi.JsonApiRequest;
if (response.errors) {
responseObj = new JsonApi.JsonApiRequest();
if (DSUTILS.isArray(response.errors)) {
DSUTILS.forEach(response.errors, (item: JsonApi.JsonApiError) => {
responseObj.WithError(DSUTILS.deepMixIn(new JsonApi.JsonApiError(), item));
});
} else {
responseObj.WithError(DSUTILS.deepMixIn(new JsonApi.JsonApiError(), response.errors));
}
} else {
responseObj = JsonApiHelper.CreateInvalidResponseError(response);
}
return responseObj;
}
// Serialize js-data object as JsonApi request
public static Serialize(options: SerializationOptions, attrs: any, config: JsonApiAdapter.DSJsonApiAdapterOptions): JsonApi.JsonApiRequest {
var result = new JsonApi.JsonApiRequest();
if (DSUTILS.isArray(attrs)) {
//Add Data as array
DSUTILS.forEach(attrs, (item: Object) => {
result.WithData(this.ObjectToJsonApiData(options, item, config));
});
} else {
// JsonAPI single object
result.data = <any>this.ObjectToJsonApiData(options, attrs, config);
}
return result;
}
// DeSerialize Json Api reponse into js-data friendly object graph
public static DeSerialize(options: SerializationOptions, response: JsonApi.JsonApiRequest): DeSerializeResult {
if (response.data === null) {
return new DeSerializeResult([], null);
}
if (DSUTILS.isArray(response.data)) {
if ((<JsonApi.JsonApiData[]>response.data).length === 0) {
return new DeSerializeResult([], null);
}
}
// Array of deserialized objects as a js-data friendly object graph
var newResponse = new JsonApi.JsonApiRequest();
// Required data
if (response.data) {
if (DSUTILS.isArray(response.included)) {
DSUTILS.forEach(response.included, (item: JsonApi.JsonApiData) => {
this.NormaliseLinkFormat(item.links);
for (var relation in item.relationships) {
if (item.relationships[relation]) {
this.NormaliseLinkFormat(item.relationships[relation].links);
var isArray = DSUTILS.isArray( item.relationships[relation].data );
item.relationships[relation] = DSUTILS.deepMixIn(new JsonApi.JsonApiRelationship(isArray), item.relationships[relation]);
}
}
// Add JsonApiData
newResponse.WithIncluded(DSUTILS.deepMixIn(new JsonApi.JsonApiData('unknown'), item));
});
}
// JSON API Specifies that a single data object be returned as an object where as data from a one to many should always be returned in an array.
if (DSUTILS.isArray(response.data)) {
DSUTILS.forEach(<JsonApi.JsonApiData[]>response.data, (item: JsonApi.JsonApiData) => {
this.NormaliseLinkFormat(item.links);
for (var relation in item.relationships) {
if (item.relationships[relation]) {
this.NormaliseLinkFormat(item.relationships[relation].links);
var isArray = DSUTILS.isArray(item.relationships[relation].data);
item.relationships[relation] = DSUTILS.deepMixIn(new JsonApi.JsonApiRelationship(isArray), item.relationships[relation]);
}
}
// Add JsonApiData
newResponse.WithData(DSUTILS.deepMixIn(new JsonApi.JsonApiData(''), item));
});
} else {
let item = (<any>response.data);
this.NormaliseLinkFormat(item.links);
for (var relation in item.relationships) {
if (item.relationships[relation]) {
this.NormaliseLinkFormat(item.relationships[relation].links);
var isArray = DSUTILS.isArray(item.relationships[relation].data);
item.relationships[relation] = DSUTILS.deepMixIn(new JsonApi.JsonApiRelationship(isArray), item.relationships[relation]);
}
}
// Add JsonApiData
newResponse.WithSingleData(DSUTILS.deepMixIn(new JsonApi.JsonApiData(''), <any>response.data));
}
}
if (response.links) {
this.NormaliseLinkFormat(response.links);
// We need somewhere global to store these link!!
for (var link in response.links) {
if (response.links[link]) {
newResponse.AddLink(link, response.links[link]);
}
}
}
//------ New algorithum ------------
//var data = {};
//var included = {};
//[1] Deserialize all data
//[2] Deserialize all included data
//[3] Iterate over included data relationships set to reference other included data.
//[4] Iterate over data relationships and set to reference included data if available.
var data = {};
var included = {};
var jsDataJoiningTables = {};
//Store data in a type,id key pairs
if (DSUTILS.isArray(newResponse.data)) {
DSUTILS.forEach(<JsonApi.JsonApiData[]>newResponse.data, (item: JsonApi.JsonApiData) => {
data[item.type] = data[item.type] || {};
data[item.type][item.id] = this.DeserializeJsonApiData(options, item, jsDataJoiningTables);
// Data section is returned to js data so does not need to be inserted again from anywhere else!!
var metaData = MetaData.TryGetMetaData(data[item.type][item.id]);
metaData.incrementReferenceCount();
});
} else {
let item: JsonApi.JsonApiData = <JsonApi.JsonApiData>newResponse.data;
if (item) {
data[item.type] = data[item.type] || {};
data[item.type][item.id] = this.DeserializeJsonApiData(options, item, jsDataJoiningTables);
// Data section is returned to js data so does not need to be inserted again from anywhere else!!
var metaData = MetaData.TryGetMetaData(data[item.type][item.id]);
metaData.incrementReferenceCount();
}
}
// Attach liftime events
JsonApiHelper.AssignLifeTimeEvents(options.def());
//Store data included as type,id key pairs
DSUTILS.forEach(newResponse.included, (item: JsonApi.JsonApiData) => {
var includedDef = options.getResource(item.type);
included[item.type] = included[item.type] || {};
included[item.type][item.id] = this.DeserializeJsonApiData(includedDef, item, jsDataJoiningTables);
// Attach liftime events
JsonApiHelper.AssignLifeTimeEvents(includedDef.def());
});
// This is an array of top level objects with child, object references and included objects
//var jsDataArray = this.NormaliseDataObjectGraph(data, included, jsDataJoiningTables, options);
var itemSelector = (item: ModelPlaceHolder): any => {
//If included or data or joining data contains the reference we are looking for then use it
let newItem = included[item.type] ? included[item.type][item.id] :
(data[item.type] ? data[item.type][item.id] :
(jsDataJoiningTables[item.type] ? jsDataJoiningTables[item.type][item.id] : null));
return newItem;
};
var toManyPlaceHolderVisitor = (data: Object): any => {
if (data.constructor === ModelPlaceHolder) {
let itemPlaceHolder = <ModelPlaceHolder>data;
//If included or data or joining data contains the reference we are looking for then use it
let newItem = itemSelector(itemPlaceHolder);
if (newItem) {
//Included item found!!
// Apply foreign key to js-data object
if (itemPlaceHolder.keyName) {
newItem[itemPlaceHolder.keyName] = itemPlaceHolder.keyValue;
}
//TODO : What about local keys, when this is a locaKeys array we must append to it!!
// These are/have ben set directly on the parent in Deserialize
// To avoid circular dependanciesin the object graph that we send to jsData only include an object once.
// Otherwise it is enough to reference an existing object by its foreighn key
var meta = MetaData.TryGetMetaData(newItem);
if (meta.incrementReferenceCount() === 1) {
return newItem;
} else {
return undefined;
}
} else {
//This item dosn't exist so create a model reference to it
let newItem = <any>{};
// Apply foreign key to js-data object
if (itemPlaceHolder.keyName) {
newItem[itemPlaceHolder.keyName] = itemPlaceHolder.keyValue;
}
//TODO : What about local keys, when this is a locaKeys array we must append to it!!
// These are/have ben set directly on the parent in Deserialize
// Replace item in array with plain object, but with Primary key or any foreign keys set
var itemOptions = options.getResource(itemPlaceHolder.type);
let metaData = new MetaData(itemPlaceHolder.type);
metaData.isJsonApiReference = true;
newItem[JSONAPI_META] = metaData;
newItem[itemOptions.idAttribute] = itemPlaceHolder.id;
// Attach liftime events
JsonApiHelper.AssignLifeTimeEvents(itemOptions.def());
return newItem;
}
}
return data;
};
var toOnePlaceHolderVisitor = (data: Object, localField: string, opt: SerializationOptions): any => {
var val = data[localField];
if (val && val.constructor === ModelPlaceHolder) {
var itemPlaceHolder = <ModelPlaceHolder>val;
//If included or data or joining data contains the reference we are looking for then use it
var newItem = itemSelector(itemPlaceHolder);
if (newItem) {
// To avoid circular dependancies in the object graph that we send to jsData only include an object once.
// Otherwise it is enough to reference an existing object by its foreign key
var meta = MetaData.TryGetMetaData(newItem);
if (meta.incrementReferenceCount() === 1) {
return newItem;
} else {
// hasOne uses foreignKey or localKey fieldand localField
// Apply foreign key to js-data object hasOne
if (itemPlaceHolder.keyName) {
newItem[itemPlaceHolder.keyName] = itemPlaceHolder.keyValue;
} else {
var relation = opt.getParentRelationByLocalField(localField);
//Belongs to uses localfield and localkey
if (relation && relation.type === jsDataBelongsTo) {
data[relation.localKey] = itemPlaceHolder.id;
}
}
return undefined;
}
} else {
//This item dosn't exist so create a model reference to it
newItem = {};
// Replace item in array with plain object, but with Primary key or any foreign keys set
var itemOptions = options.getResource(itemPlaceHolder.type);
// Apply keys, foreign and local to js-data object
if (itemPlaceHolder.keyName) {
newItem[itemPlaceHolder.keyName] = itemPlaceHolder.keyValue;
}
let metaData = new MetaData(itemPlaceHolder.type);
metaData.isJsonApiReference = true;
newItem[JSONAPI_META] = metaData;
newItem[itemOptions.idAttribute] = itemPlaceHolder.id;
// Attach liftime events
JsonApiHelper.AssignLifeTimeEvents(itemOptions.def());
return newItem;
}
}
return data[localField];
};
this.RelationshipVisitor(data, options, toManyPlaceHolderVisitor, toOnePlaceHolderVisitor);
this.RelationshipVisitor(included, options, toManyPlaceHolderVisitor, toOnePlaceHolderVisitor);
this.RelationshipVisitor(jsDataJoiningTables, options, toManyPlaceHolderVisitor, toOnePlaceHolderVisitor);
// Register all data types for life time events
var registration = (type: string) => {
var typeOptions = options.getResource(type);
if (typeOptions) {
// Attach liftime events
JsonApiHelper.AssignLifeTimeEvents(typeOptions.def());
} else {
throw new Error('Unknow type:' + type);
}
};
this.DataTypeVisitor(data, registration);
this.DataTypeVisitor(included, registration);
this.DataTypeVisitor(jsDataJoiningTables, registration);
//this.ReplaceModelPlaceHolderRelations(included, options);
//this.ReplaceModelPlaceHolderRelations(jsDataJoiningTables, options);
// Copy top level objects
// This is an array of top level objects with child, object references and included objects
if (data) {
var jsDataArray = [];
if (DSUTILS.isArray(newResponse.data)) {
DSUTILS.forEach(<JsonApi.JsonApiData[]>newResponse.data, (item: JsonApi.JsonApiData) => {
if (data[item.type] && data[item.type][item.id]) {
jsDataArray.push(data[item.type][item.id]);
}
});
return new DeSerializeResult(jsDataArray, newResponse);
} else {
if (newResponse.data) {
var item = <JsonApi.JsonApiData>newResponse.data;
if (data[item.type] && data[item.type][item.id]) {
return new DeSerializeResult(data[item.type][item.id], newResponse);
}
} else {
return new DeSerializeResult(null, newResponse);
}
}
}
}
private static RelationshipVisitor(data: any, options: SerializationOptions,
toManyVisitor: (relationData: Object) => any,
toOneVisitor: (relationData: Object, fieldName: string, opt: SerializationOptions) => any) {
if (data) {
// Replace data references with included data where available
for (var dataType in data) {
if (data[dataType]) {
for (var dataId in data[dataType]) {
if (data[dataType][dataId]) {
var dataObject = data[dataType][dataId];
for (var prop in dataObject) {
if (DSUTILS.isArray(dataObject[prop])) {
// hasMany Relationship
// With many relations we can set the foreign key and delete the object to prevent circular relations
DSUTILS.forEach(dataObject[prop], (item: ModelPlaceHolder, index: number, source: Array<ModelPlaceHolder>) => {
var result = toManyVisitor(item);
source[index] = result;
});
// Remove un-used array items
for (var i = dataObject[prop].length; i >= 0; i--) {
if (!dataObject[prop][i]) {
dataObject[prop].splice(i, 1);
}
}
// Remove array if empty
if (dataObject[prop].length === 0) {
delete dataObject[prop];
}
} else {
// hasOne, belongsTo relations
// hasOne or parent Relationship
var opt = options.getResource(dataType);
// Has one relations we can set the foreign key and remove the object
var result = toOneVisitor(dataObject, prop, opt);
if (result !== undefined) {
dataObject[prop] = result;
} else {
delete dataObject[prop];
}
}
}
}
}
}
}
}
}
private static DataTypeVisitor(data: any, visitor: (type: string) => any) {
// Replace data references with included data where available
for (var dataType in data) {
if (dataType) {
visitor(dataType);
}
}
}
private static CreateInvalidResponseError(response: any) {
var responseObj = new JsonApi.JsonApiRequest();
var e = new JsonApi.JsonApiError();
e.title = 'Invalid response';
e.detail = 'Response is incorrectly formed: ' + JSON.stringify(response);
responseObj.WithError(e);
return responseObj;
}
// Convert js-data object to JsonApi request
private static ObjectToJsonApiData(options: SerializationOptions, attrs: Object, config: JsonApiAdapter.DSJsonApiAdapterOptions): JsonApi.JsonApiData {
if (!options.type) {
throw new Error('Type required within options');
}
var data = new JsonApi.JsonApiData(options.type);
//JsonApi id is always a string, it can be empty for a new unstored object!
if (attrs[options.idAttribute]) {
data.WithId(attrs[options.idAttribute]);
}
// Take object attributes
if (config.changes && attrs[options.idAttribute]) {
var id = attrs[options.idAttribute];
if ((<JSData.DSResourceDefinition<any>>options.def()).hasChanges(id)) {
var changes = (<JSData.DSResourceDefinition<any>>options.def()).changes(id);
DSUTILS.forOwn(changes['added'], (value: any, prop: string) => {
// Skip id attribute as it has already been copied to the id field out side of the attributes collection
// Skip any non-json api compliant tags
if (prop !== options.idAttribute && prop !== JSONAPI_META && prop.indexOf('$') < 0) {
data.WithAttribute(prop, value);
}
});
DSUTILS.forOwn(changes['changed'], (value: any, prop: string) => {
// Skip id attribute as it has already been copied to the id field out side of the attributes collection
// Skip any non-json api compliant tags
if (prop !== options.idAttribute && prop !== JSONAPI_META && prop.indexOf('$') < 0) {
data.WithAttribute(prop, value);
}
});
DSUTILS.forOwn(changes['removed'], (value: any, prop: string) => {
// Skip id attribute as it has already been copied to the id field out side of the attributes collection
// Skip any non-json api compliant tags
if (prop !== options.idAttribute && prop !== JSONAPI_META && prop.indexOf('$') < 0) {
data.WithAttribute(prop, null);
}
});
}
} else {
DSUTILS.forOwn(attrs, (value: any, prop: string) => {
// Skip id attribute as it has already been copied to the id field out side of the attributes collection
// Skip any non-json api compliant tags
if (prop !== options.idAttribute && prop !== JSONAPI_META && prop.indexOf('$') < 0) {
data.WithAttribute(prop, value);
}
});
}
// Get object related data
// Create should always send relationships
if (config.jsonApi.updateRelationships === true) {
options.enumerateAllChildRelations( (relation: JSData.RelationDefinition) => {
// Process child definition
var relatedDef = options.getResource(relation.relation);
if (relation.type === jsDataHasMany) {
var relationship = new JsonApi.JsonApiRelationship(true);
var relatedObjects = DSUTILS.get<any[]>(attrs, relation.localField);
if (relatedObjects) {
//This is a relationship so add data as relationship
DSUTILS.forEach(relatedObjects, (item: any) => {
relationship.WithData(relation.relation, item[relatedDef.idAttribute]);
});
}
data.WithRelationship(relation.localField, relationship);
}