dehaze

Exploring GraphQL APIs

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

  • Create tables
  • Make trainers and catch Pokemons 😍 (Insert operation)
  • Retrieve all trainers along with their Pokemons 😎 (Join operation)

Create tables

Note: If you are using MongoDB, you can skip this step, since MongoDB is schemaless.

Head over to the Database section in Mission Control.

Click on Add table button to open this form:

Create a project screen

Give your table name as trainer.

Copy-paste the following schema and hit save:

type trainer {
  id: ID! @primary
  name: String!
  pokemons: [pokemon] @link(table: "pokemon", from: "id", to: "trainer_id")
}

Note: Don’t worry if this syntax is new to you. It is GraphQL SDL which Space Cloud uses to create tables for you. You can read more about it later from here.

Similarly, to create a pokemon table, click on Add Table button once again.

Give your table name as pokemon.

type pokemon {
  id: ID! @primary
  name: String!
  trainer_id: ID! @foreign(table: "trainer", field: "id")
}

Making trainers and catching pokemons (insert operation)

Let’s insert some trainers along with their pokemons.

Head over to the Explorer section in Mission Control:

Explorer

Try running the following query in the GraphiQL section:

mutation {
  insert_trainer(
    docs: [
      { 
        id: "1",
        name: "Ash",
        pokemons: [
          { id: "1", name: "Pikachu" },
          { id: "2", name: "Snorlax" }
        ] 
      },
      { 
        id: "2",
        name: "Misty",
        pokemons: [
          { id: "3", name: "Psyduck" },
          { id: "4", name: "Staryu" }
        ] 
      },      
    ]
  ) @postgres {
    status
  }
}

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

Retrieve trainers along with their Pokemons (join operation)

Try running the following query in GraphiQL:

query {
  trainer @postgres {
    id
    name
    pokemons {
      id
      name
    }
  }
}

The response should look something like this:

{
  "trainer": [
    {
      "id": "1",
      "name": "Ash",
      "pokemons": [
        {
          "id": "1",
          "name": "Pikachu"
        },
        {
          "id": "2",
          "name": "Snorlax"
        }
      ]
    },
    {
      "id": "2",
      "name": "Misty",
      "pokemons": [
        {
          "id": "3",
          "name": "Psyduck"
        },
        {
          "id": "4",
          "name": "Staryu"
        }
      ]
    }
  ]
}

Next Steps

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

Read more about:

Have a technical question?

Improve the docs!