SuiteScript snippets

Small pieces of SuiteScript 2.1 I reuse on most projects. Each one is self-contained and safe to drop into an SDF project. Copy, rename the ids, go.

SuiteQL: fetch every row with paging

SuiteQL caps a single run at 5,000 rows. This helper pages through a query and returns all results as plain objects, so callers never think about page boundaries.

suiteql-all-rows.js
/**
 * @NApiVersion 2.1
 * Run a SuiteQL query and return every row, regardless of size.
 */
define(['N/query'], (query) => {

  /**
   * @param {string} sql     SuiteQL with ? placeholders
   * @param {Array}  params  values for the placeholders
   * @returns {Object[]}     one plain object per row
   */
  function runAll(sql, params = []) {
    const paged = query.runSuiteQLPaged({ query: sql, params, pageSize: 5000 });
    const rows = [];
    paged.pageRanges.forEach((range) => {
      const page = paged.fetch({ index: range.index });
      page.data.asMappedResults().forEach((row) => rows.push(row));
    });
    return rows;
  }

  // Example: open vendor bills by subsidiary
  // const bills = runAll(
  //   'SELECT id, tranid, foreigntotal FROM transaction WHERE type = ? AND status = ? AND subsidiary = ?',
  //   ['VendBill', 'A', 2]
  // );

  return { runAll };
});

RESTlet skeleton with validation and a consistent error envelope

A RESTlet that always answers in the same shape. Callers get a predictable JSON body for success and failure, and every error is logged with the request it came from.

restlet-skeleton.js
/**
 * @NApiVersion 2.1
 * @NScriptType Restlet
 */
define(['N/record', 'N/log'], (record, log) => {

  const ok    = (data)          => ({ success: true,  data });
  const fail  = (code, message) => ({ success: false, error: { code, message } });

  function requireFields(body, fields) {
    const missing = fields.filter((f) => body[f] === undefined || body[f] === '');
    if (missing.length) throw { code: 'MISSING_FIELDS', message: `Missing: ${missing.join(', ')}` };
  }

  function post(body) {
    try {
      requireFields(body, ['entity', 'tranDate', 'items']);

      const so = record.create({ type: record.Type.SALES_ORDER, isDynamic: true });
      so.setValue({ fieldId: 'entity',   value: body.entity });
      so.setText({  fieldId: 'trandate', text:  body.tranDate });

      body.items.forEach((line) => {
        so.selectNewLine({ sublistId: 'item' });
        so.setCurrentSublistValue({ sublistId: 'item', fieldId: 'item',     value: line.item });
        so.setCurrentSublistValue({ sublistId: 'item', fieldId: 'quantity', value: line.quantity });
        so.commitLine({ sublistId: 'item' });
      });

      return ok({ id: so.save() });
    } catch (e) {
      log.error({ title: 'RESTlet POST failed', details: { body, error: e } });
      return fail(e.code || e.name || 'UNEXPECTED', e.message || String(e));
    }
  }

  return { post };
});

Map/Reduce that respects governance and summarises errors

Map/Reduce gives you governance for free, but failures are easy to lose. This skeleton isolates one record per map call, lets reduce retry safely, and writes a single readable error summary at the end.

mapreduce-skeleton.js
/**
 * @NApiVersion 2.1
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', 'N/log', 'N/runtime'], (search, record, log, runtime) => {

  function getInputData() {
    // Return a search; each result becomes one map() call.
    return search.create({
      type: 'vendorbill',
      filters: [['mainline', 'is', 'T'], 'AND', ['custbody_sync_status', 'anyof', 'pending']],
      columns: ['internalid']
    });
  }

  function map(ctx) {
    const row = JSON.parse(ctx.value);
    // Key by record id so reduce receives exactly one record at a time.
    ctx.write({ key: row.id, value: row.id });
  }

  function reduce(ctx) {
    const id = Number(ctx.key);
    try {
      record.submitFields({
        type: 'vendorbill', id,
        values: { custbody_sync_status: 'done' },
        options: { enableSourcing: false, ignoreMandatoryFields: true }
      });
    } catch (e) {
      // Throwing marks the key as failed and keeps the rest of the batch going.
      throw new Error(`${id}: ${e.message}`);
    }
  }

  function summarize(summary) {
    const errors = [];
    summary.mapSummary.errors.iterator().each((k, e)  => { errors.push(`map ${k}: ${JSON.parse(e).message}`);  return true; });
    summary.reduceSummary.errors.iterator().each((k, e) => { errors.push(`reduce ${k}: ${JSON.parse(e).message}`); return true; });

    log.audit({
      title: `${runtime.getCurrentScript().id} finished`,
      details: { seconds: summary.seconds, usage: summary.usage, yields: summary.yields, failed: errors.length }
    });
    if (errors.length) log.error({ title: 'Failed keys', details: errors.join('\n') });
  }

  return { getInputData, map, reduce, summarize };
});

Saved search: all results without the 1,000 row limit

search.run().getRange() stops at 1,000 rows. runPaged() walks the whole result set and this helper turns each result into a simple object keyed by column label.

search-all-results.js
/**
 * @NApiVersion 2.1
 * Load a saved search (or an ad-hoc one) and return every result.
 */
define(['N/search'], (search) => {

  function toObject(result) {
    const obj = { id: result.id };
    result.columns.forEach((col) => {
      const key = col.label || col.name;
      obj[key] = result.getText(col) || result.getValue(col);
    });
    return obj;
  }

  /**
   * @param {search.Search|string} s  a Search object or a saved search id like 'customsearch_open_pos'
   */
  function getAll(s) {
    const srch = typeof s === 'string' ? search.load({ id: s }) : s;
    const paged = srch.runPaged({ pageSize: 1000 });
    const out = [];
    paged.pageRanges.forEach((range) => {
      paged.fetch({ index: range.index }).data.forEach((r) => out.push(toObject(r)));
    });
    return out;
  }

  return { getAll };
});