GraphQL returning an array of data

Hi in this post we are going to display a list of jobs in an array.

Note: last GraphQL chapter was GraphQL configuring Apollo server with Express Js

First we need to see how is the data structure, so let’s open the schema.graphql file, en GraphQL we can create our own custom types, so let’s declare a Job type.

type Job {}

Once we have our job type we can fetch some jobs returning in array format.

type Query {
  jobs: [Job]
}

type Job {

}

Now we need to define what a Job looks like:

The id is type ID that give us extra information it tell the client that this is a unique identifier and we can specify that the id should never ben null by adding an exclamation mark, this means that each Job will have an id.

If we don’t insert the exclamation this means that the id can be null that also means that is an optional field.

type Job {
  id: ID!
}

We can add more fields like title & description:

type Job {
  id: ID!
  title: String
  description: String
}

Now, we can add the functionality in the resolvers.js file, for this project we not using a DB instead we have local data (for real application you will need a DB), so in our case we are going to use the package called notarealdb that will help us to store data in JSON files.

The file server/db.js have the notrealdb configuration, and we have some data ready to use:

Nice, now in our resolvers.js we need to have access to that data, so let’s import that data into our Jobs resolver.

// Data
const db = require("./db");

const Query = {
  // Jobs resolver that return an array of jobs
  jobs: () => db.jobs.list(),
};

module.exports = { Query };

Then open the browser and test the query:

By Cristina Rojas.