objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

Virtual attributes validation fails with insertGraph

Open dimitrikochnev opened this issue 8 years ago • 7 comments

I checked the issues but didn't find the similar topic. I have a model with a virtual attribute password:

class User extends Model {
  static jsonSchema = {
    type: 'object',

    required: [
      'password',
    ],

    properties: {
      password: {
        pattern: PASSWORD_COMPLEXITY_REGEX_STRING,
        type: 'string',
      },
    },
  }

  static set password(val) {
     this.$password = val;
  }

  async $beforeInsert(ctx) {
     // hash password here...
  }

  async $beforeUpdate(ctx, opts) {
     // hash password here...
  }
}

Then I do User.query().insert({ email: '[email protected]', password: '123 '}) everything works fine, i.e the password validation against the schema works as expected, but User.query().insertGraph({ email: '[email protected]', password: '123 '}) fails with:

ValidationError: password: is a required property

Adding static get virtualAttributes() { return ['password'] } doesn't help.

dimitrikochnev avatar Sep 06 '18 22:09 dimitrikochnev

First of all, your setter is static. It shouldn't be. Second, you need a getter too.

koskimas avatar Sep 07 '18 05:09 koskimas

Sorry It's a typo in the example, of course my setter and getter aren't static:

class User extends Model {
 static jsonSchema = {
   type: 'object',

   required: [
     'password',
   ],

   properties: {
     password: {
       pattern: PASSWORD_COMPLEXITY_REGEX_STRING,
       type: 'string',
     },
   },
 }

 set password(val) {
   this.$password = val;
 }

 get password() {
   return this.$password;
 }

 async $beforeInsert(ctx) {
    // hash password here...
 }

 async $beforeUpdate(ctx, opts) {
    // hash password here...
 }
}

It doesn't work.

dimitrikochnev avatar Sep 07 '18 05:09 dimitrikochnev

It may be that Ajv (the validator objection uses) doesn't loop through getters by default. See if there is some option you can pass to Ajv and then you can override the createValidator method to pass in the option.

koskimas avatar Sep 07 '18 05:09 koskimas

Objection disables that actually with ownProperties: true. If you set it to true, you could end up validating all kinds of internal variables though. I don't know if this is possible the way you are doing it.

koskimas avatar Sep 07 '18 05:09 koskimas

OK, I'll check it!

dimitrikochnev avatar Sep 07 '18 07:09 dimitrikochnev

Hm, but shouldn't .insertGraph({ ..., password: '123 '}) work out of the box like .insert({ ..., password: '123 '}) does?

dimitrikochnev avatar Sep 07 '18 08:09 dimitrikochnev

I have the same problem, have you found any solution?

jdavidferreira avatar Apr 30 '21 04:04 jdavidferreira