PhilWaldmann / openrecord

Make ORMs great again!
https://openrecord.js.org
MIT License
486 stars 38 forks source link

validatesUniquenessOf not called #44

Closed SampsonCrowley closed 7 years ago

SampsonCrowley commented 7 years ago

validatesUniquenessOf never seems to run. I'm getting database level errors of unique index violations on an email column

module.exports = function (){
  this.filteredChanges = function filteredChanges(changes){
    return Object.keys(changes)
    .filter(key => key.toLowerCase() !== 'password')
    .reduce((obj, key) => {
      obj[key] = changes[key];
      return obj;
    }, {})
  }

  this.forCookie = function forCookie(){
    return {id: this.id, email: this.email}
  }

  this
  .validatesUniquenessOf(['email', 'athlete_id'])
  .validatesFormatOf('email', /^[^@\s\;]+@[^@\s\;]+\.[^@\s\;]+$/)
  .belongsTo('athlete')
  .hasMany('accounts_users')
  .hasMany('users', {through: 'accounts_users'})
  .hasMany('infokits')
  .hasMany('account_audits')
  .beforeSave(function(){
    let action;
    if(!this.__exists){
      action = 'create';
    } else if(this.hasChanges()){
      action = 'update';
    }
    if(action) console.log(this.account_audits.new({action: action, audited_changes: this.filteredChanges(this.changes), remote_address: this.context.current_ip || '127.0.0.1'}))
    return true
  })
}
PhilWaldmann commented 7 years ago

I'm currently not at my machine, but please try validatesUniquenessOf('email', 'athlete_id') (without the array)

PhilWaldmann commented 7 years ago

Yep, that's a bug! Thanks for reporting.

I've just added a bunch of new tests to cover the use of e.g. .validatesUniquenessOf(['email', 'athlete_id']) in c231894cd9ce63319bdee51a4f005a756ced4d87 Unfortunately there was a bug, so that OpenRecord tries to find a field with the name of ['email', 'athlete_id'].

I've just published version 1.11.2 to fix this issue.

Thanks, Philipp

SampsonCrowley commented 7 years ago

No problem. I'm still having connection issues, but that's becaus of the way knex works. Unfortunately that means I can't use your library until knex figures out how to check for disconnects from the database. My database is set to close idle connections after 2 minutes, which knex doesn't try to reconnect. But know you've inspired me in the custom ORM that I'm writing!

PhilWaldmann commented 7 years ago

Good to know! What settings do you have set in your database (postgres right?)

Maybe we could find a solution for your problem and open a PR for knex