Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 14, 2021 05:05 am GMT

Using GraphQL in Express JS

GraphQL is a useful query language for your API. But it can be intimidating because they bring the complexity upfront as there are a lot that has to be set up before we can create our first query. I hope this article will be useful and understandable. Let's get started!

First things first, we'll need to require our module to our file and put some basic express boilerplate, let's say it's called app.js:

const express = require('express')const app = express()const { graphqlHTTP } = require('express-graphql')const port = 3000// We'll put everything here later// This code below must be on the last part of the fileapp.listen(port, () => {  console.log('Listening on port:', port)})

Then we'll create our first and (maybe) only route in this article:

app.use('/graphql', graphqlHTTP({  schema: schema,  graphiql: true}))

Instead of using (req, res) => {} to the callback we put an invoked graphqlHTTP function, so we can let the graphql do its thing. Inside the graphqlHTTP, we put a object that contains option to switch the graphiQL interface on, and schema that we'll create later on.

So what's a schema?

Schema defines a hierarchy of types with fields that are populated from your back-end data stores. The most basic components of a GraphQL schema are object types for query and mutation (optional), which just represent a kind of object you can fetch from your service, and what fields it has.

In the simplest way, we might represent the object types like this:

{  name: 'Book',  fields: {    title: { type: GraphQLString },    author: { type: GraphQLString }  }}

What's GraphQLString? It's a type that can only be recognized by graphQL instead of regular String in javascript. They have other types as well like GraphQLInt, GraphQLList, and GraphQLObjectType. And we can define them like this:

const {  GraphQLSchema, // for base schema type  GraphQLString,  GraphQLInt,  GraphQLList,  GraphQLObjectType} = require('graphql')

Now before we make our schema, we can create our own type first by putting the book object from earlier.

const BookType = new GraphQLObjectType({  name: 'Book',  fields: {    title: { type: GraphQLString },    author: { type: GraphQLString }  }})

Then we create our query object and prepare it with a small dummy data:

let dummyBooks = [  { title: 'Harry Potter', author: 'JK Rowling' },  { title: 'Lord of The Rings', author: 'JRR Tolkien' },  { title: 'Sherlock Holmes', author: 'Arthur Conan Doyle' }]const queryType = new GraphQLObjectType({  name: 'Book query',  fields: function () {    return {      // we called it books so we can type 'books' later on      books: {        type: new GraphQLList(BookType),        resolve: function () {          return dummyBooks        }      }    }  }})

Query object requires fields function that returns an object. The object itself contains properties of what we want to find via the query later on. And each has to have type and resolve. type property defines the type returned to us users and resolve gives the actual data, which is dummyBooks.

Lastly, we can define our schema like this:

const schema = new GraphQLSchema({  query: queryType})

Running the file

Now we can run this from terminal:

node app.js

Type this in the browser:

localhost:3000/graphql

Now you'll see this:
GraphiQL

There are two main parts in the screen, the white part on the left is the query editor, we can crate our query there. And the gray part on the right side will show the result of query done in the left.

Now we can create our first query:

query {  books {    title  }}

Notice there's no author in the query, and we'll get the data exactly like our query format:

{  "data": {    "books": [      {        "title": "Harry Potter"      },      {        "title": "Lord of The Rings"      },      {        "title": "Sherlock Holmes"      }    ]  }}

source: https://graphql.org/learn/


Original Link: https://dev.to/mhmmdysf/using-graphql-in-express-js-oi9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To