Search code examples
javascriptnode.jscachingsuperagent

Caching HTTP responses using superagent-cache for different params


I am using superagent-cache for caching responses on Node Express server. So the request goes like this:

myServer.com/api/posts?id=21

And the caching works perfectly. Once Node fetches the response from API server, it passes the same data to all the visiting users instead of calling API again and again.

Now the problem is that I want to add user's ID to the request. So the new request becomes:

myServer.com/api/posts?id=21&userId=123

Now the caching becomes user specific. Superagent takes it as a separate request and fetches it every time for each user. Which is redundant. Is there any way i can tell superagent to avoid userId param ?


Solution

  • I'm the author of superagent-cache. Glad you're enjoying it!

    You can use the .pruneQuery chainable to execute a query with a given param but cache it without that param as part of the generated key.

    Your new code should look something like this:

    superagent
      .get('myServer.com/api/posts')
      .query({id: id, userId: userId})
      .pruneQuery(['userId'])
      .end(function (error, response){
        // handle response
      }
    );