Retrieve the Name of the City Based on a ZIP Code

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
    }
}); 

        

Related Topics

SuiteScript 2.x Suitelet Script Type
SuiteScript 2.x Suitelet Script Type Code Samples
Backend Suitelets
N/cache Module

General Notices