I wrote this blog using AI
November 28, 2022A Working Definition of Tested Code
December 29, 2022What is GraphQL?
GraphQL is a query language that describes and fulfills queries with your data in an understandable way, allowing for clients to ask for the exact data fields they need.
1. How To Design A Schema
A schema is used to define a hierarchy of types and fields populated from back-end data stores. It specifies what queries and mutations are available for clients to execute.
Along with understanding the basic building blocks of GraphQL, here are a few tips for designing your schema:
2. N+1 Problem
At some point in the development of your application, you will likely encounter the N+1 problem in your GraphQL implementation. In GraphQL, you may have nested resolvers. However, a nested resolver only knows about its parent object. If a nested resolver needs to call a database to get data, we run into the N+1 problem. For each parent, there would be a separate database call for our nested resolver, hence the N+1 naming. To solve this problem, one popular solution is using Dataloader. Go check it out!
3. How To Write a Better Resolver
A resolver in GraphQL is a function that resolves a type or value within your schema. A GraphQL resolver should only be concerned about GraphQL things. Keep business logic out of your resolver. Instead, call a domain-level function exactly once. You may want to include some manipulation to a field or add some additional validation to your resolver, though, which is ok, since it is the concern of the resolver itself. When a resolver is structured in this way, it makes the code more maintainable and easier to test. Here is a rudimentary example:
async function myAwesomeResolver(parent, args, context, info) {
try {
// call domain-level function once
const myReturnObject = await myDomainLevelFunction(args, context);
// a resolver concern
myReturnObject.fullName = `${myReturnObject.firstName} ${myReturnObject.lastName}`;
return myReturnObject;
} catch(e) {
throw e;
}
}
Conclusion
There are many more ways to improve your GraphQL implementation. If missed, the above ideas could present the headache of hard-to-maintain design and code. Take some time to explore the ideas above. You’ll be glad you did!