首页 > 解决方案 > Grouping graphql mutations

问题描述

I'm trying to group my mutations into second level types. The schema is parsed correctly, but resolvers aren't firing in Apollo. Is this even possible? Here's the query I want:

mutation {
    pets: {
        echo (txt:"test") 
    }
}

Here's how I'm trying to do it

Schema:

type PetsMutations {
    echo(txt: String): String
}

type Mutation {
    "Mutations related to pets"
    pets: PetsMutations
}

schema {
    mutation: Mutation
}

Resolvers:

  ...
  return {
    Mutation: {
      pets : {
        echo(root, args, context) {
            return args.txt;
        }
      },
    }

标签: graphqlgraphql-js

解决方案


Assuming you're using apollo-server or graphql-tools, you cannot nest resolvers in your resolver map like that. Each property in the resolver map should correspond to a type in your schema, and itself be a map of field names to resolver functions. Try something like this:

{
  Mutation: {
    // must return an object, if you return null the other resolvers won't fire
    pets: () => ({}),
  },
  PetsMutations: {
    echo: (obj, args, ctx) => args.txt,
  },
}

Side note, your query isn't valid. Since the echo field is a scalar, you can't have a subselection of fields for it. You need to remove the empty brackets.


推荐阅读