How To Set Up a GraphQL server with Apollo Server on Localhost

In this post, I'll walk you through the process of setting up a GraphQL server with Apollo Server and also doing different operations of GraphQL on the mock data. 


Steps:

1. Create a new folder. Open CMD, and type `npm init -y` to scaffold your package.json. We are using `-y` so to fast-track the process and keep the defaults.

2. We are going to need the following dependencies: graphql, apollo-server and nodemon.

`npm install graphql apollo-server nodemon`

3. After the above packages have been added successfully, open your code in any editor or IDE.

4. Create a new file and name it `index.js` at the root of your project folder. Inside index.js type the following:


5. Open package.json, under scripts, define a new key as `start`, and for its value, type `nodemon index.js`.

6. Open CMD again, type `npm run start` and hit enter. On the console, you will the see the message as `Server is running on http://localhost:4000/`.


7. Open GraphQL Playground at https://www.graphqlbin.com/. Enter the endpoint URL `http://localhost:4000` in the textbox and click on `Use Endpoint`.

8. Let's test a query here. Enter query 

{

  totalDays

} 

and click on the Play button to execute the query.


9. You will see there is a random number being generated for `totalDays`. It's so because you have set `mocks: true` under `new ApolloServer()` in the `index.js` file. This allows us to have some data returned without having to think about data sources when just starting.

10. Everything's working fine so let's now create a custom object User. Then add some fields of our custom object.


11. Once this custom object is created, let's add a query for Users.


12. Head back to your GraphQL playground and query for Users. We see that we have an array of objects coming with the Apollo server mocking the data for us.

13. Next, let us add an enumeration type. Enums are like a restricted list of options for a field. Also, add this field in your query in your playground. On clicking `Play` on your playground, you see that we get data for userTypes but from our enum only.


14. Let's work with a different operation of GraphQL which is mutation. In your `index.js` file, under typeDef, add `type mutation {}` and define a field to remove a user with an ID and make it return deleted User details. Mutations are used to change data.


15. Write the mutation in your playground and it will return mock data.

Comments

Popular

How To Create MySQL Table with SequelizeJS

How To Read CSV Files in Java as Maven Project

How To Create A Hibernate Project in Maven