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?
4 Replies
brunobuddy
brunobuddy7d 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
BennySamaOP7d 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
brunobuddy7d ago
OK ! No easier way yet but we are open to suggestions if you think of something simpler
BennySama
BennySamaOP7d 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

Did you find this page helpful?