Requirements
nodejs
babel
Assume that you already have Node js installed in your system.
Create a folder i.e graphql-local-server
initialize package.json with following command. we just keep all defaults with it.
npm init
Add a start script to your package.json file
{ | |
"name": "graphql-local-server", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"start": "babel-node src/index.js", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"babel-cli": "^6.26.0", | |
"babel-preset-env": "^1.7.0" | |
} | |
} |
Setup babel
Install babel dependencies.
Run following commands in order to install latest version of babel compiler and babel preset
npm install babel-cli babel-preset-env
babel-cli is a babel compiler and babel-preset-env will tell babel what it should change so the browser can understand the JS code.
Now create a single file called .babelrc in your root folder which will tell our presets which environment to use.
{ | |
"presets": [ | |
"env" | |
] | |
} |
import GraphQL-yoga library
npm install graphql-yoga
create an index.js file inside your src root folder with following content.
import { GraphQLServer } from 'graphql-yoga' | |
//Type definations (Application Schema) | |
//Describes the operations and the data structures. | |
const typeDefs = ` | |
type Query { | |
hello: String! | |
} | |
` | |
//Resolvers object for our API | |
// These are the functions that acutally run when various oprations are performed. | |
const resolvers = { | |
Query: { | |
hello() { | |
return "Hello World!" | |
} | |
} | |
} | |
const server = new GraphQLServer({ | |
typeDefs, | |
resolvers | |
}) | |
server.start(()=>{ | |
console.log('The Sever is up!') | |
}) |
Now when you run
npm run start
you will see the log with "The server is up!" text.
By default, graphql-yoga starts the server on port 4000
Open the http://localhost:4000/ to see your first graphQL api.
Your first available GraphQL query
query {
hello
}
Top comments (1)
Thank you