GraphQL Schema

Hi, if you want to read the previous post here is GraphQL environment. Ok, in this post we are going to talk about the Schema in GraphQL.

A Schema allows the client to understand what properties are available on your api and enables them to select only fields they want.

Creating a Schema

Let’s open the file index.js and create an object call typeDefs this is for the hole schema that we are defined for the Api

To create that object we need to create a special syntax with gql from apollo server

So we are saying that Session have all of this properties and also we are defined the types of that properties.

If you see the id: ID! have an exclamation mark at the end – this means that the id cannot be empty, alway will have a value.

Another thing that GraphQL requires is the description of what queries are allow by the API, is like the “Schema for the query”, so let’s add a type Query and the name of the query: and what that query will return.

In this case the name of our query is Sessions and that query will return a Session (that is the type that we already declared).

But we want more than one Session to return so lets wrap the Session type into an array.

Ok cool, the next step is add this typeDefs object to the Apollo constructor

// Dependencies
const { ApolloServer, gql } = require("apollo-server");

// Schema
const typeDefs = gql`
  type Query {
    Sessions: [Session]
  }

  type Session {
    id: ID!
    title: String!
    description: String
    startAt: String
    endsAt: String
    room: String
    day: String
    format: String
    track: String
    level: String
  }
`;

// Instanciating Apolloserver
const server = new ApolloServer({ typeDefs });

// Server configuration
server
  .listen({ port: process.env.PORT || 4000 }) // the server port
  // this function will be called when server started
  .then(({ url }) => {
    console.log(`GraQL running at ${url}`);
  });

Then run npm start.

By Cristina Rojas.