Skip to content
This page View Markdown Open in ChatGPT Open in Claude

Utility classes

A utility class is TypeScript shared by all your code : helpers, validations, pricing rules, clients of external services, interfaces. Write it once on the Utility Classes page (Utility → Utility Classes) and import it anywhere with utils/<Name>.

Create one

Click +, give a path (a folder to group them) and a name. The name is unique, starts with a capital letter, and is what you import.

utils/Calculator
class Calculator {
    add(x: number, y: number) {
        return x + y;
    }
    multi(x: number, y: number) {
        return x * y;
    }
}
let temp = new Calculator();
export = temp;
  • The file exports an instance (export = temp), so the importer calls the methods directly.
  • The class can hold state : a connection opened in a method stays for the life of the sandbox.

Use one

1
2
3
4
5
6
7
import * as T from 'types';
import * as calc from 'utils/Calculator';

async function main(g: T.IAMGlobal) {
    return { sum: calc.add(3, 6), product: calc.multi(3, 6) };
}
module.exports = main;
  • Works in custom APIs, pre and post hooks, event listeners, schedulers, migration scripts, process initializers, WebSocket connect code and test cases.
  • Press Ctrl+Space after utils/ in the editor to see every class.
  • A method which needs API Maker takes g as a parameter : Pricing.total(g, order).

Interfaces

A utility class can export interfaces and types, for every piece of code to share :

utils/Inf
1
2
3
4
5
6
7
8
9
class Inf {
}
let temp = new Inf();
export = temp;
export interface IUserP {
    firstName: string;
    lastName: string;
    phone: number;
}
1
2
3
4
5
6
7
8
import * as T from 'types';
import * as inf from 'utils/Inf';

async function main(g: T.IAMGlobal) {
    const data: inf.IUserP = { firstName: 'John', lastName: 'Doe', phone: 123456789 };
    return data;
}
module.exports = main;

Versions

A utility class has versions and one active version. The code which imports it always gets the active one, at once, without a restart. Keep the old version until the new one has proven itself, and switch back in one click.

Testing

A test case imports the class the way custom APIs do and calls its methods, with mocks for the g.sys calls it makes and coverage of its lines.

Good to know

  • Utility classes are files in Git under src/Utility classes/ and deploy with a pull.
  • A utility class runs where its importer runs : in the sandbox, or on the native process for a native custom API.
  • A new account comes with a sample utility class to read.