32
loading...
This website collects cookies to deliver better user experience
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 file
app.listen(port, () => {
console.log('Listening on port:', port)
})
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true
}))
(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.{
name: 'Book',
fields: {
title: { type: GraphQLString },
author: { type: GraphQLString }
}
}
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')
const BookType = new GraphQLObjectType({
name: 'Book',
fields: {
title: { type: GraphQLString },
author: { type: GraphQLString }
}
})
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
}
}
}
}
})
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
.const schema = new GraphQLSchema({
query: queryType
})
node app.js
localhost:3000/graphql
query {
books {
title
}
}
{
"data": {
"books": [
{
"title": "Harry Potter"
},
{
"title": "Lord of The Rings"
},
{
"title": "Sherlock Holmes"
}
]
}
}