7 Optimizing data fetching

 

This chapter covers

  • Caching and batching data-fetch operations
  • Using the DataLoader library with primary keys and custom IDs
  • Using GraphQL’s union type and field arguments
  • Reading data from MongoDB

Now that we have a GraphQL service with a multimodel schema, we can look at one of GraphQL’s most famous problems, the N+1 queries problem. We ended the previous chapter with a GraphQL query that fetches data from three database tables.

Listing 7.1 The N+1 query example
{
  taskMainList {
    // ·-·-·
    author {
      // ·-·-·
    }
    approachList {
      // ·-·-·
      author {
        // ·-·-·
      }
    }
  }
}

Because the GraphQL runtime traverses the tree field by field and resolves each field on its own as it does, this simple GraphQL query resulted in a lot more SQL statements than necessary.

7.1 Caching and batching

To analyze a solution to this problem, let’s go back to the simpler query from listing 6.30.

Listing 7.2 The taskMainList query
{
  taskMainList {
    content
    author {
      id
      username
      name
    }
  }
}

7.1.1 The batch-loading function

7.1.2 Defining and using a DataLoader instance

7.1.3 The loader for the approachList field

7.2 Single resource fields

7.3 Circular dependencies in GraphQL types

7.3.1 Deeply nested field attacks

7.4 Using DataLoader with custom IDs for caching

7.4.1 The taskMainList field

7.4.2 The search field

7.5 Using DataLoader with MongoDB

Summary

sitemap