Virtual attributes validation fails with insertGraph
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.
First of all, your setter is static. It shouldn't be. Second, you need a getter too.
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.
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.
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.
OK, I'll check it!
Hm, but shouldn't .insertGraph({ ..., password: '123 '}) work out of the box like .insert({ ..., password: '123 '}) does?
I have the same problem, have you found any solution?