Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async getter/setter in Sequelize as part of a property

Can I define a getter of a property as an asyc function in Sequelize?
In the getter I should retrieve a value from another table and I've tried this in the model definition:

...
bio: {
    type: Sequelize.STRING,
    get: async function() {
        let bio = this.getDataValue('bio');
        if (bio) {
            let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))
            if(bestFriend){
                bio += ` Best friend: ${bestFriend.name}.`;
            }
            console.log(bio)
            return bio;
        } else {
            return '';
        }
    }
},
...

Logging I can read the correct bio with something like:
Born yesterday. Love to read Best friend: Markus

But the object I retrieve has an empty object in the bio attribute.
I suppose that is because the async function is not supported, am I wrong?

How can I achieve this without using an async function?

like image 838
lellefood Avatar asked Jun 01 '18 10:06

lellefood


1 Answers

According to the documentation getters and setters do not support any form of asynchrony. They are sync. So there is no way to use async functions (as we'd need a promise support).

Also here is a thread with a discussion on this subject. And it's confirmed that this feature is not going to be added in future.

You could extend the model instead and add the instance level method. The doc calls it a virtual getter. Please see this article.

You can also make it async and access the model data.

BioModel.prototype.getBio = async function() {
    let bio = this.getDataValue('bio');
    if (bio) {
        let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))
        if(bestFriend){
            bio += ` Best friend: ${bestFriend.name}.`;
        }
        return bio;
    } else {
        return '';
    }
}
like image 89
Antonio Narkevich Avatar answered Sep 17 '22 15:09

Antonio Narkevich