I will leave my implementation to help others to figure out how to implement this approach
// get-mydata-controller.tsexportconstgetMyDataController=async(req,res,next)=>{try{const{id}=req.params;constmyDataRepository:MyDataRepository=newPrismaMyDataRepository();constmyData=awaitgetMyData(id,myDataRepository);res.locals.data=myData;// make the result accesible to the middlewaresnext();// allow the next middleware to handle the response data}catch(err){res.status(500).json({data:null,error:err.message});}};
It seems that you're using URL as cache key, right? Things to be considered:
are the URL-s public? I.e circumstances changes when the URL-s are behind authentication because then you cannot send back the same responses to all users etc.
do all the parameters come in via URL? Are there any headers or anything that may differ between requests? Should these be considered?
Both of these considerations depend upon one's own project and what routes they want to cache. This example works best for data that only dependents on the URL and not any context like current user.
Hey, processQuery & responseHandler are not anything related to caching or have anything to do with this artcle. They are just examples of common middlewares.
In our app, processQuery transforms some of our url query params, does some checks if they are valid.
responseHandler just converts the response data to json and returns a 200 status.
This may not be everyone's usecase.
Thanks!
I will leave my implementation to help others to figure out how to implement this approach
Awesome Post 🏆
I wrote a similar one but saving data in Cloudflare edge servers coffeencoding.com/how-i-used-cloud...
It seems that you're using URL as cache key, right? Things to be considered:
What's your cache backend?
Both of these considerations depend upon one's own project and what routes they want to cache. This example works best for data that only dependents on the URL and not any context like current user.
Can you explain the processQuery, responseHandler fuction for me.
Hey,
processQuery&responseHandlerare not anything related to caching or have anything to do with this artcle. They are just examples of common middlewares.In our app,
processQuerytransforms some of our url query params, does some checks if they are valid.responseHandlerjust converts the response data to json and returns a 200 status.This may not be everyone's usecase.
Thank you. Do you still have this tutorial. i don't see it on your github
thank bro
function getUrlFromRequest(req) {
const url = req.protocol + '://' + req.headers.host + req.originalUrl
return url
}
becasue of req.protocol in key the cache is not effective as can be :)
Hi, can you please share index file also ?