Utilities
Global helpers and the U object: identifiers, object copies, paths, files, queues and text functions.
Total.js puts a set of helpers into the global scope. You do not require() them: they are available in controllers, schemas, definitions, modules and plugins. Most of them live in the object U (the file utils.js), the rest are global functions and objects. The full list is in the reference of Utilities.
var id = UID();
var ext = U.getExtension('Photo.JPG'); // 'jpg'
var copy = CLONE(model, { password: 1 });U, Utils and utils are the same object. Total is an alias of the framework instance F.
Identifiers
| Function | Result |
|---|---|
UID([type]) | A short time-based ID, for example 24j0y001xn51d |
UID16([type]) | The same with the time in base 16 |
GUID() | A UUID-like string xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
GUID(length) | Random lowercase letters and digits |
U.random_text(length) | Random letters and digits |
U.random_number(length) | Random digits as a string, never starting with 0 |
U.random([max], [min]) | A random integer (0 to 100000 by default) |
UID() is the usual choice for primary keys: it is short, unique within the running instance and it sorts by time. The type argument keeps a separate counter for each collection. CONF.default_uid set to r switches UID() to random IDs.
function create(model) {
model.id = UID('orders');
model.dtcreated = NOW;
return model;
}When an ID goes to the client and comes back in a URL, sign it with U.encrypt_uid(). U.decrypt_uid() returns null when somebody changed it. The value is not hidden, only protected.
var link = '/invoice/' + U.encrypt_uid(invoice.id) + '/';
// later
var id = U.decrypt_uid(this.params.id);Objects
| Function | What it does |
|---|---|
CLONE(obj, [skip]) | A deep copy; skip is { key: 1 } of keys to leave out |
COPY(source, [target]) | Copies all keys of source to target |
U.copy(source, [target]) | Copies only keys that target already has |
U.extend(target, source, [rewrite]) | Adds keys; with rewrite = false it fills only missing values |
U.reduce(obj, keys, [reverse]) | Keeps the listed keys, or removes them with reverse |
U.get(obj, path) / U.set(obj, path, value) | Read and write by a path like address.city |
U.trim(obj, [clean]) | Trims all strings; clean turns empty strings into undefined |
DIFFARR(key, db, form) | Compares two lists: { add, upd, rem } |
U.copy() is useful when you update a stored record from a form: only the fields the record already has are written.
var user = { name: '', email: '' };
U.copy(this.body, user); // extra keys of the body are ignored
var output = U.reduce(user, ['password'], true);DIFFARR() tells you what to insert, update and remove when a user saves an edited list.
var diff = DIFFARR('id', stored, model.items);
diff.add.forEach(insert);
diff.upd.forEach(function(item) {
update(item.db, item.form);
});
diff.rem.forEach(remove);Shared state
The framework creates empty global objects for your app: MAIN, REPO and FUNC. It never writes into them, so they are a safe place for shared data and helpers. TEMP is cleared regularly (every 10 minutes by default). NOW is a Date the framework refreshes about every minute; use it for timestamps where a precision of a minute is enough. EMPTYOBJECT and EMPTYARRAY are frozen defaults and NOOP is an empty callback.
// definitions/init.js
FUNC.price = function(value) {
return value.format(2) + ' EUR';
};
MAIN.countries = ['SK', 'CZ', 'AT'];Loaded modules are in MODS, and MODULE(name) returns one of them or null.
Paths and files
PATH returns paths to the directories of the app. Each directory comes from its CONF.directory_* option. PATH.temp(), PATH.databases() and PATH.logs() also create the directory when it is missing.
PATH.root('data/countries.json');
PATH.public('img/logo.png');
PATH.temp('export.csv');
PATH.databases('settings.json');
PATH.mkdir(PATH.databases('uploads/2021/'), true);U.combine() joins paths relative to the root of the app, U.join() joins parts of a URL path, and U.path() adds a trailing slash. U.getExtension(), U.getName() and U.getContentType() work with file names. U.setContentType() adds a new extension to the table the framework uses for static files.
U.ls() lists a directory with all its subdirectories. Without a callback it returns a Promise. The unified argument gives paths with / on Windows. U.ls2() adds the fs.Stats of each file.
U.ls(PATH.public(), function(files, directories) {
console.log(files);
}, /\.(jpg|png)$/);
var response = await U.ls2(PATH.temp());
response.files.forEach(function(file) {
console.log(file.filename, file.stats.size);
});LOGGER(name, ...) appends a line with a date to /logs/{name}.log.
LOGGER('payments', 'order', order.id, 'paid', order.price);Asynchronous helpers
U.queue(name, max, fn) runs at most max functions of one queue at the same time; each function calls next() when it is done. WAIT(validator, callback, [timeout], [interval]) checks a condition until it is true or the time runs out. PROMISIFY(fn, [a], [b], [c]) turns a function with a callback(err, response) into a Promise.
files.forEach(function(filename) {
U.queue('resize', 2, function(next) {
resize(filename, next);
});
});
var text = await PROMISIFY(require('fs').readFile, PATH.root('readme.md'), 'utf8');Text and data
| Function | Result |
|---|---|
U.encode(value) / U.decode(value) | HTML entities |
U.btoa(value) / U.atob(value) | Base64 |
HASH(value, [type]) | A numeric hash, or md5, sha1, sha256, sha512, crc32 |
U.keywords(text) | Unique words for a search index |
U.parseXML(xml) | A flat object with dot paths as keys |
U.parseInt(value, [def]) | A number from any value (also U.parseFloat, U.parseBoolean) |
QUERIFY([url], obj) | A URL with a query string |
U.sortcomparer('price_desc,name') | A compare function for Array.sort() |
U.distance(lat1, lon1, lat2, lon2) | Kilometres between two GPS points |
U.minify_css/js/html(value) | Code minified by the built-in compilers |
var keywords = U.keywords(product.name + ' ' + product.description).join(' ');
products.sort(U.sortcomparer('price_desc,name'));
var url = QUERIFY('/api/products/', { page: 2, q: 'book' });The methods of String, Number, Date and Array that the framework adds are described on their own page.