re-modelr
Simple-to-use javascript object-relational mapping store
Install
$ npm i @ngyv/re-modelr --save
Quick Start
With MobX ( Demo )
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);
API
BaseModel
Base class for model instances created based on data fetched from server.
_attributes
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
_cache
Sets _data
based on json during instantiation
Parameters
-
data
Object
Returns undefined
_deserialize
Deserializes json data fetched with camelcase keys
Parameters
-
modelJson
Object
Returns Object _data
_serialize
Serializes _data
with snakecase keys
Returns Object
_validateAttributes
Validates the attributes against that described in _attributes
Parameters
-
modelJson
Object
Returns Boolean
isDirty
Returns Boolean indicator if the model is dirty
changedAttributes
Returns Object difference object between _data from server and model properties
save
Saves the changes made to the model instance to server
Returns Object promise by domain store following the api call
softDelete
Marks isDeleted
status as true so that the change is propogated when save
is called
Returns undefined
delete
Deletes the model via domain store
Returns Object promise by domain store
discardChanges
Discards changes made to model based on _data
Returns undefined
DomainStore
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]
_generateApi
Generates api object that is called based on default endpoints
Parameters
_createRecord
Creates a model object but doesn't push to store
Parameters
Returns Object new record instance created
_normalizeModels
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
_pushEntry
Adds model to store entries
Parameters
-
modelJson
Object
Returns Object model entry
_deleteEntry
Deletes entry by id from store entries
Parameters
entriesArray
Getter function that returns array representation of entries
Returns Array
all
Returns cached entries
Parameters
-
toJson
boolean determines if the object return is serialized (format fetched by server)
Returns Object
find
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
findOrShowEntry
Checks cached entries
before dispatching network request
Parameters
-
id
(number | string) of model or entry -
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 function -
errorCallback
Function will override default error callback function -
finallyCallback
Function will override default callback function after api call
Returns Promise
allOrListEntries
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 function -
errorCallback
Function will override default error callback function -
finallyCallback
Function will override default callback function after api call
Returns Promise
listEntries
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 function -
errorCallback
Function will override default error callback function -
finallyCallback
Function will override default callback function after api call
Returns Promise containing the models
showEntry
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 function -
errorCallback
Function will override default error callback function -
finallyCallback
Function will override default callback function after api call
Returns Promise containing the model
createRecord
Creates the model object but doesn't persist it until the model.save()
Parameters
-
modelJson
Object
Returns Model
createEntry
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 function -
errorCallback
Function will override default error callback function -
finallyCallback
Function will override default callback function after api call
Returns Promise containing newly created model
updateEntry
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 function -
errorCallback
Function will override default error callback function -
finallyCallback
Function will override default callback function after api call
Returns Promise containing updated model
updateEntries
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 function -
errorCallback
Function will override default error callback function
Returns Promise containing the updated models
deleteEntry
Makes delete network request
Parameters
-
modelId
(String | Number) -
$1
Object (optional, default{}
)$1.errorCallback
$1.finallyCallback
-
errorCallback
Function will override default error callback function -
finallyCallback
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 around -
options
Object (optional, default{basePath:'/api',modelName:modelClass.name.toLowerCase()}
)
type
Takes in model descriptors and returns a flat object
Parameters
-
typeName
string String representation of prop types -
options
(optional, default{}
) -
required
boolean Indicates validation -
default
(number | boolean | string | array | object) Fallback value
Returns object
validate
Parameters
-
attribute
any To be validated on -
type
object To be validated against and is generated bytype
function (optional, default{}
)
Returns boolean
License
MIT © Yvonne Ng