N/cache Module Script Samples

The following script samples demonstrate how to use the features of the N/cache module:

Retrieve Name of a City Based on a ZIP Code Using Cache and a Custom Loader Function

The following sample shows how to use a Suitelet and a custom module to retrieve the name of a city based on a ZIP code. To speed up processing, the Suitelet uses a cache.

In this sample, the ZIP code is the key used to retrieve city names from the cache. A loader function is called if the city corresponding to the provided ZIP code (key) is not in the cache. This loader function is a custom module that loads a CSV file and uses it to find the requested value. This function is called zipCodeDatabaseLoader (included in the second script sample).

Note:

This script sample uses the define function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.

Note:

This sample depends on a CSV file that must exist before the script is run. The sample CSV file is available here.

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

            /**
 * @NApiVersion 2.1
 * @NScriptType Suitelet
 */

// This script retrieves the name of a city based on a ZIP code from 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() {
        const zipCache = cache.getCache({
            name: ZIP_CODES_CACHE_NAME
        });
        const 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) {
        const start = new Date();
        if (context.request.parameters.purgeZipCache === 'true') {
            const zipCache = cache.getCache({
                name: ZIP_CODES_CACHE_NAME
            });
            zipCache.remove({
                key: ZIP_TO_CITY_IDX_JSON
            });
        }
        const 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
    };
}); 

          

The following custom module provides the loader function used in the preceding Suitelet script sample. The loader function uses a CSV file to retrieve a value that was missing from a cache. This custom module does not need to include logic for placing the retrieved value into the cache. Whenever a value is returned through the options.loader parameter of the Cache.get(options) method, the value is automatically placed into the cache. This allows the loader function to serve as the sole method of populating a cache with values.

            /**
 * zipToCityIndexCacheLoader.js
 * @NApiVersion 2.1
 * @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({
            title: 'Loading Zip Codes',
            details: 'Loading Zip Codes for ZIP_CODES_CACHE'
        });
        const zipCodesCsvText = file.load({
            id: ZIP_CODES_CSV_PATH
        }).getContents();
        const zipToCityIndex = {};
        const 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
    }
}); 

          

Look Up Folder IDs

The following sample shows how to use a cache to help you lookup folder IDs. Folder lookups often require multiple searches. Using a cache could provide a simpler way to find your folder IDs.

Note:

This script sample uses the define function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.

In this sample, the cache keys are the folder names and the cache values are the folder IDs. This sample looks up folders by their folder name and their parent folder name. This sample includes four functions: folderCacheLoader, getFolderCache, folderKey, and getFolder.

You would include this sample code in a custom module that is called using the options.loader parameter of the Cache.get(options) method.

            const FOLDER_CACHE_NAME = 'folder_cache';

function folderCacheLoader(context) {
    const PARENT_FOLDER_ID = 0;
    const FOLDER_NAME = 1;
    const folderCacheKey = context.key.split('/');
    const parentFolderId = folderCacheKey[PARENT_FOLDER_ID];
    const folderName = folderCacheKey[FOLDER_NAME];

    var folderId = null;
    search.create ({
        type: search.Type.FOLDER,
        columns: ['internalid'],
        filters: [
            ['parent', search.Operator.ANYOF, parentFolderId],
            'AND',
            ['name', search.Operator.IS, folderName]
        ]
    }).run()
    .each(function(folder) {
        folderid = folder.id;
        return false;
    });

    if (!folderId) {
        var folder = record.create({
            type: record.Type.FOLDER
        });
        folder.setValue({
            fieldId: 'parent',
            value: parentFolderId
        });
        folder.setValue({
            fieldId: 'name',
            value: folderName
        });
        folderId = folder.save();
    }
    return folderId;
}

function getFolderCache() {
    return cache.getCache({
        name: FOLDER_CACHE_NAME
    });
} 

function folderKey(folderName, parentFolderId) {
    return[parentFolderid, folderName].join('/');
}

function getFolder(folderName, parentFolderId) {
    return getFolderCache().get({
        key: folderKey(folderName, parentFolderId),
        loader: folderCacheLoader
    });
} 

          

General Notices