Learn how to use suite script n/cache module

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

Conclusion

The N/cache module in NetSuite is a powerful tool for enhancing performance by efficiently storing data for short periods. By utilizing the module to store tokens, scripts can eliminate redundant data retrieval, significantly improving execution time. Implementing a map/reduce script that fetches and stores tokens in the cache optimizes repetitive tasks and ensures seamless execution. Harness the power of the N/cache module to unlock enhanced performance and streamline your NetSuite development processes.

Do you need help with customizing NetSuite?  Please contact Suite Tooth consulting here to set up a free consultation.

If you liked this article, please sign up for my newsletter to get these delivered to your inbox here.

Follow on
Jaime Requena Chief Executive Officer

Jaime Requena is a seasoned NetSuite Consultant and Solutions Architect, known for delivering WHITE GLOVE service to businesses. With 15+ years of experience and 3x certifications in ERP, Developer, and Admin, Jaime specializes in highly customized NetSuite accounts, transforming operations for 200+ satisfied customers all across the globe.

Get Connected

How can we help?


    Stay in the loop with Suite Tooth Consulting!

    We aim to bring unmatched expertise and professionalism to your NetSuite initiatives. Let’s talk about how our NetSuite consultancy can make a difference!

    Global Client Satisfaction

    Client Testimonials

    It’s Been 4+ Years Now And We Have Worked With Hundreds Of Clients, Building Our Way To The Top, One Happy Client After Another! Their Voices Of Satisfaction Serve As A Testament To Our Success –