Created
August 21, 2020 08:37
-
-
Save stemount/3adbde4201bbb02b97a4bca693dda0fc to your computer and use it in GitHub Desktop.
type-graphql hack/scalar for Nested field validation - take inspiration from this (and even just see if it works!)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Field } from 'type-graphql'; | |
import { ValidateNested } from 'class-validator'; | |
import { plainToClass } from 'class-transformer'; | |
export function Nested(options?: { each?: boolean; nullable?: boolean }) { | |
return (target: any, propertyName: string) => { | |
const Ctx = Reflect.getMetadata( | |
'design:type', | |
target.constructor.prototype, | |
propertyName | |
); | |
if (options && options.each) { | |
Field(() => [Ctx], { nullable: options.nullable })(target, propertyName); | |
} else { | |
Field(() => Ctx, { nullable: options ? options.nullable : false })( | |
target, | |
propertyName | |
); | |
} | |
ValidateNested()(target, propertyName); | |
Object.defineProperty(target.constructor.prototype, propertyName, { | |
get() { | |
return this[`__${propertyName}`]; | |
}, | |
set(value: any) { | |
this[`__${propertyName}`] = plainToClass(Ctx, value); | |
}, | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment