-
-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathjsongenerator.js
324 lines (306 loc) · 12.2 KB
/
jsongenerator.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
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
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const Resource = require('../model/resource');
const Typed = require('../model/typed');
const ModelUtil = require('../modelutil');
const Util = require('../util');
/**
* Converts the contents of a Resource to JSON. The parameters
* object should contain the keys
* 'stack' - the TypedStack of objects being processed. It should
* start with a Resource.
* 'modelManager' - the ModelManager to use.
* @private
* @class
* @memberof module:concerto-core
*/
class JSONGenerator {
/**
* Constructor.
* @param {boolean} [convertResourcesToRelationships] Convert resources that
* are specified for relationship fields into relationships, false by default.
* @param {boolean} [permitResourcesForRelationships] Permit resources in the
* place of relationships (serializing them as resources), false by default.
* @param {boolean} [deduplicateResources] If resources appear several times
* in the object graph only the first instance is serialized, with only the $id
* written for subsequent instances, false by default.
* @param {boolean} [convertResourcesToId] Convert resources that
* are specified for relationship fields into their id, false by default.
* @param {boolean} [ergo] target ergo.
* @param {number} [utcOffset] UTC Offset for DateTime values.
*/
constructor(convertResourcesToRelationships, permitResourcesForRelationships, deduplicateResources, convertResourcesToId, ergo, utcOffset) {
this.convertResourcesToRelationships = convertResourcesToRelationships;
this.permitResourcesForRelationships = permitResourcesForRelationships;
this.deduplicateResources = deduplicateResources;
this.convertResourcesToId = convertResourcesToId;
this.ergo = ergo;
this.utcOffset = utcOffset || 0;
}
/**
* Visitor design pattern
* @param {Object} thing - the object being visited
* @param {Object} parameters - the parameter
* @return {Object} the result of visiting or null
* @private
*/
visit(thing, parameters) {
if (thing.isClassDeclaration?.()) {
return this.visitClassDeclaration(thing, parameters);
} else if (thing.isRelationship?.()) {
return this.visitRelationshipDeclaration(thing, parameters);
} else if (thing.isTypeScalar?.()) {
return this.visitField(thing.getScalarField(), parameters);
} else if (thing.isField?.()) {
return this.visitField(thing, parameters);
} else {
throw new Error('Unrecognised ' + JSON.stringify(thing));
}
}
/**
* Visitor design pattern
* @param {ClassDeclaration} classDeclaration - the object being visited
* @param {Object} parameters - the parameter
* @return {Object} the result of visiting or null
* @private
*/
visitClassDeclaration(classDeclaration, parameters) {
const obj = parameters.stack.pop();
if (!((obj instanceof Resource))) {
throw new Error('Expected a Resource, but found ' + obj);
}
let result = {};
let id = null;
if (obj.isIdentifiable() && this.deduplicateResources) {
id = obj.toURI();
if( parameters.dedupeResources.has(id)) {
return id;
}
else {
parameters.dedupeResources.add(id);
}
}
result.$class = classDeclaration.getFullyQualifiedName();
if(this.deduplicateResources && id) {
result.$id = id;
}
// Walk each property of the class declaration
const properties = classDeclaration.getProperties();
for (let index in properties) {
const property = properties[index];
const value = obj[property.getName()];
if (!Util.isNull(value)) {
parameters.stack.push(value);
result[property.getName()] = property.accept(this, parameters);
} else if (this.ergo) {
result[property.getName()] = { '$right' : null };
}
}
if (this.ergo) {
const theClass = result.$class;
delete result.$class;
result = {
$class: {
$coll: [theClass],
$length: 1
},
$data: result,
};
}
return result;
}
/**
* Visitor design pattern
* @param {Field} field - the object being visited
* @param {Object} parameters - the parameter
* @return {Object} the result of visiting or null
* @private
*/
visitField(field, parameters) {
const obj = parameters.stack.pop();
let result;
if (field.isArray()) {
let array = [];
// Walk the object
for (let index in obj) {
const item = obj[index];
if (!field.isPrimitive() && !ModelUtil.isEnum(field)) {
parameters.stack.push(item, Typed);
const classDeclaration = parameters.modelManager.getType(item.getFullyQualifiedType());
array.push(classDeclaration.accept(this, parameters));
} else {
array.push(this.convertToJSON(field, item));
}
}
if (this.ergo) {
result = {
$coll: array,
$length: array.length
};
} else {
result = array;
}
} else if (field.isPrimitive()) {
result = this.convertToJSON(field, obj);
} else if (ModelUtil.isEnum(field)) {
if (this.ergo) {
// Boxes an enum value to the expected combination of sum types
const enumDeclaration = field.getParent().getModelFile().getType(field.getType());
const enumName = enumDeclaration.getFullyQualifiedName();
const properties = enumDeclaration.getProperties();
let either = { '$left' : obj };
for(let n=0; n < properties.length; n++) {
const property = properties[n];
if(property.getName() === obj) {
break;
} else {
either = { '$right' : either };
}
}
result = { '$class' : [enumName], '$data': either };
} else {
result = this.convertToJSON(field, obj);
}
} else {
parameters.stack.push(obj);
const classDeclaration = parameters.modelManager.getType(obj.getFullyQualifiedType());
result = classDeclaration.accept(this, parameters);
}
if (field.isOptional()) {
if (this.ergo) {
if (result) {
result = { '$left' : result };
} else {
result = { '$right' : result };
}
}
}
return result;
}
/**
* Converts to JSON safe format.
*
* @param {Field} field - the field declaration of the object
* @param {Object} obj - the object to convert to text
* @return {Object} the text JSON safe representation
*/
convertToJSON(field, obj) {
switch (field.getType()) {
case 'DateTime':
{
const objWithOffset = obj.utc().utcOffset(this.utcOffset);
if (this.ergo) {
return objWithOffset;
} else {
const inZ = objWithOffset.utcOffset() === 0;
return objWithOffset.format(`YYYY-MM-DDTHH:mm:ss.SSS${inZ ? '[Z]': 'Z'}`);
}
}
case 'Integer':
case 'Long': {
if (this.ergo) {
return { $nat: obj };
} else {
return obj;
}
}
case 'Double':
case 'Boolean':
default:
{
return obj;
}
}
}
/**
* Visitor design pattern
* @param {RelationshipDeclaration} relationshipDeclaration - the object being visited
* @param {Object} parameters - the parameter
* @return {Object} the result of visiting or null
* @private
*/
visitRelationshipDeclaration(relationshipDeclaration, parameters) {
const obj = parameters.stack.pop();
let result;
if (relationshipDeclaration.isArray()) {
let array = [];
// walk the object
for (let index in obj) {
const item = obj[index];
if (this.permitResourcesForRelationships && item instanceof Resource) {
let fqi = item.getFullyQualifiedIdentifier();
if (parameters.seenResources.has(fqi)) {
let relationshipText = this.getRelationshipText(relationshipDeclaration, item);
array.push(relationshipText);
} else {
parameters.seenResources.add(fqi);
parameters.stack.push(item, Resource);
const classDecl = parameters.modelManager.getType(relationshipDeclaration.getFullyQualifiedTypeName());
array.push(classDecl.accept(this, parameters));
parameters.seenResources.delete(fqi);
}
} else {
let relationshipText = this.getRelationshipText(relationshipDeclaration, item);
array.push(relationshipText);
}
}
if (this.ergo) {
result = {
$coll: array,
$length: array.length
};
} else {
result = array;
}
} else if (this.permitResourcesForRelationships && obj instanceof Resource) {
let fqi = obj.getFullyQualifiedIdentifier();
if (parameters.seenResources.has(fqi)) {
let relationshipText = this.getRelationshipText(relationshipDeclaration, obj);
result = relationshipText;
} else {
parameters.seenResources.add(fqi);
parameters.stack.push(obj, Resource);
const classDecl = parameters.modelManager.getType(relationshipDeclaration.getFullyQualifiedTypeName());
result = classDecl.accept(this, parameters);
parameters.seenResources.delete(fqi);
}
} else {
let relationshipText = this.getRelationshipText(relationshipDeclaration, obj);
result = relationshipText;
}
return result;
}
/**
* Returns the persistent format for a relationship.
* @param {RelationshipDeclaration} relationshipDeclaration - the relationship being persisted
* @param {Identifiable} relationshipOrResource - the relationship or the resource
* @returns {string} the text to use to persist the relationship
*/
getRelationshipText(relationshipDeclaration, relationshipOrResource) {
if (relationshipOrResource instanceof Resource) {
const allowRelationships =
this.convertResourcesToRelationships || this.permitResourcesForRelationships;
if (!allowRelationships) {
throw new Error('Did not find a relationship for ' + relationshipDeclaration.getFullyQualifiedTypeName() + ' found ' + relationshipOrResource);
}
}
if (this.convertResourcesToId) {
return relationshipOrResource.getIdentifier();
} else {
return relationshipOrResource.toURI();
}
}
}
module.exports = JSONGenerator;