Question

I recently had to optimize my graphql API server by selecting only specific fields from the database before returning the actual result to the client. For example, let's say my graphql schema has the entity called Product:

type Product {
  name: String!
  details: String
  company: String
}

In addition to the 3 fields above there're another 30 fields some of which are nested objects. I noticed that one of my resolvers took too long to return the result so as part of the optimisations I thought to myself: "If the client currently asks for only 5% of the total fields which are available for Product so maybe I should use projection in my query to select only the 5% of the possible fields". (For an SQL-based database SELECT could be used similarly). But I'm wondering if conceptually it's the right thing to do because one of the cool things about graphql is that you know you can select any field for some entity. But in this case I'm just using the trick that currently only 5% of the fields are requests. To clarify the only client using my API is myself (my company).

What do you think, is this OK?

Was it helpful?

Solution

one of the cool things about graphql is that you know you can select any field for some entity.

Don't make the mistake of thinking that your GraphQL schema has to have a 1:1 mapping with your database schema. It's perfectly fine for there to be fields in your database which can't be fetched via the GraphQL API, and it's also perfectly fine for there to be fields in your GraphQL schema which aren't a direct mapping to a database field. Work out what the business needs are for your GraphQL API, implement those and don't build stuff just because you can.

Even given all that, I think it's fairly obvious you should be doing projections - but these should be dynamic based on the specific request made; if the GraphQL request contains only name, then just select the appropriate name field from the database, don't fetch details or company, because you're just going to throw all that data away before returning it to the client.

Licensed under: CC-BY-SA with attribution
scroll top