Is there a cleaner/more appropriate way to auto-create this entity relationship in the Middleware?

Hello, my current middleware to additionally create a Profile entitiy for the newly registered user looks like this:
module.exports = async (req, res, manifest) => {
const user = await manifest.from('users').where('name = ' + req.body.name).find();
const userId = user.data[0].id;
await manifest.from('profiles').create({
userId: userId,
});
}
module.exports = async (req, res, manifest) => {
const user = await manifest.from('users').where('name = ' + req.body.name).find();
const userId = user.data[0].id;
await manifest.from('profiles').create({
userId: userId,
});
}
Is there a better, or rather, more sanitized way to additionally create the entity like this?
5 Replies
brunobuddy
brunobuddy7mo ago
@BennySama that's nice ! One thing is that if there is no user that correcponds to that name the code will fail when getting "user.data". You can add a condition (if !user) { throw some error } to make it more robust.
BennySama
BennySamaOP7mo ago
I use this middleware handler as "afterCreate", so the specific user should always exist But I wonder if there was an easier way, or if the where function from the manifest already has some built-in sanitation
brunobuddy
brunobuddy7mo ago
OK ! No easier way yet but we are open to suggestions if you think of something simpler
BennySama
BennySamaOP7mo ago
For my use case, where the Profile entity of the specific user needs to be created along side, it would be sufficent to skip the step to get the userId by userName, like I do, but straight-up using the direct User ID from the freshly created User Entity
cAroed
cAroed2mo ago
I'd add a timestamp field to the backend.yml Then push it from the frontend, then find the record using the timestamp from the req. This would ensure uniqueness of the find() Hope that helps ¯\_(ツ)_/¯ The timestamp-based approach ensures that even if the immediate response doesn't contain the ID as expected, we can reliably find and create/update new items using the unique timestamp identifier

Did you find this page helpful?