GraphQL is a very powerful and versatile tool, but it's very easy to use it wrong.
1. GraphQL is not REST
GraphQL allows clients to request specific data in a single request, while REST uses a fixed set of endpoints with predefined data.
GraphQL queries are very different from REST endpoints. Expose your data to the client by creating generic queries, allowing the client to compose the request as they need. Decouple your API from the application.
Avoid creating situation-specific queries.
2. Use Resolvers as functions
Resolvers can be functions; that's the real deal.
Use them as functions; don't limit your data to what's in the database. Decouple the DB structure from the shape you want to expose to the client. Use resolvers to manipulate data and connect entities.
Make resolvers your strength; they are the reason why GraphQL is so powerful.
3. Create Custom Scalars
Create custom types in GraphQL, as it is a typed system.
You should create custom scalars for structures that don't fall into GraphQL standard scalar types. Custom scalars can be used to validate input and output data, as well as to parse and serialize values in specific ways.
Make your types safe and modular by using and reusing custom scalars.
4. Cache data using Dataloaders
The same data may be requested more than once in the same query.
Entities in GraphQL may be connected in different ways because GraphQL is a graph. Dataloaders ensure that the entity is only loaded the first time and cached every other time when this occurs.
Using dataloaders to cache data will greatly improve your performance.
5. Decompose queries using Fragments
Fragments are a way to make your GraphQL queries modular on the client.
Having one giant query on a single component on the client is not ideal. It is way better to split the query into multiple components where each component only requests the data it needs. Don't worry about multiple requests, several GraphQL frameworks will merge those queries automatically.
Make queries modular using Fragments.
Top comments (0)