Start using GraphQL with OSS LWC
In this article we will explorer the use of GraphQL along with Express server within our LWC OSS app.
What is it ?
GraphQL is a data language and an API technology. Originally developed by Facebook later on has moved to be open-sourced .
When it comes to building API’s to your app data points, many wonder what would be the ideal way?
Using REST API would be the current modern convention, but GraphQL really stands out as an alternative architecture mainly (but not only) because it provides a “discoverable API” by design.
It also comes with its own query language and a runtime engine for fulfilling queries via functions called resolvers.
High level benefits :
- One unified API to consume data and perform your calls against.
- Allows the Client to define the structure of data in payloads.
- No Over-Fetching or Under-Fetching – you only get the data you specify – nothing less and nothing more.
- Allows a better Client side development experience
- Strongly Typed with advanced intellisense features in IDE.
- Scalable and easy to maintain.
With those great benefits there are a few draw backs in my opinion you should consider before migrating your entire REST API infra-structure into GraphQL.
- There is a Learning Curve for learning how to set up and start running and specially when it comes to optimization at scale.
- Infrastructure and Tooling might be different in some levels.
High level Design for our app
- Our Client app will generate a POST call to a single endpoint.
- The payload body will hold the query to retrieve all fields defined in the schema.
- GraphQL basically intercept the call from the defined endpoint and perform all other calls it needs in an efficient way that returns all values you expect and defined inside your schema.
- All will be done in a single callout – which is really cool and efficient.
Breakdown Steps
- Express Server will be setup with an endpoint
graphql
will be imported and we will set it up as a separate JS module- This will be example in Javascript but can be in TS.
- our schema will basically operate the entire Graph output payload to your client.
Install packages: (assuming we have express installed)
npm i graphql
npm i express-graphql
Add GraphQL as Url route in our Express server
Build your GraphQL Schema and Hello World Query
Client Rest call to GraphQL