Search code examples
javascriptnetsuitesuitescript

Efficiently Saving Multiple Records with One Call to Record.save() in SuiteScript


I'm working with SuiteScript and have encountered a scenario where I need to record 20 sales order records. My understanding is that each call to the Record.save() method consumes units, similar to points. This leads me to two questions:

  1. To save 20 sales order records, do I need to call Record.save() 20 times, resulting in a significant consumption of units?
  2. Is there a more efficient way to save these 20 records with a single call to Record.save(), which would reduce the unit cost?

I'm looking for a solution that allows me to save multiple records efficiently without excessively depleting my units. Any insights or alternative methods for handling this in SuiteScript would be greatly appreciated. Thank you!


Solution

  • Don't think of the NetSuite script governance units as something you need to be scared of depleting; think of them as a sanity check against doing something that will cause problems for your users or system. In other words, the governance system is set up to protect you from yourself.

    For example, if your question relates to a User Event or Client script, saving 20 sales orders will cause a long delay whenever it's fired, and that would not even (by itself) cause a governance exceeded error. (Record.save() uses 20 units per invocation, so 400 total. Including the units from loading or creating wopuld have you up to 600 - still well below the 1000 unit total allowed.)

    To answer your question, you would need to call Record.save() once for each record, as it is a method on the Record instance object. There is no SuiteScript API, for example, which accepts an array of Record objects and saves them all.

    There are several options for improving performance, depending on your specific use case:

    1. If you only need to update body level fields which support inline editing, you can use record.submitFields(). This will be more performant and use half the governance units, compared with loading and saving.
    2. If using a client script, I wouldn't recommend saving 20 records from within a client script but you can use Record.save.promise() to enable your flow to continue while the records save asynchronously. This would still use the same amount of governance units, but may significantly improve user experience.
    3. For either client or user event, you can save the relevant data to a custom record or text file (EG: as JSON data), and then call a Scheduled or Map/Reduce script to complete the bulk of the work. In this scenario, your client or user event would save the data, and then schedule the Scheduled or Map/Reduce script using the N/task module. The record or file to be processed by the scheduled script can be passed as a script parameter or discovered using a predefined flag (field) on the custom record, or retrieved from a specified folder if using a file.