Feature(s) impacted
Adding smart fields, handling collection associations with Sequelize.
Observed behavior
Let’s imagine a simple user
collection in which we add one-to-one relationships for a child to a parent, via a nullable parentId
foreign key. A user may have 0 or 1 parent (depending on whether parentId
is null). As we are running sequelize, we use hasOne
and belongsTo
to and from the user
collection.
From there, let’s add a smart field:
agent.customizeCollection('user', collection => {
collection.addField('displayName', {
columnType: 'String',
dependencies: ['firstName', 'lastName'],
getValues: (records, context) => {
console.log(records)
// Note the toUpperCase
return records.map(r => `${r.firstName} ${r.lastName.toUpperCase()}`),
}
});
});
This works perfectly on a user listing.
Now here’s the issue I encounter: when I go to view a specific user, getValues
is always called 3 times. Twice for the parent and the child, and then once for the current user record.
If the user has neither child nor parent, then the records
array will contain a single empty object twice. The third and last time, the records object will contain the current user.
That is, here is what appears in the console:
[ {} ]
[ {} ]
[ { firstName: 'John', lastName: 'Doe' }]
This causes a crash because .toUpperCase
is accessed on undefined
.
I’m thinking I may have bonked how I defined these relationships, so that Forest thinks users must have a parent and also must have a child. In which case the behavior could make sense…
This idea is supported by the fact that user.Child
and user.Parent
are both non-nullable in typings. I tried telling sequelize that parentId
is nullable
via allowNull
, to no avail.
Expected behavior
Either I should build my models so that Forest understands this relationship is optional, or the fact that getValues
can be called with empty objects is a bug. I’m trying to blame my code before moving on to blaming the framework =D
Context
- Agent technology: nodejs
- Agent (forest package) name & version: 1.40.1 with sequelize 6.37.3 and sequelize-typescript 2.1.6
- Database type: MSSQL
- Recent changes made on your end if any: Migrating from old agent.