dehaze

Exploring GraphQL APIs

Let’s explore some awesome powers of Space Cloud. In this guide, we will be:

  • Creating trainers and catching Pokemons 😍 (Insert operation)
  • Retrieving all trainers (Simple query operation)
  • Retrieving all trainers with along with their Pokemons 😎 (Join operation)

Creating trainers (insert operation)

Creating trainers requires us to insert trainer documents into the database.

Head over to the Explorer section in Mission Control.

Try running the following query in the GraphiQL section:

mutation {
  insert_trainers(
    docs: [
      {_id: "1", name: "Ash"},
      {_id: "2", name: "Misty"},
      {_id: "3", name: "Brock"}
    ]
  ) @mongo {
    status
  }
}

On successful insert, you should be able to see the status as 200 which means the documents were inserted in the database.

Retrieving trainers (query operation)

Now let’s get the list of trainers back using graphql. Try running the following query:

query {
  trainers @mongo {
    _id
    name
  }
}

There, we get our list of trainers!

Catch Pokemons (insert operation)

Catching Pokemons requires us to insert Pokemon data into the database (And a lot of hard work ofcourse!😅)

mutation {
  insert_pokemons(
    docs: [
      {_id: "1", name: "Pikachu", trainerId: "1"},
      {_id: "2", name: "Snorlax", trainerId: "1"},
      {_id: "3", name: "Psyduck", trainerId: "2"},
      {_id: "4", name: "Staryu", trainerId: "2"},
      {_id: "5", name: "Onix", trainerId: "3"}
    ]
  ) @mongo {
    status
  }
}

Great! That’s a lot of Pokemon catching for the day. Now time for the trainers to show off their Pokemons.

Retrieve trainers along with their Pokemons (join operation)

Try running the following query in GraphiQL:

query {
  trainers @mongo {
    _id
    name
    pokemons(
      where: {trainerId: {_eq: "trainers._id"}}
    ) @mongo {
      _id
      name
    }
  }
}

The response should look something like this:

{
  "data": {
    "trainers": [
      {
        "_id": "1",
        "name": "Ash",
        "pokemons": [
          {"_id": "1", "name": "Pikachu"},
          {"_id": "2", "name": "Snorlax"}
        ]
      },
      {
        "_id": "2",
        "name": "Misty",
        "pokemons": [
          {"_id": "3", "name": "Snorlax"},
          {"_id": "4", "name": "Staryu"}
        ]
      },
      {
        "_id": "3",
        "name": "Brock",
        "pokemons": [
          {"_id": "5", "name": "Onix"}
        ]
      }      
    ]
  }
}

Next Steps

Awesome! We have just started our Pokemon journey without writing a single line of backend code. The journey ahead is surely going to be super exciting!

The next step is to dive into the various Space Cloud features:

Have a technical question?

Improve the docs!