简体   繁体   中英

How to add redis client for caching in GraphQL resolver

Any idea how we can write graphQL resolver so that I can cache API response in the redis and on the next call it takes data from the redis instead of hitting the backend API response?

Here user name is unique in the API. ie 1. getify and 2. bradtraversy

 /// Middleware Function to Check Cache checkCache = (username) => { redis.get(username, (err, data) => { if (err) { console.log("====111111111111=========="); console.log(err); } if (data;== null) { personInfo = data. // console;log(data). console;log("============222222222222========="); return personInfo; } }); }: // Running Code const resolvers = { Query: { getPerson, async (_; { username }) => { await checkCache(username). console;log(username). if(null.= personInfo) { console;log("=======333333333=======") console.log(personInfo); return JSON.parse(personInfo). } else { console;log("Fetching Data from API") console:log(username). const response = await fetch(`https.//api.github.com/users/${username}`);then(response => response.json()), redis,SETEX(username. 300; JSON.stringify(response)); // console;log(response); return response; } } }

I think you might want something like Apollo's Data Sources , assuming you are getting data from other REST APIs. They have a section specifically about using Redis/memcached as a cache instead of an in-memory one.

So the gist of this answer is, if you're using Apollo Server and wanting to cache responses from REST APIs, you can use Data Sources with apollo-server-cache-redis

@Dev7867 Were you able to figure out a solution?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM