Simple-to-use javascript object-relational mapping store
$ npm i @ngyv/re-modelr --save
Default endpoints for DomainStore:
/*
* GET /modelName List of entries [ listEntries ]
* GET /modelName/:id Show entry details [ showEntry ]
* POST /modelName Create new entry [ createEntry ]
* PUT /modelName/:id Update entry [ updateEntry ]
* DELETE /modelName/:id Delete entry [ deleteEntry ]
*/
import { type, BaseModel, DomainStore } from '@ngyv/re-modelr';
class User extends BaseModel {
_attributes() {
const defaultAttributes = super._attributes();
const userAttributes = {
name: type('string', { required: true, acceptedTypes: [propTypes.undefined, propTypes.null, propTypes.emptyString] }),
favouriteFood: type('array'),
};
return Object.assign({}, defaultAttributes, userAttributes);
}
}
const userStore = new DomainStore(User, { basePath: '/ajax'} ); // basePath = '/api' by default
// `id`, `createdAt`, and `updatedAt` are default attributes defined in the `BaseModel` class
let singer = new User(userStore, {
id: 1,
name: 'Yuna',
createdAt: new Date(),
updatedAt: new Date(),
favouriteFood: ['nasi lemak'],
});
singer.set('name', 'Zee Avi');
singer.changedAttributes();
//=> { name: ['Yuna', 'Zee Avi'] }
singer.isDirty();
//=> true
singer.discardChanges();
singer.get('name');
//=> 'Yuna'
singer.set('name', 'Siti');
singer.save();
singer.softDelete();
singer.save();
userStore.listEntries();
//=> { 1: UserModel, 2: UserModel, length: 2 }
userStore.showEntry(1);
//=> UserModel
userStore.entries[1];
//=> { id: 1, name: 'Yuna', status: { isSaving: false, isNew: false, isDeleted: false }, _store: DomainStore, _data:{}, ... }
userStore.entriesArray;
//=> [UserModel, UserModel]
let newUser = userStore.createRecord({ name: 'Hari' });
//=> UserModel
// newUser.status.isNew == true
newUser.save();
// newUser.status.isNew == false
userStore.deleteEntry(3);
Base class for model instances created based on data fetched from server.
Declares the model attributes which will be validated
Examples
return {
name: type('string', { required: true, acceptedTypes: [propTypes.null, propTypes.emptyString] })
}
Returns Object containing attributes of model and the type
Sets _data
based on json during instantiation
Parameters:
data
Object
Returns undefined
Deserializes json data fetched with camelcase keys
Parameters:
modelJson
Object
Returns Object _data
Serializes _data
with snakecase keys
Returns Object
Validates the attributes against that described in _attributes
Parameters:
modelJson
Object
Returns Boolean
Returns Boolean indicator if the model is dirty
Returns Object difference object between _data from server and model properties
Saves the changes made to the model instance to server
Returns Object promise by domain store following the api call
Marks isDeleted
status as true so that the change is propogated when save
is called
Returns undefined
Deletes the model via domain store
Returns Object promise by domain store
Discards changes made to model based on _data
Returns undefined
Endpoints are dependant on the model name that extends from this.
Default endpoints:
GET /modelName List of entries
GET /modelName/:id Show entry details
POST /modelName Create new entry
PUT /modelName/:id Update entry
DELETE /modelName/:id Delete entry
Required params:
{Object} ModelClass - an alias class wrapper
Optional params in options:
{String} [basePath='/api']
{String} [modelName=ModelClass.name]
Generates api object that is called based on default endpoints
Parameters:
Creates a model object but doesn't push to store
Parameters:
Returns Object new record instance created
Convert an array of json and into an object of models with id as key
Parameters:
models
Array containing each model json data
Returns Object normalized models object for easy model retrieval
Adds model to store entries
Parameters:
modelJson
Object
Returns Object model entry
Deletes entry by id from store entries
Parameters:
Getter function that returns array representation of entries
Returns Array
Returns cached entries
Parameters:
toJson
boolean determines if the object return is serialized (format fetched by server)
Returns Object
Returns cached entry based on id
Parameters:
id
(number | string)toJson
boolean determines if the object return is serialized (format fetched by server)
Returns Object
Checks cached entries
before dispatching network request
Parameters:
id
(number | string) of model or entryparams
Object additional search params for api call$2
Object (optional, default{}
)$2.successCallback
$2.errorCallback
$2.finallyCallback
successCallback
Function will override default success callback functionerrorCallback
Function will override default error callback functionfinallyCallback
Function will override default callback function after api call
Returns Promise
Checks if any entries are available before making network request
Parameters:
toJson
boolean determines if the object return is serialized (format fetched by server)params
Object additional search params for api call$2
Object (optional, default{}
)$2.successCallback
$2.errorCallback
$2.finallyCallback
successCallback
Function will override default success callback functionerrorCallback
Function will override default error callback functionfinallyCallback
Function will override default callback function after api call
Returns Promise
Makes network request to get all.
Parameters:
params
Object additional search params for api call$1
Object (optional, default{}
)$1.successCallback
$1.errorCallback
$1.finallyCallback
successCallback
Function will override default success callback functionerrorCallback
Function will override default error callback functionfinallyCallback
Function will override default callback function after api call
Returns Promise containing the models
Makes network request to get model by id
Parameters:
id
(String | Number)params
Object additional search params for api call$2
Object (optional, default{}
)$2.successCallback
$2.errorCallback
$2.finallyCallback
successCallback
Function will override default success callback functionerrorCallback
Function will override default error callback functionfinallyCallback
Function will override default callback function after api call
Returns Promise containing the model
Creates the model object but doesn't persist it until the model.save()
Parameters:
modelJson
Object
Returns Model
Makes a post network request
Parameters:
modelEntryJson
(Model | Object)$1
Object (optional, default{}
)$1.successCallback
$1.errorCallback
$1.finallyCallback
successCallback
Function will override default success callback functionerrorCallback
Function will override default error callback functionfinallyCallback
Function will override default callback function after api call
Returns Promise containing newly created model
Makes a put network request to update an existing model
Parameters:
modelEntry
Model$1
Object (optional, default{}
)$1.successCallback
$1.errorCallback
$1.finallyCallback
successCallback
Function will override default success callback functionerrorCallback
Function will override default error callback functionfinallyCallback
Function will override default callback function after api call
Returns Promise containing updated model
Makes multiple put network requests to update models
Parameters:
modelEntriesObjectArray
(Array<Model> | Object<Model>)$1
Object (optional, default{}
)$1.successCallback
$1.errorCallback
successCallback
Function will override default success callback functionerrorCallback
Function will override default error callback function
Returns Promise containing the updated models
Makes delete network request
Parameters:
modelId
(String | Number)$1
Object (optional, default{}
)$1.errorCallback
$1.finallyCallback
errorCallback
Function will override default error callback functionfinallyCallback
Function will override default callback function after api call
Creates a domain store to handle api calls to server
Parameters:
ModelClass
Object Model class reference to wrap data aroundoptions
Object (optional, default{basePath:'/api',modelName:modelClass.name.toLowerCase()}
)
Takes in model descriptors and returns a flat object
Parameters:
typeName
string String representation of prop typesoptions
(optional, default{}
)required
boolean Indicates validationdefault
(number | boolean | string | array | object) Fallback value
Returns object
Parameters:
attribute
any To be validated ontype
object To be validated against and is generated bytype
function (optional, default{}
)
Returns boolean
MIT © Yvonne Ng