Skip to content

Instantly share code, notes, and snippets.

@narutaro
Last active December 4, 2021 01:36
Show Gist options
  • Save narutaro/cd0006bc0d066fc6548534b1c1a36fb0 to your computer and use it in GitHub Desktop.
Save narutaro/cd0006bc0d066fc6548534b1c1a36fb0 to your computer and use it in GitHub Desktop.
Simple list view with Apollo

Simple list view with Apollo

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment