Setting up GraphQL Playground with Hapi 18
Prerequisites
- NodeJS installed
- Basic JavaScript
- Terminal (any will do, preferably bash-based)
Let’s start with creating package.json for our project by running the command in the project folder.
npm init
The above command would generated a package.json for your project.
Setting Up Hapi Server
The next steps to add the dependencies to setting up the Hapi Server with the routes. For this, we need to install hapi and nodemon.
npm i hapi nodemon
Then, let’s open our text editor, i choose VS Code.
Create an index.js file into the root directory with the contents following
const Hapi = require(‘hapi’);const app = new Hapi.server({
port: 4000,
host: 'localhost'
});async function StartServer() {
app.route([
{
method: "GET",
path: "/",
handler: function(request, response){
return "<h1>Thanks Hapi</h1>"
}
}
])
await app.start();
console.log(`Server running at: ${app.info.uri}`);
}StartServer().catch(error => console.log(error));
And, add the script with nodemon to package.json.
Open the package.json and edit the scripts
What we did so far is we import the hapi and provide the minimal configuration only a port and host to start the server. We added a simple get route to thanks hapi :-)
Its time to test our code, open your project terminal and run this command
npm start
If everything looks good, we should see this in our terminal
Alright. Good to go to hit the url http://localhost:4000/ in the browser and, we will see Thanks Hapi
Setting up GraphQl
Now, we will set up the Apollo server and provide with the sample query to test in our playground.
Edit the index.js file and update the content with the following:
const Hapi = require(‘hapi’);
const { ApolloServer, gql} = require(‘apollo-server-hapi’);const typeDefs = `
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello world!'
},
};const server = new ApolloServer({
typeDefs,
resolvers
});const app = new Hapi.server({
port: 4000,
host: 'localhost'
});async function StartServer() { await server.applyMiddleware({
app
}); await server.installSubscriptionHandlers(app.listener); app.route([
{
method: "GET",
path: "/",
handler: function(request, response){
return "<h1>Thanks Hapi</h1>"
}
}
]) await app.start();
console.log(`Server running at: ${app.info.uri}`);
}StartServer().catch(error => console.log(error));
As we are using the nodemon we don’t need to run the start command again.
Only need to hit the url http://localhost:4000/graphql and we will able to see the playground.
So everything is done here and running in the browser.
Let’s run our test query which we added in the typeDefs.
{
hello
}
Type the query into the playground and hit the play button. Yeah its working and we get our first response “Hello world!”
My Name is Tarun Kalra. I am a Sr. Frontend Developer at Publicis.Sapient
If you enjoyed this article, please clap n number of times and share it! Thanks for your time.