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

How to get a Nested Field and make it Non Plural (without mutating the original TC)? #383

Closed tasoskakour closed 2 years ago

tasoskakour commented 2 years ago

Hey all!

My Schema:

const CommentSchema = {
            ... 
            _id: String,
}

const PostSchema = {
         ...,
         comments:  [CommentSchema]
}

const RootSchema = new mongoose.Schema(
     {
           ...., 
           posts: [Post]
     }
)

What I want to achieve?

I want to create a mutation, let's call it getCommentById where I need to fetch a particular comment by comment._id and return a that comment. So the return type of the resolver must be Comment (non plural).

The resolver will be a custom one, and I'm fine by it, I already made it work. However I have trouble with setting the resolver type by recomposing the RootTC (I don't want to write it by hand because it kinda miss the purpose of this library).

Technically what I want to do is to get posts.comments field from RootSchema and makeItNonPlural without modifying the initial RootTC object.

My Code:

const RootTC = composeMongoose(RootSchema);

schemaComposer.Mutation.addFields({ 
       ...,
       // My custom resolver:
                getCommentById: RootTC.addResolver({
                    name: 'getCommentById',
                    args: {
                        commentId: 'String!'
                    },
                    type: `${RootTC.getFieldOTC('posts') // Here is the problem
                    .makeFieldNonPlural('comments')   // It looks like I'm modifying the RootTC
                    .getFieldType('comments')}`,  // However I just need this type for this resolver one-off.
                    resolve: myCustomResolver,  
          }).getResolver('getCommentById'),
})

Any help is appreciated! :-)

nodkz commented 2 years ago

I think it is better to write your resolver manually without using unclear wrappers and resolvers.

The resolver will be a custom one, and I'm fine by it, I already made it work. However I have trouble with setting the resolver type by recomposing the RootTC (I don't want to write it by hand because it kinda miss the purpose of this library).

If you change the type internals (some field inside it) it must have another name. So you need clone type with a new name, modify it and use it in your resolver.