Created
November 22, 2018 19:59
-
-
Save georgebrata/7ee9463c44a782c2c0ca5a128ed020cb to your computer and use it in GitHub Desktop.
Simple GraphQL example using express-graphql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var graphqlHTTP = require('express-graphql'); | |
var { buildSchema } = require('graphql'); | |
// Construct a schema, using GraphQL schema language | |
var schema = buildSchema(` | |
type Query { | |
quoteOfTheDay: String | |
random: Float! | |
rollThreeDice: [Int] | |
} | |
`); | |
// The root provides a resolver function for each API endpoint | |
var root = { | |
quoteOfTheDay: () => { | |
return Math.random() < 0.5 ? 'Take it easy' : 'Salvation lies within'; | |
}, | |
random: () => { | |
return Math.random(); | |
}, | |
rollThreeDice: () => { | |
return [1, 2, 3].map(_ => 1 + Math.floor(Math.random() * 6)); | |
}, | |
}; | |
var app = express(); | |
app.use('/graphql', graphqlHTTP({ | |
schema: schema, | |
rootValue: root, | |
graphiql: true, | |
})); | |
app.listen(4000); | |
console.log('Running a GraphQL API server at localhost:4000/graphql'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment