Apollo Server: pass arguments to nested resolvers

前端 未结 3 728
余生分开走
余生分开走 2021-01-21 20:28

My GraphQL query looks like this:

{
    p1: property(someArgs: \"some_value\") {
        id
        nestedField {
            id
            moreNestedField {
           


        
3条回答
  •  失恋的感觉
    2021-01-21 21:12

    Please check this answer here on how to pass the arguments: https://stackoverflow.com/a/63300135/11497165

    To simplify it, you can define your field type with args:

    In your Type Definition

    type Query{
      getCar(color: String): Car
      ... other queries
    }
    
    type Car{
      door(color: String): Door // <-- added args
      id: ID
      previousOwner(offset: Int, limit: Int): Owner // <-- added args
      ...
    }
    

    then, in your client query (from apollo client or your gql query):

    query getCar(carId:'123'){
      door(color:'grey') // <-- add variable
      id
      previousOwner(offset: 3) // <-- added variable
      ... other queries
    }
    

    You should be able to access color in your child resolver arguments:

    In your resolver:

    Car{
      door(root,args,context){
       const color = args.color // <-- access your arguments here
      }
      previousOwner(root,args,context){
       const offset = args.offset // <-- access your arguments here
       const limit = args.limit // <-- access your arguments here
      }
      ...others
    }
    

    For your example:

    it will be like this

    {
        p1: property(someArgs: "some_value") { // <-- added variable
            id
            nestedField(someArgs: "some_value") { // <-- added variable
                id
                moreNestedField(offset: 5) {
                    id
                }
            }
        }
    }
    

提交回复
热议问题