Request-scoped singleton in SuiteScript scripts

Answered

Hi all,

In my SuiteApp, I have a use case for a request-scoped singleton object which could be accessed easily by various parts of the code, asked to store some information on each access, and send it off at the end of each script execution.

For clarity, by request-scoped I mean that each separate execution of a script gets its own copy of the singleton object.

For concreteness, let’s say it’s like this:

/**
 * MyStore.js
 * @NApiVersion 2.1
 */
define([], function () {
    let instance;
    function getInstance() {
        if (!instance) {
            instance = new Map();
        }
        return instance;
    }

    return { getInstance };
});

And used like this in various places:

[...]
const store = MyStore.getInstance();
store.set('someKey', 'someValue');
[...]

Now, my concern is: will such a singleton object will be truly request-scoped? I.e. am I guaranteed that two (simultaneous?) executions of the same script or of different scripts, but using this object will get two distinct copies of the object? I suspect they will, but would appreciate a confirmation.

I couldn’t find any info on the internal execution model within NetSuite backend – hence the question.

Many thanks!

Jan

Rookie Asked on June 5, 2024 in SuiteApps.
Add Comment
1 Answer(s)
Best answer

Hi Jan,

Your ‘instance’ here is scoped to the function within define and so it behaves like standard Javascript in that separate executions behave independently.

Moreover, even if you were to set a var I’m pretty sure the behaviour would be the same.

In short, nothing will leak outside a particular invocation of a script.

Thanks,

Chris

Advanced Answered on June 5, 2024.

Thanks a lot!

on June 5, 2024.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.
  • This site made possible by our sponsors:   Tipalti   Celigo   Become a Sponsor   Become a Sponsor