Modules

filter

 

Objects/Functions

module (N/cache)

SuiteScript 2.0

Main Examples

N/cache Module
Member Type: Name
Search NetSuite - https://system.netsuite.com/app/help/helpcenter.nl?search=N/cache Module

// Code Example 1
/**
* @NApiVersion 2.x
* @NScriptType Suitelet
*/

// This script retrieves the name of a city based on a ZIP code, using a cache.
define(['N/cache', '/SuiteScripts/zipToCityIndexCacheLoader'], function(cache, lib) {
const ZIP_CODES_CACHE_NAME = 'ZIP_CODES_CACHE';
const ZIP_TO_CITY_IDX_JSON = 'ZIP_TO_CITY_IDX_JSON';

function getZipCodeToCityLookupObj() {
var zipCache = cache.getCache({
name: ZIP_CODES_CACHE_NAME
});
var zipCacheJson = zipCache.get({
key: ZIP_TO_CITY_IDX_JSON,
loader: lib.zipCodeDatabaseLoader
});
return JSON.parse(zipCacheJson);
}

function findCityByZipCode(options) {
return getZipCodeToCityLookupObj()[String(options.zip)];
}

function onRequest(context) {
var start = new Date();
if (context.request.parameters.purgeZipCache === 'true') {
var zipCache = cache.getCache({
name: ZIP_CODES_CACHE_NAME
});
zipCache.remove({
key: ZIP_TO_CITY_IDX_JSON
});
}
var cityName = findCityByZipCode({
zip: context.request.parameters.zipcode
});

context.response.writeLine(cityName || 'Unknown :(');

if (context.request.parameters.auditPerf === 'true') {
context.response.writeLine('Time Elapsed: ' + (new Date().getTime() - start.getTime()) + ' ms');
}
}
return {
onRequest: onRequest
};
});

// Code Example 2
/**
* zipToCityIndexCacheLoader.js
* @NApiVersion 2.x
* @NModuleScope Public
*/

//This custom module is a loader function that uses a CSV file to retrieve a value that was missing from a cache.
define(['N/file', 'N/cache'], function(file, cache) {
const ZIP_CODES_CSV_PATH = '/SuiteScripts/Resources/free-zipcode-CA-database-primary.csv';

function trimOuterQuotes(str) {
return (str || '').replace(/^"+/, '').replace(/"+$/, '');
}

function zipCodeDatabaseLoader(context) {
log.audit('Loading Zip Codes for ZIP_CODES_CACHE');
var zipCodesCsvText = file.load({
id: ZIP_CODES_CSV_PATH
}).getContents();
var zipToCityIndex = {};
var csvLines = zipCodesCsvText.split('\n');
util.each(csvLines.slice(1), function(el) {
var cells = el.split(',');
var key = trimOuterQuotes(cells[0]);
var value = trimOuterQuotes(cells[2]);
if (parseInt(key, 10))
zipToCityIndex[String(key)] = value;
});
return zipToCityIndex;
}

return {
zipCodeDatabaseLoader: zipCodeDatabaseLoader
}
});

//SOURCE: https://system.netsuite.com/app/help/helpcenter.nl?fid=section_4642573343.html