To setup a project install nodejs and vscode for IDE and in a folder run below commands.
npm init --yes
npm i --save express express-graphql graphql lodash
Schema code to link with graphql queries.
schema/schema.js
--
const graphql = require('graphql'); const _ = require('lodash'); const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema } = graphql; //static data for testing const users = [ {id:'23',firstName: 'Bill', age:20}, {id:'47',firstName: 'Samantha', age:21}, ]; const UserType = new GraphQLObjectType({ name: 'User', fields:{ id: {type: GraphQLString}, firstName: {type: GraphQLString}, age: {type: GraphQLInt} } }); const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { user: { type: UserType, args: {id: { type: GraphQLString}}, resolve(parentValue,args){ return _.find(users, {id: args.id}); } } } }); module.exports = new GraphQLSchema({ query: RootQuery });
To host this we have this express app running.
server.js
--
const express = require('express'); const expressGraphQL = require('express-graphql'); const schema = require('./schema/schema'); const app = express(); app.use('/graphql',expressGraphQL({ schema, //es6 equavalant to schema: schema graphiql: true })); app.listen(4000,()=>{ console.log('Listening'); });
To run the app: node server.js
Inside a web browser, launch : localhost:4000/graphql?query=
It will open inside the GraphiQL UI. There you run this sample query:
{ user(id: "23"){ id, firstName, age } }
docs link right side, will give document explorer of the data.
No comments:
Post a Comment