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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!