Introduction
In NetSuite development, the N/cache module plays a vital role in optimizing performance by efficiently storing data for a limited duration. By leveraging this module, scripts can avoid repetitive data retrieval, resulting in improved efficiency and reduced execution time. One common scenario where N/cache proves invaluable is storing tokens that are generated once and reused multiple times. In this article, we will explore how to utilize the N/cache module to store tokens and build a map/reduce script that fetches a token, stores it in the cache, and efficiently utilizes it for subsequent iterations.
Use Case: Token Storage
To illustrate its implementation, let’s consider a map/reduce script. The script begins by calling a web service to retrieve a token, which is then stored in the cache. In subsequent iterations of the map/reduce process, the script will utilize the token stored in the cache until it is removed.
When the token is removed from the cache, the script calls a loader function to generate a fresh token and stores it again for future use. This approach ensures that the token remains up-to-date and readily available for efficient processing.
/**
* @NApiVersion 2.1
* @NScriptType MapReduceScript
*/
define(['N/https', 'N/cache'],
(https, cache) => {
const getInputData = (inputContext) => {
// Get data to act on
}
const reduce = (reduceContext) => {
try {
// Get the cache object with the name "tokencache"
let objCache = cache.getCache({
name: 'tokencache',
});
// Get the token from the cache, if token does not exist, loader function will
// retrieve the token and store it in the cache.
// The time to live (ttl) is the maximum number of seconds the value will remain in the cache
// If you know how long the token is valid for, set ttl to this amount of seconds
let stringObjToken = objCache.get({
key: 'token',
loader: getToken,
ttl:900
});
// use token as needed to make https calls
}
catch(e){
log.error('reduce',JSON.stringify(e));
}
}
// Retrieve the token
const getToken = () => {
let objectResponse = https.post({
url: 'https://gettoken.com/token',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {
// flesh out as needed
},
});
if (objectResponse.code === 200){
return objectResponse.body
}
}
return {getInputData, reduce}
});