Skip to content

Overriding model getters/setters? #66

Description

@dxg

Hey, say I have a model like:

User = db.define('user',{
    email: String
  },{
  validations: {
    email: orm.validators.unique()
  },
  hooks: {
    beforeSave: function() {
      this.email = email.toLowerCase();
    }
  }
});

All is jolly, however:

user1 = db.models.user.new({email: 'a@b.c'});
user1.save(...);
...
user2 = db.models.user.new({email: 'A@b.c'});
user2.save(...);

We now have two duplicate users.
(I actually have a unique index on the table to prevent this, but it throws an ugly error when saving)

I can think of two ways of solving this:

  1. Add a beforeValidate hook.
  2. Make it possible to add custom setters/getters for model properties.

I imagine it working something like this:

User = db.define('user',{
    email: String
  },{
  setters: {
    email: function(val) {
        return val.toLowerCase();
    }
  }
});

Or maybe even more fancy:

User = db.define('user',{
    email: String
  },{
  methods: {
    email: {
        set: function(val) {
            this.setAttribute('email', val.toLowerCase());
        }
    }
  }
});

where it defaults to the standard getter as one isn't specified, and setAttribute calls the default setter.

What do you think?

Activity

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions