Skip to content

Instantly share code, notes, and snippets.

@narutaro
Last active October 30, 2021 12:03
Show Gist options
  • Save narutaro/823f29425c47bc7eda5ab260fdc2c26c to your computer and use it in GitHub Desktop.
Save narutaro/823f29425c47bc7eda5ab260fdc2c26c to your computer and use it in GitHub Desktop.
Query to Search for an Item with Apollo

Query to Search for an Item with Apollo

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

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