Is there a way to extend classes with required properties and make them optional in subclass? #1121
-
I'm trying to reduce code and want to reuse existing classes where properties are required and make them optional for updates. I tried the following, which works from a typescript point of view but not from a TypeGraphQL point of view because the decorators are off-course not in the compiled javascript for the Is there a way to achieve this? import { plainToClassFromExist } from 'class-transformer';
import {Arg, Field, InputType, Mutation, ObjectType, Resolver} from 'type-graphql';
@InputType('TestUserInput')
@ObjectType()
class User {
@Field()
id!: string;
@Field()
firstName!: string;
@Field()
lastName!: string;
@Field()
email!: string;
@Field({ nullable: true })
street?: string;
@Field({ nullable: true })
postalCode?: string;
}
interface UserForUpdate extends Partial<User> {}
@InputType('TestUpdateUserInput')
class UserForUpdate {
@Field({ nullable: true })
id?: string;
@Field({ nullable: true })
firstName?: string;
@Field({ nullable: true })
lastName?: string;
@Field({ nullable: true })
email?: string;
}
@Resolver()
export class TestResolver {
user?: User;
@Mutation(() => User)
async testCreateUser(@Arg('user') userToCreate: User): Promise<User> {
this.user = userToCreate;
return this.user;
}
@Mutation(() => User)
async testUpdateUser(@Arg('user') userToUpdate: UserForUpdate): Promise<User> {
console.log(userToUpdate);
this.user = plainToClassFromExist(this.user!, userToUpdate);
// userToUpdate.street exists on userToUpdate but is not available in GraphQLSchema
// userToUpdate.postalCode exists on userToUpdate but is not available in GraphQLSchema
return this.user;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Looks like a duplicate of #453. There are some pasted solution for such operators that you can try to use. There's nothing built-in as it would introduce tons of bugs when used together with class-validator, TypeORM or other decorator-based libs. |
Beta Was this translation helpful? Give feedback.
Looks like a duplicate of #453. There are some pasted solution for such operators that you can try to use.
There's nothing built-in as it would introduce tons of bugs when used together with class-validator, TypeORM or other decorator-based libs.