Apollo Server

  • typeDefs - GraphQL Schema
  • resolvers (an object) - defines how GraphQL queries are responded to
    • all resolver functions are given four parameters1
const { ApolloServer, gql } = require('apollo-server')
const typeDefs = gql`
type Person {
name: String!
phone: String
street: String!
city: String!
id: ID!
}
type Query {
personCount: Int!
allPersons: [Person!]!
findPerson(name: String!): Person
}
`
const resolvers = {
Query: {
personCount: () => persons.length,
allPersons: () => persons,
findPerson: (root, args) =>
persons.find(p => p.name === args.name)
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
})
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`)
})

Resolvers

  • GraphQL-server must define resolvers for each field of type in the schema
  • when we don't define resolvers, Apollo defined default resolvers for them
  • possible to define resolvers for only some fields of a type, and let the default resolvers handle the rest.
const resolvers = {
Query: {
personCount: () => persons.length,
allPersons: () => persons,
findPerson: (root, args) => persons.find(p => p.name === args.name)
},
Person: {
name: (root) => root.name,
phone: (root) => root.phone,
street: (root) => root.street,
city: (root) => root.city,
id: (root) => root.id
}
}