Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 45 additions & 23 deletions packages/concerto-core/src/serializer/jsongenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import Resource from '../model/resource';
import Typed from '../model/typed';
import ModelUtil from '../modelutil';
import { NullUtil as Util } from '@accordproject/concerto-util';
import dayjs from '../dayjs-setup';

/**
* Converts the contents of a Resource to JSON. The parameters
Expand Down Expand Up @@ -68,7 +69,7 @@ class JSONGenerator {
return this.visitClassDeclaration(thing, parameters);
} else if (thing.isRelationship?.()) {
return this.visitRelationshipDeclaration(thing, parameters);
}else if (thing.isMapDeclaration?.()) {
} else if (thing.isMapDeclaration?.()) {
return this.visitMapDeclaration(thing, parameters);
} else if (thing.isTypeScalar?.()) {
return this.visitField(thing.getScalarField(), parameters);
Expand Down Expand Up @@ -102,26 +103,36 @@ class JSONGenerator {

if (mapDeclaration.getValue().isRelationship()) {
value = this.processRelationship(mapDeclaration.getValue(), value, parameters);
} else if (typeof value === 'object') {
// Resolve the declaration for the map value. Prefer the instance's
// own fully-qualified type so that polymorphic values (subclasses of
// the map's declared value type) are serialized using their actual
// declaration. Fall back to the map's declared value type - honouring
// imports - for instances that do not expose a fully-qualified type
// (e.g. those created by the populator). Either way the value concept
// may live in another namespace, so resolve it via the model manager
// rather than the map's own model file.
const modelFile = mapDeclaration.getModelFile();
const valueType = typeof value.getFullyQualifiedType === 'function'
? value.getFullyQualifiedType()
: modelFile.getFullyQualifiedTypeName(mapDeclaration.getValue().getType());
const decl = modelFile.getModelManager().getType(valueType);
} else if (!Util.isNull(value)) {
if (typeof value === 'object' && typeof value.isBefore === 'function') {
value = this.formatDateTime(value);
} else if (typeof value === 'object') {
const modelFile = mapDeclaration.getModelFile();
const isPrimitive = ModelUtil.isPrimitiveType(mapDeclaration.getValue().getType());
const isScalar = ModelUtil.isScalar(mapDeclaration.getValue());
if (!isPrimitive && !isScalar) {
// Resolve the declaration for the map value. Prefer the instance's
// own fully-qualified type so that polymorphic values (subclasses of
// the map's declared value type) are serialized using their actual
// declaration. Fall back to the map's declared value type - honouring
// imports - for instances that do not expose a fully-qualified type
// (e.g. those created by the populator). Either way the value concept
// may live in another namespace, so resolve it via the model manager
// rather than the map's own model file.
const valueType = typeof value.getFullyQualifiedType === 'function'
? value.getFullyQualifiedType()
: modelFile.getFullyQualifiedTypeName(mapDeclaration.getValue().getType());
const decl = modelFile.getModelManager().getType(valueType);

// convert declaration to JSON representation
parameters.stack.push(value);
const jsonValue = decl.accept(this, parameters);
if (decl && !decl.isScalarDeclaration?.()) {
// convert declaration to JSON representation
parameters.stack.push(value);
const jsonValue = decl.accept(this, parameters);

value = jsonValue;
value = jsonValue;
}
}
}
}

map.set(key, value);
Expand Down Expand Up @@ -218,6 +229,19 @@ class JSONGenerator {
return result;
}

/**
* Formats a DateTime object to an ISO-8601 string respecting utcOffset.
* @param {Object} obj - the dayjs instance to format
* @return {string} the formatted DateTime string
* @private
*/
formatDateTime(obj) {
const dayjsObj = typeof obj.utc === 'function' ? obj.utc() : dayjs.utc(obj);
const objWithOffset = dayjsObj.utcOffset(this.utcOffset);
const inZ = objWithOffset.utcOffset() === 0;
return objWithOffset.format(`YYYY-MM-DDTHH:mm:ss.SSS${inZ ? '[Z]' : 'Z'}`);
}

/**
* Converts to JSON safe format.
*
Expand All @@ -229,9 +253,7 @@ class JSONGenerator {
switch (field.getType()) {
case 'DateTime':
{
const objWithOffset = obj.utc().utcOffset(this.utcOffset);
const inZ = objWithOffset.utcOffset() === 0;
return objWithOffset.format(`YYYY-MM-DDTHH:mm:ss.SSS${inZ ? '[Z]': 'Z'}`);
return this.formatDateTime(obj);
}
case 'Integer':
case 'Long': {
Expand Down Expand Up @@ -323,4 +345,4 @@ class JSONGenerator {
}

export { JSONGenerator };
export default JSONGenerator;
export default JSONGenerator;
7 changes: 5 additions & 2 deletions packages/concerto-core/src/serializer/resourcevalidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,11 +153,14 @@ class ResourceValidator {
throw new Error(`Model violation in ${mapDeclaration.getFullyQualifiedName()}. Expected Type of String but found '${value}' instead.`);
}
break;
case 'DateTime':
if (typeof value !== 'string' || !dayjs.utc(value).isValid()) {
case 'DateTime': {
const isDayJs = typeof value === 'object' && typeof value?.isBefore === 'function' && value.isValid();
const isValidDateString = typeof value === 'string' && dayjs.utc(value).isValid();
if (!isDayJs && !isValidDateString) {
throw new Error(`Model violation in ${mapDeclaration.getFullyQualifiedName()}. Expected Type of DateTime but found '${value}' instead.`);
}
break;
}
case 'Boolean':
if (typeof value !== 'boolean') {
throw new Error(`Model violation in ${mapDeclaration.getFullyQualifiedName()}. Expected Type of Boolean but found ${typeof value} instead, for value '${value}'.`);
Expand Down
66 changes: 66 additions & 0 deletions packages/concerto-core/test/serializer/maptype/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,72 @@ describe('Serializer', () => {
resource.birthday.get('Alice').should.equal('2024-10-28T01:02:03Z');
});

it('should serialize a map with dayjs DateTime values (#1546)', () => {
let concept = factory.newConcept('org.acme.sample@1.0.0', 'Concepts');

concept.birthday = new Map();
concept.birthday.set('Bob', dayjs('2023-10-28T01:02:03.000Z'));
concept.birthday.set('Alice', dayjs('2024-10-28T01:02:03.000Z'));

const json = serializer.toJSON(concept);

json.should.deep.equal({
$class: 'org.acme.sample@1.0.0.Concepts',
birthday: {
Bob: '2023-10-28T01:02:03.000Z',
Alice: '2024-10-28T01:02:03.000Z'
}
});
});

it('should serialize a map with dayjs DateTime scalar values (#1546)', () => {
let concept = factory.newConcept('org.acme.sample@1.0.0', 'Concepts');

concept.celebration = new Map();
concept.celebration.set('BobBirthday', dayjs('2022-11-28T01:02:03.000Z'));

const json = serializer.toJSON(concept);

json.should.deep.equal({
$class: 'org.acme.sample@1.0.0.Concepts',
celebration: {
BobBirthday: '2022-11-28T01:02:03.000Z'
}
});
});

it('should serialize a map with null value without throwing TypeNotFoundException (#1546)', () => {
let concept = factory.newConcept('org.acme.sample@1.0.0', 'Concepts');

concept.birthday = new Map();
concept.birthday.set('Bob', null);

const json = serializer.toJSON(concept, { validate: false });

json.should.deep.equal({
$class: 'org.acme.sample@1.0.0.Concepts',
birthday: {
Bob: null
}
});
});

it('should serialize a map with dayjs DateTime values respecting custom utcOffset (#1546)', () => {
let concept = factory.newConcept('org.acme.sample@1.0.0', 'Concepts');

concept.birthday = new Map();
concept.birthday.set('Bob', dayjs('2023-10-28T01:02:03.000Z'));

const json = serializer.toJSON(concept, { utcOffset: 330 });

json.should.deep.equal({
$class: 'org.acme.sample@1.0.0.Concepts',
birthday: {
Bob: '2023-10-28T06:32:03.000+05:30'
}
});
});

it('should serialize -> deserialize with a Map <String, Scalar>', () => {
// setup
let concept = factory.newConcept('org.acme.sample@1.0.0', 'Concepts');
Expand Down
Loading