Skip to content

Instantly share code, notes, and snippets.

@stemount
Created August 21, 2020 08:37
Show Gist options
  • Save stemount/3adbde4201bbb02b97a4bca693dda0fc to your computer and use it in GitHub Desktop.
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!)
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