Log in to GraphQL EditorGet started
Zeus update - GraphQL spread operator

Michał Tyszkiewicz

9/24/2024

Zeus update - GraphQL spread operator

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 Fragments

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! :)

Zeus fields - GraphQL spread operator

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'),
    },
  ],
});

Never go full REST

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.

Check out our other blogposts

GraphQL cache: using LRU cache with GraphQL Zeus
Michał Tyszkiewicz
Michał Tyszkiewicz
GraphQL cache: using LRU cache with GraphQL Zeus
1 min read
8 days ago
Unlocking the Power of React 19
Tomasz Gajda
Tomasz Gajda
Unlocking the Power of React 19
1 min read
about 2 months ago
Zeus update - GraphQL spread operator
Michał Tyszkiewicz
Michał Tyszkiewicz
Zeus update - GraphQL spread operator
1 min read
3 months ago

Ready for take-off?

Elevate your work with our editor that combines world-class visual graph, documentation and API console

Get Started with GraphQL Editor