I'm building an application with NestJS using GraphQL with MongoDB and mongoose. I have a mongoose schema that is imported from an external module (i.e. it's a dependency in the repo). It is because the schema is used by many other services too. The module exports the schema and the typescript interface of the resulting document.
The schema is in a standard mongoose format:
export const UserSchema = new Schema(
{
// ...properties here
}
)
It works well in NestJS for endpoints with a normal controller.
But I have to use GraphQL.
My problem is that I can't convert the mongoose schema format to a GraphQL model without duplicating the code.
I know that I can create a GraphQL model and mongoose schema in NestJS with the following syntax:
@ObjectType()
@Schema()
export class User {
@Field()
// ...property here
// etc.
}
and then
export const UserSchema = SchemaFactory.createForClass(User);
creates the mongoose schema. I will then use the User class in the resolver.
But it would mean that I have to copy all properties into the repo, so when we change or add a property, we will have to make the change in multiple repos.
Is there a way in NestJS where the input is the mongoose schema (in mongoose schema format), and the output can be used in the resolver module?