Michał Tyszkiewicz
9/24/2024
Welcome to a short post about a recent quality of life update to GraphQL Zeus. If you're not familiar with GraphQL Zeus go ahead and read my earlier post which breaks down its basics. If you are lets go ahead and talk about the update!
GraphQL has long supported reusable fields natively with the use of fragments. If you're not familiar with them basically if you had the same fields in multiple queries you could define a fragment - a set of fields, and then reuse it instead of repeating all the fields every time. Lets say you had a user with some fields like name, email, address. Then you could use a fragment like this:
query getUser {
user(id: 4) {
...userFields
}
}
fragment userFields on User {
name,
email,
address,
avatar
}
For reusability you could put all your fragments in a fragments.js file and then use them across a project. Zeus already had a solution like Selectors (which work a bit similarly to that) but with the latest update it can now go a step further! :)
For our example lets say we need to get the posts data for our blog page where we display them in a grid, usually the query that would look something like this:
const posts = await Chain('http://example.com/api/graphql')('query')({
posts: [
{
title: true,
coverImage: true,
publishedAt: true,
slug: true,
content: { markdown: true },
},
],
});
With Zeus 6.0.0 you can simply use a spread operator ...fields
with the TypeScript type from the schema (eg. Post
) to simply get all the fields available for that type:
const posts = await Chain('http://example.com/api/graphql')('query')({
posts: [
{
...fields('Post'),
},
],
});
With this, we now have a convenient quality-of-life improvement for cases where you just want to quickly retrieve all the fields for a type. That said it's important to remember what GraphQL is all about - getting exactly what you requested without overfetching. So don't just use ...fields
everywhere or you'll defeat the entire purpose of using GraphQL in the first place and turn it into REST, always pulling way more data than necessary.