DEV Community

A simple caching strategy for Node REST APIs, Part 1

Vignesh M on March 03, 2019

Hello World, this is the beginning of 2 Part Series on "How to make your REST APIs blazing fast 🚀". These are from my personal experiences and from...
Collapse
 
chema profile image
José María CL

Thanks!

I will leave my implementation to help others to figure out how to implement this approach

// get-mydata-controller.ts
export const getMyDataController = async (req, res, next) => {
  try {
    const { id } = req.params;
    const myDataRepository: MyDataRepository = new PrismaMyDataRepository();
    const myData = await getMyData(
      id,
      myDataRepository
    );

    res.locals.data = myData; // make the result accesible to the middlewares

    next(); // allow the next middleware to handle the response data
  } catch (err) {
    res
      .status(500)
      .json({ data: null, error: err.message });
  }
};
Enter fullscreen mode Exit fullscreen mode
// response-handler.ts
export function responseHandler(message = "Data successfully fetched") {
  return (req, res) => {
    res
      .status(200)
      .json({ data: res.locals.data, message });
  }
}

Enter fullscreen mode Exit fullscreen mode
// routes.ts
router.get(
  "/:id/my-data",
  cacheLayer.get,
  getMyDataController,
  cacheLayer.set,
  responseHandler("My Data successfully fetched")
);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gijovarghese profile image
Gijo Varghese

I wrote a similar one but saving data in Cloudflare edge servers coffeencoding.com/how-i-used-cloud...

Collapse
 
nikosdev profile image
Nikos Kanakis

Awesome Post 🏆

Collapse
 
svenvarkel profile image
Sven Varkel

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?

What's your cache backend?

Collapse
 
vigzmv profile image
Vignesh M

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.

Collapse
 
namthang_ng profile image
Nguyễn Nam Thắng

Can you explain the processQuery, responseHandler fuction for me.

Collapse
 
vigzmv profile image
Vignesh M

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.

Collapse
 
namthang_ng profile image
Nguyễn Nam Thắng

thank bro

Collapse
 
namthang_ng profile image
Nguyễn Nam Thắng

Thank you. Do you still have this tutorial. i don't see it on your github

Collapse
 
fukamichal profile image
fuka-michal

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 :)

Collapse
 
shashidhar85 profile image
shashidhar reddy

Hi, can you please share index file also ?