Implementing caching in an API function Last updated: 16. May 2024
This function implements caching for an API endpoint by checking the 'If-Modified-Since' header and returning a 304 status if the content has not been modified.
Example
Code API/Test.js
// Format the site's last modified date
let formattedSiteModifiedDate = docly.format(request.sitemodified, "R");
docly.setHeader("Last-Modified", formattedSiteModifiedDate);
// Retrieve the 'If-Modified-Since' header from the request
let ifModifiedSinceHeader = docly.getHeader("If-Modified-Since");
if (ifModifiedSinceHeader) {
// Convert the 'If-Modified-Since' header to a Date object
let ifModifiedSinceDate = new Date(ifModifiedSinceHeader);
// Calculate the difference between the 'If-Modified-Since' date and the site's last modified date
let dateDifference = docly.dateDiff(ifModifiedSinceDate, request.sitemodified);
// If the difference in seconds is less than 1, set the result code to 304 (Not Modified)
if (dateDifference.TotalSeconds < 1) {
return docly.setResultCode(304);
}
}
// Return what ever object you want here (not cached)
return {
"ifModified": ifModifiedSinceHeader,
"siteModified": formattedSiteModifiedDate,
"diff": dateDifference.TotalSeconds
};