Skip to content

Implement asynchronicity in getters / setters #965

Closed

Description

@thanpolas

Allow for async execution of virtual getters / setters.

I will implement this feature as it's a show-stopper for me (hashing algo for passwords is async).

Since there is no established pattern for async callbacks in Sequelize (apart from chained promises) i'll take the initiative to use the this.async() pattern.

I'm not choosing detecting function arity (ala express.js) as this has side-effects in combination with promises.

Proposed Pattern using this.async()

var Foo = sequelize.define('Foo', {
  title: {type     : Sequelize.STRING, allowNull: false,}

  }, {

  getterMethods   : {
    title_slug  : function()  { 
      var done = this.async();

      doSomethingAsync(function(){
        done(slugify(this.title));
      })
    }
});

Using Function Arity Detection

var Foo = sequelize.define('Foo', {
  title: {type     : Sequelize.STRING, allowNull: false,}

  }, {

  getterMethods   : {
    title_slug  : function(done)  {  // defining an argument means async
      doSomethingAsync(function(){
        done(slugify(this.title));
      })
    }
});

// @sdepold

Activity

  1. thanpolas commented on Oct 7, 2013

    @thanpolas
    ContributorAuthor
  2. thanpolas commented on Oct 7, 2013

    @thanpolas
    ContributorAuthor

    Just a note, decision about the async pattern will also have to be applied to other parts where async will be required (e.g. custom instance / class methods for models)

  3. mickhansen commented on Oct 7, 2013

    @mickhansen
    Contributor

    I'm mostly for the function arity detection. What are the possible side effects of that?

  4. thanpolas commented on Oct 7, 2013

    @thanpolas
    ContributorAuthor

    @mickhansen it's a subtle and very real issue. The resume is that the arity detection pattern assumes that any argument passed to the callback function is considered to be an error:

    function someAsync(done) {
      // this is considered an error and execution should stop after that
      done('any value');
    }

    Promises on the other hand may have arguments on callbacks which conflicts with this pattern:

    function someAsync(done) {
      anotherAsync.then(done);
    }
    
    function anotherAsync() {
      var def = defer();
    
      // do stuff...
    
      // the 'a result' value will create an error as it will be passed as arg to the 'done' cb
      return def.resolve('a result');
    };

    You could solve the problem by being more verbose on the done statement:

      anotherAsync.then(done.bind(null, null), done.bind(null, 'an error occurred');

    Mind you the value an error occurred is hard-coded as a promise that is rejected, may or may not provide an argument...

    There are more than meets the eye here and personally i had several issues i had to tackle while writing tests. You can dive in, in one of the many related discussions kriskowal/q#86

  5. sdepold commented on Oct 7, 2013

    @sdepold
    Member

    i'd would vote for the callback parameter.

  6. sdepold commented on Oct 8, 2013

    @sdepold
    Member

    Hmm we actually already have some kind of inconsistency in the project :(
    https://github.com/sequelize/sequelize-doc/pull/81/files => custom validators use the first argument as an error.

  7. reopened this on Oct 8, 2013
  8. sdepold commented on Oct 8, 2013

    @sdepold
    Member

    oops. sorry.

  9. sdepold commented on Oct 8, 2013

    @sdepold
    Member

    @Inconsistency: i guess we can ignore it at this point as, because it (imho) makes sense that the done argument takes the result of the getter as first parameter, whereas it seems kinda senseless, to demonstrate the error case?! i mean, if you'd use a normal synchronous getter, you wouldn't demonstrate the error case explicitly as well?!

  10. mickhansen commented on Oct 8, 2013

    @mickhansen
    Contributor

    In my opinion we should maintain node-style callbacks with error first, also for done callbacks for setter/getters.
    It might seem silly for setters/getters to have errors, but ultimately it will keep the api more sane i think.

  11. sdepold commented on Oct 8, 2013

    @sdepold
    Member

    +1 for that

  12. sdepold commented on Oct 8, 2013

    @sdepold
    Member

    so we will go for:

    var Foo = sequelize.define('Foo', {
      title: {type     : Sequelize.STRING, allowNull: false,}
    
      }, {
    
      getterMethods: {
        title_slug: function(done)  {  // defining an argument means async
          doSomethingAsync(function(){
            done(null, slugify(this.title));
          })
        }
    });
  13. mickhansen commented on Oct 8, 2013

    @mickhansen
    Contributor

    We need to discuss what happens if one does callback with an error though - We don't really have any way to support that - The error that is, where would it be reported? :) If we want to report it all, which i assume we do if its there

  14. sdepold commented on Oct 8, 2013

    @sdepold
    Member

    we don't have to handle that. the user will use it like this:

    foo.title_slug(function(err, value) {
      if (err) { /* oops */ }
      else { /* cool ! */ }
    })
  15. 12 remaining items

  16. mickhansen commented on Dec 16, 2015

    @mickhansen
    Contributor

    @diosney It's simply too complicated to get right, and would change pretty much everything.
    You could add a afterFind that checks if the VIRTUAL attribute has been requested and then inject the value.

  17. diosney commented on Dec 16, 2015

    @diosney
    Contributor

    @mickhansen Thanks! As always, you give me another ray of hope 😄

    I didn't know about the afterFind hook, that definitively will work for me.

    Thanks!

  18. tremby commented on Mar 8, 2016

    @tremby
    Contributor

    @mickhansen or @diosney, can you give an example of how to use an afterFind hook in that way, with an async bit of code? In particular, checking if the virtual attribute has been requested, and then fulfilling a promise of a result for that field.

    In my experimentation, the hook is called both after findById and findAll, but the first argument is a single instance in the first case and a list of instances in the second. I can handle this. But the second argument options doesn't have the attribute I added to the options ({attributes: {include: ['field']}}).

  19. mickhansen commented on Mar 9, 2016

    @mickhansen
    Contributor

    @tremby Hmm that's odd, the options should be options passed, so your attribute should be in there.

  20. tremby commented on Mar 9, 2016

    @tremby
    Contributor

    I added an afterFind hook which just logs out the second argument.

    When I try the following

      console.log "find by id"
      models.User.findById 1,
        attributes:
          include: 'position'
      .then ->
        console.log "findall"
        models.User.findAll
          attributes:
            include: 'position'

    I get back this:

    find by id
    { attributes: 
       [ 'id',
         'provider',
         'providerId',
         'name',
         'image',
         'email',
         'createdAt',
         'updatedAt' ],
      where: '`User`.`id` = 1',
      plain: true,
      hooks: true,
      tableNames: [ 'Users' ],
      type: 'SELECT',
      model: User }
    findall
    { attributes: 
       [ 'id',
         'provider',
         'providerId',
         'name',
         'image',
         'email',
         'createdAt',
         'updatedAt' ],
      hooks: true,
      tableNames: [ 'Users' ],
      type: 'SELECT',
      model: User }
    

    If I instead have, as the options,

        attributes:
          include: ['position']

    I get the same output.

    If I have

        attributes:
          include: ['position', 'pos']

    I'm told pos doesn't exist (that's correct).

    If I have

        attributes:
          include: [
            ['position', 'pos']
          ]

    I'm told Unknown column 'position' in 'field list'. This is legit, because that column doesn't exist. But it is a virtual field so I expected it not to really add it to the query.

    If I have

        attributes:
          include: [
            ['(select 1)', 'one']
          ]

    I get

    find by id
    { attributes: 
       [ 'id',
         'provider',
         'providerId',
         'name',
         'image',
         'email',
         'createdAt',
         'updatedAt',
         [ '(select 1)', 'one' ] ],
      where: '`User`.`id` = 1',
      plain: true,
      hooks: true,
      tableNames: [ 'Users' ],
      type: 'SELECT',
      model: User }
    findall
    { attributes: 
       [ 'id',
         'provider',
         'providerId',
         'name',
         'image',
         'email',
         'createdAt',
         'updatedAt',
         [ '(select 1)', 'one' ] ],
      hooks: true,
      tableNames: [ 'Users' ],
      type: 'SELECT',
      model: User }
    

    What I want is to request the position attribute (which is defined as VIRTUAL), and have the afterFind know about it, as you suggested was possible above. Am I going about this totally wrongly?

  21. mickhansen commented on Mar 9, 2016

    @mickhansen
    Contributor

    You're going about this correctly but it appears there's a bug in our code. You're getting the cleaned and normalized options rather than the original options.

  22. tremby commented on Mar 9, 2016

    @tremby
    Contributor

    Want me to open a new ticket?

  23. mickhansen commented on Mar 9, 2016

    @mickhansen
    Contributor

    Please do @tremby

  24. twelve17 commented on Sep 30, 2016

    @twelve17

    Thanks to @iamjochem and others for making what I believe are good points regarding the problem with asynchronous calls in getters and setters. May I suggest, in this case, that the example code in the VIRTUAL datatype be changed to something else besides password hashing as a setter method, since it might mislead folks to the problem discussed here?

  25. felixfbecker commented on Oct 1, 2016

    @felixfbecker
    Contributor

    @twelve17 sure, feel free to do a PR. I prefer the firstName / lastName / fullName example

  26. twelve17 commented on Oct 21, 2016

    @twelve17

    @felixfbecker Sounds good, I'll take a look.

  27. thomascgray commented on Oct 12, 2017

    @thomascgray

    How do you change a virtual field in afterFind? Tried everything with getters and setters, but it still comes out with original values.

  28. iamjochem commented on Oct 12, 2017

    @iamjochem
    Contributor

    @thomascgray - what does it mean to change a virtual field value? (given that is it niether stored in the instance nor represented in the underlying storage). When you say you tried "everything" it is always helpful to show actual code. I'll hazard a guess that your virtual-field is retrieving a value from the instance using this.getDataValue('some_real_attribute') and then possibly doing something with it then returing a value based on it ... in your afterFind hook you'll want to manipulate the some_real_attribute somehow (e.g. this.some_real_attribute = "my fudged after-find value")

    • nice thread hijack btw ;-) maybe consider opening a new issue instead?
  29. pforprince commented on Sep 27, 2022

    @pforprince

    Hi, is there any alternate for an async getter? I'm saving the file key in DB and every time I want a file, I need to fetch its signed URL using its key. Writing the code in one place i.e getter would have solved the issue.

  30. BuistvoPloti commented on Mar 12, 2024

    @BuistvoPloti

    though it is closed i'm leaving my answer on the opened issue
    aws/aws-sdk-js-v3#5509 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions