GraphQL Introduction - part 2

Hi, this the continuation of the first post called GraphQL introduction

So, let’s continue with this post; suppose that we have a database in this case just for the example I’m going to create a file with data that simulate my database.

1.- Create the file data.json in the project that we already have.

{
  "courses": [
    {
      "id": 1,
      "title": "NoseJs Course",
      "author": "Cristina Rojas",
      "topic": "javascript",
      "url": "http://learntechsystem.com"
    },
    {
      "id": 2,
      "title": "React Js",
      "author": "Carlos Santana",
      "topic": "javascript",
      "url": "http://learntechsystem.com"
    },
    {
      "id": 3,
      "title": "How to do technology",
      "author": "Cristina Rojas",
      "topic": "HTML",
      "url": "http://learntechsystem.com"
    }
  ]
}

Then import that file into the index.js to access the data

2.- Then I’m going to define how my data looks like in the schema (index.js). GraphQL permit us to declare the data type of each property in our server, this is similar to an interface of typescript so lets add the types too.

const schema = buildSchema(`
  type Query {
    message: String
  }

  type Course {
    id: Int
    title: String
    description: String
    author: String
    topic: String
    url: String
  }
`);

3.- Then we need to declare the query to get course by id like this:

  type Query {
    message: String
    course(id: Int!)
  }

course(id: Int!) – So if we want to see a specific course, then we need to type the id of the course and the ‘!‘ means that the id is required all the time to get the data of that course.

4.- Then we need to return the data (Course schema) to the user so in this case we need to write the code like this

course(id: Int!): Course

5.- Also we can return another query with all the courses that we have, so we need to insert this inside the Query. So instead of the id we can add the topic property to search by the topic. So, because we are returning multiple courses we can return the courses in an array.

  type Query {
    message: String
    course(id: Int!): Course
    courses(topic: String): [Course]
  }

6.- The next step is define our functions to resolve the queries that the user is typing, in root we are going to call our functions. The functions we are defining are the ones that do the magic of doing searches or filters in our data.

// Function to get course
let getCourse = (args) => {
  // getting the id
  let id = args.id;

  // Returning only the course that match
  // with the id that the user wrote
  return courses.filter((course) => {
    return course.id == id;
  })[0]; // because filter return an array, I only want item 0
}

// Function to get multiple courses
let getCourses = (args) => {
  if (args.topic) {
    let topic = args.topic;

    // return in an array all the courses that have
    // that topic
    return courses.filter((course) => {
      return course.topic == topic
    });
  } else { // if not
    // then return all the courses
    return courses;
  }
}

const root = {
  message: () => "Hello world!",
  course: getCourse,
  courses: getCourses
}

7.- Finally we can test our queries in the browser with GraphiQL tool, remember restart the server in the terminal with the command:

node index.js

Result:

Getting course by id

Getting multiple courses by topic

The final code looks like this:

index.js

// Dependencie
const express = require('express');
const app = express();
const express_graphql = require('express-graphql');
// This Dependencie will help us
// to define schemes
const { buildSchema } = require('graphql');

// Data
const { courses } =  require('./data.json');

// Building our schema
// we define all the types of queries
// that the users can do
const schema = buildSchema(`
  type Query {
    message: String
    course(id: Int!): Course
    courses(topic: String): [Course]
  }

  type Course {
    id: Int
    title: String
    description: String
    author: String
    topic: String
    url: String
  }
`);

// Function to get course
let getCourse = (args) => {
  // getting the id
  let id = args.id;

  // Returning only the course that match
  // with the id that the user wrote
  return courses.filter((course) => {
    return course.id == id;
  })[0]; // because filter return an array, I only want item 0
}

// Function to get multiple courses
let getCourses = (args) => {
  if (args.topic) {
    let topic = args.topic;

    // return in an array all the courses that have
    // that topic
    return courses.filter((course) => {
      return course.topic == topic
    });
  } else { // if not
    // then return all the courses
    return courses;
  }
}

// Object that have the methods
const root = {
  message: () => "Hello world!",
  course: getCourse,
  courses: getCourses
}

// To build a path to interact with graphql
// when the user is in /graphql]
// will see the schema and the methods that return something
app.use('/graphql', express_graphql({
  schema: schema, // when u
  rootValue: root,
  graphiql: true // Is a graphic interfaz of graphQL
}));

// Initializing our server
app.listen(3000, () => console.log('Server on port 3000!'));

Code: https://github.com/cristinarojas/graphQLimplementation

By Cristina Rojas.