@ngyv/re-modelr v1.0.4
re-modelr
Simple-to-use javascript object-relational mapping store
Install
$ npm i @ngyv/re-modelr --saveQuick 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:
dataObject
Returns undefined
_deserialize
Deserializes json data fetched with camelcase keys
Parameters:
modelJsonObject
Returns Object _data
_serialize
Serializes _data with snakecase keys
Returns Object
_validateAttributes
Validates the attributes against that described in _attributes
Parameters:
modelJsonObject
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:
modelsArray containing each model json data
Returns Object normalized models object for easy model retrieval
_pushEntry
Adds model to store entries
Parameters:
modelJsonObject
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:
toJsonboolean determines if the object return is serialized (format fetched by server)
Returns Object
find
Returns cached entry based on id
Parameters:
id(number | string)toJsonboolean 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 entryparamsObject additional search params for api call$2Object (optional, default{})$2.successCallback$2.errorCallback$2.finallyCallback
successCallbackFunction will override default success callback functionerrorCallbackFunction will override default error callback functionfinallyCallbackFunction will override default callback function after api call
Returns Promise
allOrListEntries
Checks if any entries are available before making network request
Parameters:
toJsonboolean determines if the object return is serialized (format fetched by server)paramsObject additional search params for api call$2Object (optional, default{})$2.successCallback$2.errorCallback$2.finallyCallback
successCallbackFunction will override default success callback functionerrorCallbackFunction will override default error callback functionfinallyCallbackFunction will override default callback function after api call
Returns Promise
listEntries
Makes network request to get all.
Parameters:
paramsObject additional search params for api call$1Object (optional, default{})$1.successCallback$1.errorCallback$1.finallyCallback
successCallbackFunction will override default success callback functionerrorCallbackFunction will override default error callback functionfinallyCallbackFunction 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)paramsObject additional search params for api call$2Object (optional, default{})$2.successCallback$2.errorCallback$2.finallyCallback
successCallbackFunction will override default success callback functionerrorCallbackFunction will override default error callback functionfinallyCallbackFunction 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:
modelJsonObject
Returns Model
createEntry
Makes a post network request
Parameters:
modelEntryJson(Model | Object)$1Object (optional, default{})$1.successCallback$1.errorCallback$1.finallyCallback
successCallbackFunction will override default success callback functionerrorCallbackFunction will override default error callback functionfinallyCallbackFunction 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:
modelEntryModel$1Object (optional, default{})$1.successCallback$1.errorCallback$1.finallyCallback
successCallbackFunction will override default success callback functionerrorCallbackFunction will override default error callback functionfinallyCallbackFunction 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>)$1Object (optional, default{})$1.successCallback$1.errorCallback
successCallbackFunction will override default success callback functionerrorCallbackFunction will override default error callback function
Returns Promise containing the updated models
deleteEntry
Makes delete network request
Parameters:
modelId(String | Number)$1Object (optional, default{})$1.errorCallback$1.finallyCallback
errorCallbackFunction will override default error callback functionfinallyCallbackFunction will override default callback function after api call
Creates a domain store to handle api calls to server
Parameters:
ModelClassObject Model class reference to wrap data aroundoptionsObject (optional, default{basePath:'/api',modelName:modelClass.name.toLowerCase()})
type
Takes in model descriptors and returns a flat object
Parameters:
typeNamestring String representation of prop typesoptions(optional, default{})requiredboolean Indicates validationdefault(number | boolean | string | array | object) Fallback value
Returns object
validate
Parameters:
attributeany To be validated ontypeobject To be validated against and is generated bytypefunction (optional, default{})
Returns boolean
License
MIT © Yvonne Ng
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago