Thursday, 6 September 2018

graphql resolvers

type Query {
  human(id: ID!): Human
}

type Human {
  name: String
  appearsIn: [Episode]
  starships: [Starship]
}

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

type Starship {
  name: String
}

---------------------------------------
query:

{
  human(id: 1002) {
    name
    appearsIn
    starships {
      name
    }
  }
}

result:

{
  "data": {
    "human": {
      "name": "Han Solo",
      "appearsIn": [
        "NEWHOPE",
        "EMPIRE",
        "JEDI"
      ],
      "starships": [
        {
          "name": "Millenium Falcon"
        },
        {
          "name": "Imperial shuttle"
        }
      ]
    }
  }
}
--------------------------------------
resolvers fields

Query: {
  human(obj, args, context, info) {
    return context.db.loadHumanByID(args.id).then(
      userData => new Human(userData)
    )
  }
}

obj The previous object, which for a field on the root Query type is often not used.

args The arguments provided to the field in the GraphQL query.

context A value which is provided to every resolver and holds important contextual information like the currently logged in user, or access to a database.

info A value which holds field-specific information relevant to the current query as well as the schema details, also refer type GraphQLResolveInfo for more details.

-------------------------------------
root resolver

Human: {
  name(obj, args, context, info) {
    return obj.name
  }
}

---------------------------------
scalar resolver

Human: {
  appearsIn(obj) {
    return obj.appearsIn // returns [ 4, 5, 6 ]
  }
}

-----------------------------------
list resolver

Human: {
  starships(obj, args, context, info) {
    return obj.starshipIDs.map(
      id => context.db.loadStarshipByID(id).then(
        shipData => new Starship(shipData)
      )
    )
  }
}
----------------------------------

reference:
https://graphql.org/learn/execution/

No comments:

Post a Comment