Query to Search for an Item with Apollo

Photo by NASA on Unsplash

Query to Search for an Item with Apollo

·

2 min read

The last time was to get list of todo from Apollo. This time I am going to add task search functionality by id.

Code

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]
    task(id: ID!): Task # ❶
  }
`;

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

const resolvers = {
  Query: {
    tasks: () => tasks,
    task (parent, args, context, info) { // ❷
      const { id } = args;
      return context.db.find((task) => task.id == id)
    }
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: { db: tasks } // ❸
});

server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});

The changes from the previous one is as follows:

  1. Add the query in the type Query which specify an id.
  2. Add the resolver task which corresponds to ❶. The resolver searches for the id in the tasks.
  3. Set tasks as the database. The search in ❷ can simply be tasks.find() but I set db in context as it seems "Apollo way". As I use in-memory database this time, find() gets an item. In case the database is relational database, the query will probably be something like context.db.query('SELECT * FROM table_name');

Query

In addition to this query we had:

{
  tasks {
    id
    name
  }
}

Now, we have new query which can specify an id:

{
  task(id: 2) {
    id
    name
  }
}

The response of the query is:

{
  "data": {
    "task": {
      "id": 2,
      "name": "Sing Karaoke",
      "isActive": false
    }
  }
}

I see, I'm beginning to understand the development cycle. You repeat schema update and the resolver update as you have a new query.

Next step

Next step is add, delete and update the list. Mutation comes in.

Reference

GraphQL Search and Filter – How to search and filter results with GraphQL