graphql-compose / graphql-compose-mongoose

Mongoose model converter to GraphQL types with resolvers for graphql-compose https://github.com/nodkz/graphql-compose
MIT License
708 stars 94 forks source link

Resolvers Not Populating "source" when using TypeGoose #359

Closed litewarp closed 2 years ago

litewarp commented 3 years ago

Took the suggestion in the examples to use Typegoose, but can't seem to get the resolve function below to correctly type the source object. Is there something I need to do to get the "source" object to be typed correctly instead of any?


import { composeMongoose } from 'graphql-compose-mongoose'
import { prop, getModelForClass, modelOptions } from '@typegoose/typegoose'

@modelOptions({
  schemaOptions: {
    timestamps: true,
  }
})
class User {
  @prop({ required: true })
  email!: string

  @prop({ required: true })
  firstName!: string

  @prop()
  lastName!: string
}

const UserModel = getModelForClass(User)

export const UserTC = composeMongoose(UserModel, {})

UserTC.addFields({
  fullName: {
    type: 'String',
    // src is typed as "any"
    resolve: (src) => (src.lastName ? `${src.firstName} ${src.lastName}` : src.firstName),
    projection: { firstName: 1, lastName: 1 }
  }
})

image

nodkz commented 2 years ago

The problem was in graphql-compose package in this line https://github.com/graphql-compose/graphql-compose/blob/master/src/ObjectTypeComposer.ts#L109 (JUST FIXED):

export type ObjectTypeComposerFieldConfigDefinition<TSource, TContext, TArgs = any> =
  | ThunkWithSchemaComposer<
      ObjectTypeComposerFieldConfigAsObjectDefinition<TSource, TContext, TArgs>,
      SchemaComposer<TContext>
    >
  | ThunkWithSchemaComposer<ComposeOutputTypeDefinition<TContext>, SchemaComposer<TContext>>
  | Readonly<Resolver<TSource, TContext, any>>;  //  🤕🤕🤕 ambiguous definition for TypeScript

Try to install the latest version of graphql-compose and check how it works.


If it does not populate TSource automatically then you may pass it explicitly:

+ import { DocumentType } from '@typegoose/typegoose';

- export const UserTC = composeMongoose(UserModel, {})
+ export const UserTC = composeMongoose<DocumentType<User>>(UserModel, {})

UserTC.addFields({ ... });
litewarp commented 2 years ago

Confirmed that it works after upgrading to graphql-compose@9.0.2. Closing.