Skip to content

Latest commit

 

History

History
179 lines (120 loc) · 5.7 KB

Model.md

File metadata and controls

179 lines (120 loc) · 5.7 KB

Hord

A data storage and manipulation library for javascript

npm build coverage deps size vulnerabilities license


Model

Data models with automatic schema enforcement.


new Model(schema)

Once the Model is instantiated the schema can't be changed.

The Model class uses the on-change library (uses the Proxy API) to detect changes and enforce the schema.

Param Type
schema Schema

Example

import { Model } from 'hord';

const Person = new Model({
 first: String,
 last: String,
 age: 'integer',
 hobbies: {
     type: Array,
     content: String
 }
});

const johnDoe = Person.apply({
 first: 'John',
 last: 'Doe',
 age: 21
});

johnDoe.hobbies = ['programming', 10];

console.log(johnDoe);
// => { first: 'John', last: 'Doe', age: 21, hobbies: ['programming'] }


model.schema ⇒ Schema     🔒 Read only

Get the schema for this model.


model.apply(object) ⇒ object

Apply this model to an object.

Param Type Description
object object The object to apply this model to.


model.extend(model) ⇒ Model

Returns a new Model with a new extended Schema. Retains the errorLevel from the calling Model.

Param Type Description
model Model, Schema, Schema.SchemaDefinition The model to superimpose on this one.


model.errorLevel(errorLevel) ⇒ MODEL_ERROR_LEVEL     🔗 Chainable

How to handle errors on this model. Overrides Model.defaultErrorLevel()

Default: MODEL_ERROR_LEVEL.UNSET

Param Type
errorLevel MODEL_ERROR_LEVEL


model.onChange(callback) ⇒ Queue     🔗 Chainable

Called when a change is observed on an object applied to this model

See: Queue

Param Type Description
callback function Provides four args: path, value, previous value, and the name of the method that produced the change. Context is the model that changed.


model.onError(callback) ⇒ Queue     🔗 Chainable

Called when an error is returned from Schema validation

See: Queue

Param Type Description
callback function Provides one arg: an array of errors. Context is the model that changed.


Model.defaultErrorLevel(errorLevel) ⇒ MODEL_ERROR_LEVEL

How to handle errors on all models

Default: MODEL_ERROR_LEVEL.WARN

Param Type
errorLevel MODEL_ERROR_LEVEL


MODEL_ERROR_LEVEL : Enum

How to handle Schema validation errors in models.

Properties

Name Description
UNSET Errors are ignored.
WARN Console.warn
ERROR Console.error
THROW Throw an exception