Skip to content

Instantly share code, notes, and snippets.

@zaynelt
Created February 17, 2021 21:34
Show Gist options
  • Save zaynelt/788977ce5a2b87d55ab9bc57885fa8d2 to your computer and use it in GitHub Desktop.
Save zaynelt/788977ce5a2b87d55ab9bc57885fa8d2 to your computer and use it in GitHub Desktop.
Commerce Cloud Personalized Caching via Script API
// SFRA controller cached via decorator
server.get('Show', cache.applyDefaultCache, function (req, res, next) {} );
// set cache time directly at the response (does not rely on SFRA)
response.setExpires(new Date().getTime() + durationInMinutes * 60 * 1000);
// apply personalised caching
response.setVaryBy('price_promotion');
// Cache times do not have to be constants - let's get creative!
// apply layered caching times by product availability levels
var availabilityModel = product.getAvailabilityModel();
if (availabilityModel.isOrderable(50)) {
// cache 5 days when >= 50 orderable
response.setExpires(new Date().getTime() + 120 * 60 * 60 * 1000);
} else if (availabilityModel.isOrderable(20)) {
// cache 1 day when >= 20 orderable
response.setExpires(new Date().getTime() + 24 * 60 * 60 * 1000);
} else if (availabilityModel.isOrderable(5)) {
// cache 4 hours when >= 5 orderable
response.setExpires(new Date().getTime() + 4 * 60 * 60 * 1000);
} else {
// cache 30 minutes when < 5 orderable
response.setExpires(new Date().getTime() + 30 * 60 * 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment