How I Mock GraphQL API for Frontend Development
Mock API using GraphQL Mesh for faster project development
As a frontend developer, our work is often depend on backend developer’s work. Some people might wait for the backend developer finish their work then start to code. And some just start right away, even though backend hasn’t ready yet. I choose to do the latter because waiting is absolutely not fun at all. At the beginning of a project, I will normally define API contract with teammates before jumping into code. After that, both backend and frontend can do their work independently and that’s when I begin to code by creating a mock API based on the API contract. But before we move on, I should mention the constraint first
- I have existing endpoint displaying SpaceX missions
- I want to extend existing API. I don’t want to create graphql schema from scratch unless it is new API
- I prefer mock API code to be separated from the client code
Setup GraphQL Mesh
Well, I use GraphQL Mesh in my local machine as the mock server. It is actually a GraphQL Gateway which can turn any API into GraphQL. Check out my story implementing GraphQL Mesh as API Gateway which increase engineer’s productivity. The next thing I need is just a configuration to connect my local GraphQL Mesh with existing GraphQL server.
Here, we define sources
which can be anything like REST, gRPC, GraphQL, MySQL, etc. Then, we can just hit yarn dev
to start the server and GraphQL Mesh will automatically translate the sources into GraphQL Schema. We will have access to all queries and mutations through the playground
Extending GraphQL Schema
Suppose that I have an app displaying list of SpaceX mission and for future release, product team decides to display owner
and email
. Now we need to add those new properties to existing endpoint by extending GraphQL Schema using additionalTypeDefs
. First, we need to check the type of missions
by searching in the right column and we know that missions
is actually array of Mission
.
Then, we can see that our newly added properties owner
and email
appear on the playground. So easy isn’t it? but yes I know, it still null
Create Resolver
The next step would be resolving our new properties to certain value. Here we will create an object which represents Mission
type then add new properties owner
and email
. Both new properties will contain a function that return a string based on schema definition we’ve added.
Finally, we have successfully mock our existing API by adding new properties and use it to develop our client app. We can even add faker.js
to randomly generate value. This is only the basic of mocking with GraphQL Mesh, for further mocking implementation with GraphQL Mesh you can refer to this document and the code is available here. Well, this is pretty much what I do on daily basis, there are so many different tools and approach for mocking API. You just need to make sure that any tools you use, really help you work better.