Simple list view with Apollo

ยท

2 min read

I've been playing around with GraphQL lately and that's fun. After playing with GraphQL for a while, I thought I'd write about it in a series of articles.

The best way to get started with GraphQL now is to start with these two great sites to grasp the concept.

However, as soon as you follow these tutorials, you will start setting up the database and ORM. Personally, I think it's better to do this after you have a better understanding of GraphQL itself. GraphQL does not depend on database implementations due to its concept, so let's start with a simple in-memory database and move on. The goal of this article is to replace the this REST API based todo application with GraphQL.

Now, let's start with the installation.

Install

You anyway need the apollo server. Let's install.

mkdir todo
cd todo
npm init -y

npm install apollo-server

Launch with the template

You can find the following template in the Apollo official site. Let's use the template with your typeDefs for a quick start.

const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Task {
    id: ID!
    name: String!
    isActive: Boolean!
    createdAt: Int
    updatedAt: Int
    owner: String
  }

  type Query {
    tasks: [Task]
  }
`;

const tasks = [
  { id: 1, name: "Soak in an Onsen", isActive: true},
  { id: 2, name: "Sing Karaoke", isActive: true},
  { id: 3, name: "See cherry blossom", isActive: true},
]

const resolvers = {
  Query: {
    tasks: () => tasks,
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
  console.log(`๐Ÿš€  Server ready at ${url}`); 
});

Now, start the server

node index.js
๐Ÿš€  Server ready at http://localhost:4000/

Query

Let's try throwing a query to display a list of todo, as shown in Query, which is a simple query that returns the contents of the tasks array.

When you connect to the Apollo server, you can use the query editor. The name of this query editor seems to be GraphQL Playground. You can see the schema and other information by default, and it's pretty easy to write with keyword completion listening.

In the play ground:

  • You can use cmd + / to comment out multiple selected lines at once (super convenient).
  • You can write multiple queries and choose which one to execute by clicking the play button (super convenient).

Next step

This time it was a list view, so next time I'll try searching from a list.