Cache Database Requests Across GraphQL Resolvers

Jacob Paris
InstructorJacob Paris
Share this video with your friends

Social Share Links

Send Tweet

We're going to build a cache that sits between the GraphQL resolvers and the database and ensures we only have to fetch each user once, while later requests for the same users will return them from the cache immediately

Instructor: [0:00] To implement a cache, we need to add a layer of abstraction between the resolver and the database request. That cache layer is responsible for deciding whether request actually queries the database or just returns a cached value.

[0:13] Let's create an object named cache with a method named load, and copy paste the database request from the author resolver. Then the author resolver can just call cache.load with the author ID and everything should work just like it did before.

[0:32] We can send the same request multiple times and it still hits the database every time. We'll give the cache a promises object that will work like a map or a dictionary. The keys in the object are the user IDs we've tried to load. The values are the database request for that user ID.

[0:48] We can guard this function with a check to see if the promises object already contains this key. If so, return the promise from the cache. If it doesn't, then we add the database request to the cache and return it.

[1:02] To make it easier to see what's going on, we'll add a console.log, cache hit for key. If we query the post now, we can see that every user that was called more than once, responds first from the database, and then from the cache. That's users 1, 2, and 4.

[1:17] No database entry is called twice. That's good. If we send a second request, every user is served from the cache again and will continue to be until the server restarts. That's bad, but we'll fix that shortly.