Class: ModelCollectionBase

ModelCollectionBase()

new ModelCollectionBase()

Base class for Model and Collection. Should not be instantiated directly.

Methods

chunk(list, size) → {Array.<Array>}

Splits an array into chunks of a specified size.

Parameters:
Name Type Description
list Array

The array to be split into chunks.

size number

The size of each chunk.

Returns:

An array containing the chunks of the original array.

Type
Array.<Array>
Examples
// returns [[1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5], 2);
// returns [[1, 2, 3], [4, 5]]
chunk([1, 2, 3, 4, 5], 3);

delay(milliseconds)

Add an async execution delay

Parameters:
Name Type Description
milliseconds Number
Example
let userModel = new UserModel({id: "foo"})
await userModel.delay(5000); // delay execution by 5000ms
userModel.doSomething();

getObjectFromKeys(keys, orderByAlphaopt) → {object}

Returns an object with keys and values picked from class members. Will not return a key/value pair if value is undefined.

Parameters:
Name Type Attributes Default Description
keys Array.<String>

List of keys

orderByAlpha Boolean <optional>
true

Returned keys will be in alphabetical order unless this param is set to false

Returns:

Object with keys and values picked from class members.

Type
object
Example
let userModel = new UserModel({id: "foo", count: 4, email: "private@example.com"})
console.log(userModel.getObjectFromKeys(["id", "count"]) // {count: 4, id: "foo"}

setVarsFromData()

Will set class members from all keys and values of the data member.

Example
let model = new Model({id: "foo"});
model.setVarsFromData(); // model.id now set to "foo"

setVarsFromObject(object)

Will set class members from all keys and values of the object provided.

Parameters:
Name Type Description
object Object
Example
let userModel = new UserModel({id: "foo"})
userModel.setVarsFromObject({count: 1}); // userModel.count has now been set

validateBoolean(boolean, options)

Validate a boolean

Parameters:
Name Type Description
boolean Boolean

The boolean to be validated

options Object
Properties
Name Type Attributes Default Description
required Boolean <optional>
true
Throws:
Example
set hasUsername(boolean) {
  this.validateBoolean(boolean, {name: "hasUsername"})
  this.#hasUsername = boolean;
}

validateEmail(emailAddress, options)

Validate an email address

Parameters:
Name Type Description
emailAddress String

The email address to be validated

options Object
Properties
Name Type Attributes Default Description
required Boolean <optional>
true
Throws:
Example
set email(emailAddress) {
  this.validateEmail(emailAddress, {name: "email"})
  this.#email = emailAddress;
}

validateInstanceOf(object, constructor, options)

Validate an object is an instance of another object

Parameters:
Name Type Description
object Object

The object to be validated

constructor Object

The constructor to be validated against

options Object
Properties
Name Type Attributes Default Description
required Boolean <optional>
true
Throws:
Example
set userModel(userModel) {
  this.validateInstanceOf(userModel, UserModel, {name: "userModel"})
  this.#userModel = userModel;
}

validateNumber(number, options)

Validate a number

Parameters:
Name Type Description
number Number

The number to be validated

options Object
Properties
Name Type Attributes Default Description
required Boolean <optional>
true

If true, will check the string for undefined, null, and empty

minValue Number <optional>
Number.MIN_SAFE_INTEGER

If set will check the number for a minimum value.

maxValue Number <optional>
Number.MAX_SAFE_INTEGER

If set will check the number for a maximum value.

name String <optional>

Set to have better error messaging, ie error.message = "UserModel id is required."

Throws:
Example
set count(number) {
  this.validateNumber(number, {name: "count"})
  this.#count = number;
}

validateRequiredProperties(keys, checkForNullopt)

Validate that certain properties are set on the model. By default will check for undefined and null.

Parameters:
Name Type Attributes Default Description
keys Array.<String>

List of keys

checkForNull Boolean <optional>
true

If set to false will only check for undefined (not null)

Throws:
Example
let userModel = new UserModel({id: "foo"})
userModel.setVarsFromData();
userModel.validateRequiredProperties(["id", "count"]); // will throw an
error because 'count' is undefined.

validateString(string, options)

Validate a string

Parameters:
Name Type Description
string String

The string to be validated

options Object
Properties
Name Type Attributes Default Description
required Boolean <optional>
true

If true, will check the string for undefined, null, and empty

minLength Number <optional>

If set will check the string for a minimum length of characters.

maxLength Number <optional>
100000

If set will check the string for a maximum length of characters.

name String <optional>

Set to have better error messaging, ie error.message = "UserModel id is required."

Throws:
Example
set id(string) {
  this.validateString(string, {name: "id"})
  this.#id = string;
}

validateUrl(url, options)

Validate a url

Parameters:
Name Type Description
url String

The url to be validated

options Object
Properties
Name Type Attributes Default Description
required Boolean <optional>
true
protocols Array.<String> <optional>
[http:, https:]

By default a url must have an http: or https: protocol. Pass in a list of protocols to override this.

Throws:
Examples
set imageUrl(url) {
  this.validateUrl(url, {name: "imageUrl"})
  this.#imageUrl = url;
}
set ftpUrl(url) {
  this.validateUrl(url, {protocols: ["ftp:"]})
  this.#ftpUrl = url;
}

(async, static) acquireLock(nameopt, timeoutMsopt) → {Promise.<void>}

Acquires an asynchronous lock for a given name. If the lock is already held, waits in a queue until it becomes available, or rejects if a timeout is specified and exceeded.

Parameters:
Name Type Attributes Default Description
name string <optional>
'default'

The name of the lock to acquire. Locks are independent by name.

timeoutMs number | null <optional>
null

Optional timeout in milliseconds. If set, the lock attempt will fail after this duration.

Returns:

A promise that resolves when the lock is acquired or rejects on timeout.

Type
Promise.<void>

(static) clearCache(key)

Parameters:
Name Type Description
key string

The key of the cached value to clear.

(async, static) fetch(url, optionsopt) → {Promise.<Response>}

Fetches a resource with support for locking, GET-only caching, and request abortion. Only GET requests are eligible for caching. If a valid cached response exists, it is returned.

Parameters:
Name Type Attributes Default Description
url string

The URL to fetch.

options Object <optional>
{}

Fetch options, extended with custom fields.

Properties
Name Type Attributes Default Description
method string <optional>
'GET'

HTTP method (used for caching decisions).

lockTimeoutMs number <optional>

Optional lock timeout in milliseconds.

cacheMs number <optional>

Optional cache duration in milliseconds (only used for GET).

abortTimeoutMs number <optional>

Optional abort timeout in milliseconds.

Throws:

If the fetch is aborted or a lock times out.

Type
Error
Returns:

The network or cached response.

Type
Promise.<Response>

(static) getCache(key) → {*}

Parameters:
Name Type Description
key string

The key of the cached value to retrieve.

Returns:

The cached value if it exists and is still valid, otherwise null.

Type
*

(static) isLocked(nameopt) → {boolean}

Checks if a lock is currently held.

Parameters:
Name Type Attributes Default Description
name string <optional>
'default'

The name of the lock to check.

Returns:

True if the lock is held, false otherwise.

Type
boolean

(static) releaseLock(nameopt)

Releases a previously acquired lock for a given name. If there are queued waiters, the next one will be granted the lock.

Parameters:
Name Type Attributes Default Description
name string <optional>
'default'

The name of the lock to release.

(static) setCache(key, value, expiresInopt)

Parameters:
Name Type Attributes Default Description
key string

The key under which the value will be stored.

value *

The value to store in the cache.

expiresIn number <optional>
30000

Time in milliseconds before the cache entry expires. Defaults to 30 seconds.

(static) tryAcquireLock(nameopt) → {boolean}

Attempts to acquire the lock immediately. Returns true if the lock was acquired, false otherwise.

Parameters:
Name Type Attributes Default Description
name string <optional>
'default'

The name of the lock to try acquiring.

Returns:

True if the lock was acquired, false if it was already held.

Type
boolean