GraphQL for beginners me

A graphQL server needs a schema, resolvers and a datasource. The schema defines the data model but also the queries that you are allowed to do. The datasource actually gets the data from wherever it is, like a database or file or whatever. Resolvers take the data from the datasource and convert it into the shape defined in the schema.

Lets say you are listing the books you have in your bookshelf.

To list all the books you need:

  • a data model in the schema that defines all the properties of a book

    type Book {
        id: ID,
        title: String!,
        author: String!
    }
    
  • a query in the schema that lists what bits of the model is returned by the query

    type Query {
      books(
          id: ID,
          title: String,
          author: String
      ): [Book]
    }
    
  • a method in the datasource that lists all the books - args is added here so you can filter on any of the properties of a book like title or author in the API

    getBooks(args){
        return _.filter(books, args)
    }
    
    • (where here books is the actual datasource, in my demo project I'm using a json file so books is a direct link to this file)
  • a method in the resolver that links the schema to the datasource

    books: (parent, args, { dataSources }, info) => {
        return dataSources.booksAPI.getBooks(args)
    }
    
    • ( here dataSources.booksAPI is the apollo-datasource)

To get a specific book by its ID (yeh I know) you need:

  • another query in the schema that gets the id sent by the API

    bookById(id: ID): Book
    
  • a method in the resolvers that passes that id over to the datasource

    bookById: (parent, {id}, {dataSources}, info) => {
        return dataSources.bookAPI.getBookById(id)
    }
    
  • a method in the datasource that uses the id to filter the data and return the single record

    getBookById(id){
        const book = _.filter(books, {id: parseInt(int)}):
        return book[0];
    }