Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(smart views): smart views can access nested relationship #203

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
83 changes: 66 additions & 17 deletions src/serializers/resource.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,30 @@ function ResourceSerializer(
this.perform = () => {
const typeForAttributes = {};

function getAttributesFor(dest, fields) {
function getRelatedLinkForHasMany(relatedModelName, relationshipName) {
return (record, current, parent) => {
if (current && current[relationshipName]) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not want the link to be set if the relation is already included in the payload

return null;
}
return `/forest/${relatedModelName}/${parent.id}/relationships/${relationshipName}`;
};
}

function getReferenceField(referenceSchema, field) {
let fieldReference = referenceSchema.idField;

if (_.isArray(field.type) && !fieldReference && referenceSchema.isVirtual) {
if (_.find(referenceSchema.fields, (subField) => subField.field === 'id')) {
fieldReference = 'id';
} else {
logger.warn(`Cannot find the 'idField' attribute in your '${referenceSchema.name}' Smart Collection declaration.`);
}
}

return fieldReference || 'id';
}

function getAttributesFor(dest, fields, include = true) {
_.map(fields, (field) => {
detectFieldWithSpecialFormat(field);

Expand All @@ -68,7 +91,7 @@ function ResourceSerializer(
attributes: getFieldsNames(field.type.fields),
};

getAttributesFor(dest[field.field], field.type.fields);
getAttributesFor(dest[field.field], field.type.fields, include);
} else if (field.reference) {
const referenceType = field.reference.split('.')[0];
const referenceSchema = Schemas.schemas[referenceType];
Expand All @@ -79,33 +102,31 @@ function ResourceSerializer(
return;
}

let fieldReference = referenceSchema.idField;

if (_.isArray(field.type) && !fieldReference && referenceSchema.isVirtual) {
if (_.find(referenceSchema.fields, (schemaField) => schemaField.field === 'id')) {
fieldReference = 'id';
} else {
logger.warn(`Cannot find the 'idField' attribute in your '${referenceSchema.name}' Smart Collection declaration.`);
}
}
const fieldReference = getReferenceField(referenceSchema, field);

_.each(referenceSchema.fields, (schemaField) => {
detectFieldWithSpecialFormat(schemaField, fieldName);
});

const relatedFunction = field.relationship === 'BelongsTo'
? null
: getRelatedLinkForHasMany(modelName, field.field);
dest[fieldName] = {
ref: fieldReference,
nullIfMissing: true,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need this or the links will not be included if the relation is not in the records sent to the serializer

attributes: getFieldsNames(referenceSchema.fields),
relationshipLinks: {
related: (dataSet) => ({
href: `/forest/${Implementation.getModelName(model)}/${dataSet[schema.idField]}/relationships/${field.field}`,
}),
related: relatedFunction,
},
};

if (_.isArray(field.type)) {
dest[fieldName].ignoreRelationshipData = true;
if (_.isArray(field.type) || !include) {
dest[fieldName].ignoreRelationshipData = include;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not include from second level (We never include relations of a relation)

dest[fieldName].included = false;
} else if (include) {
const referenceFields = referenceSchema.fields
.filter((subField) => subField.reference);
getAttributesFor(dest[fieldName], referenceFields, false);
}
}
}
Expand Down Expand Up @@ -141,6 +162,34 @@ function ResourceSerializer(
});
}

function defineRelationshipId(innerRecords, fields, goDeeper = true) {
const recordArray = _.isArray(innerRecords) ? innerRecords : [innerRecords];
recordArray.forEach((record) => {
fields.forEach((field) => {
if (!field.reference) {
return;
}

const fieldName = field.field;
const [referenceType, referenceKey] = field.reference.split('.');
const referenceSchema = Schemas.schemas[referenceType];
if (goDeeper && record[fieldName]) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We only do it on one level. But we could do it recursively like on forest-rails (@arnaudbesnier Your call)

defineRelationshipId(record[fieldName], referenceSchema.fields, false);
}

if (field.relationship === 'BelongsTo') {
if (!record[fieldName]) {
const fieldReference = getReferenceField(referenceSchema, field);

record[fieldName] = {
[fieldReference]: record[referenceKey],
};
}
}
});
});
}

const attributes = getFieldsNames(schema.fields);

const serializationOptions = {
Expand Down Expand Up @@ -171,7 +220,7 @@ function ResourceSerializer(
}

getAttributesFor(serializationOptions, schema.fields);

defineRelationshipId(records, schema.fields);
// NOTICE: Format Dateonly field types before serialization.
if (_.isArray(records)) {
_.each(records, (record) => { formatFields(record); });
Expand Down
87 changes: 87 additions & 0 deletions test/fixtures/jedis-schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
module.exports = {
name: 'jedis',
idField: 'id',
primaryKeys: ['id'],
isCompositePrimary: false,
fields: [
{
field: 'id',
type: 'String',
columnName: 'id',
primaryKey: true,
isRequired: true,
validations: [Array],
defaultValue: null,
isReadOnly: false,
isSortable: true,
isFilterable: true,
isVirtual: false,
description: null,
reference: null,
inverseOf: null,
relationships: null,
enums: null,
integration: null,
},
{
field: 'name',
type: 'String',
isVirtual: false,
isFilterable: true,
isSortable: true,
isReadOnly: false,
defaultValue: null,
isRequired: true,
description: null,
reference: null,
inverseOf: null,
relationships: null,
enums: null,
validations: [],
integration: null,
},
{
field: 'padawans',
type: ['String'],
isVirtual: false,
isFilterable: true,
isSortable: true,
isReadOnly: false,
defaultValue: null,
isRequired: true,
description: null,
reference: 'padawans.id',
inverseOf: 'master',
relationships: 'HasMany',
enums: null,
validations: [],
integration: null,
},
{
field: 'worstEnemy',
type: 'String',
defaultValue: null,
isRequired: false,
isReadOnly: false,
isSortable: true,
isFilterable: true,
isVirtual: false,
description: null,
reference: 'siths.id',
inverseOf: null,
relationships: 'BelongsTo',
enums: null,
validations: [],
integration: null,
},
],
isSearchable: true,
actions: [],
segments: [],
onlyForRelationships: false,
isVirtual: false,
isReadOnly: false,
paginationType: 'page',
icon: null,
integration: null,
};
70 changes: 70 additions & 0 deletions test/fixtures/padawans-schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
module.exports = {
name: 'padawans',
idField: 'id',
primaryKeys: ['id'],
isCompositePrimary: false,
fields: [
{
field: 'id',
type: 'String',
columnName: 'id',
primaryKey: true,
isRequired: true,
validations: [Array],
defaultValue: null,
isReadOnly: false,
isSortable: true,
isFilterable: true,
isVirtual: false,
description: null,
reference: null,
inverseOf: null,
relationships: null,
enums: null,
integration: null,
},
{
field: 'name',
type: 'String',
isVirtual: false,
isFilterable: true,
isSortable: true,
isReadOnly: false,
defaultValue: null,
isRequired: true,
description: null,
reference: null,
inverseOf: null,
relationships: null,
enums: null,
validations: [],
integration: null,
},
{
field: 'master',
type: 'String',
defaultValue: null,
isRequired: false,
isReadOnly: false,
isSortable: true,
isFilterable: true,
isVirtual: false,
description: null,
reference: 'jedis.id',
inverseOf: null,
relationships: 'BelongsTo',
enums: null,
validations: [],
integration: null,
},
],
isSearchable: true,
actions: [],
segments: [],
onlyForRelationships: false,
isVirtual: false,
isReadOnly: false,
paginationType: 'page',
icon: null,
integration: null,
};
70 changes: 70 additions & 0 deletions test/fixtures/siths-schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
module.exports = {
name: 'siths',
idField: 'id',
primaryKeys: ['id'],
isCompositePrimary: false,
fields: [
{
field: 'id',
type: 'String',
columnName: 'id',
primaryKey: true,
isRequired: true,
validations: [Array],
defaultValue: null,
isReadOnly: false,
isSortable: true,
isFilterable: true,
isVirtual: false,
description: null,
reference: null,
inverseOf: null,
relationships: null,
enums: null,
integration: null,
},
{
field: 'name',
type: 'String',
isVirtual: false,
isFilterable: true,
isSortable: true,
isReadOnly: false,
defaultValue: null,
isRequired: true,
description: null,
reference: null,
inverseOf: null,
relationships: null,
enums: null,
validations: [],
integration: null,
},
{
field: 'power',
type: 'String',
defaultValue: null,
isRequired: false,
isReadOnly: false,
isSortable: true,
isFilterable: true,
isVirtual: false,
description: null,
reference: null,
inverseOf: null,
relationships: null,
enums: null,
validations: [],
integration: null,
},
],
isSearchable: true,
actions: [],
segments: [],
onlyForRelationships: false,
isVirtual: false,
isReadOnly: false,
paginationType: 'page',
icon: null,
integration: null,
};
Loading