1.0.15 • Published 3 years ago

@devslane/mobx-entity-manager v1.0.15

Weekly downloads
16
License
ISC
Repository
-
Last release
3 years ago

DevsLane Mobx Entity Store Manager


Mobx Entity Store Manager is born from the need for an extensible yet easy-to-use solution that helps you manage your entities in Mobx store without writing any boilerplate code.

Table of Content

Features

  • Easily manage your entities.
  • Lesser boilerplate code.
  • Comes with a Basic Entity Store setup .
  • Support for Single Entity, Entity List and Paginated Entity List.

Getting Started

Install Mobx Entity Manager by running this command

$ yarn add @devslane/mobx-entity-manager

To finalize the setup, boot Mobx Entity Manager in your entry file, such as App.ts or index.ts, by adding the following code -

App.ts

import { ContextStatic } from '@devslane/mobx-entity-manager';
import { BaseApiService } from 'services';

ContextStatic.boot({
            api: BaseApiService.getInstance(),
        });

...

Now you are ready to use Mobx Entity Manager seamlessly.

Usage

Mobx Entity Manager provides multiple Model Classes that can be extended to create models of your entities. These Model classes provide helper methods that can be used out of the box.

Mobx Entity Flow Diagram

Example -

A basic User Model extending EntityBaseModel class will look like -

UserModel.ts

import { EntityBaseModel, ModelList, ModelItem, ModelJson } from '@devslane/mobx-entity-manager';
import { UserStore } from 'stores';
import { observable } from 'mobx';
import { OccupationModel, EducationModel } from 'models';

class UserModel extends EntityBaseModel {
  static _store: UserStore;
  
  @observable
  name: string;
  
  @observable
  email: string;
  
  @observable
  occupations: ModelList<OccupationModel>;
  
  @observable
  education?: ModelItem<EducationModel>;
  
  deserialize_occupations(data: any[]) {
        this.occupations = new ModelList<OccupationModel>(OccupationModel);
        this.occupations.deserialize(data);
    }
  
  deserialize_education(data: ModelJson) {
        this.education = new ModelItem<EducationModel>(EducationModel);
        this.education.deserialize(data);
    }  
  
}

Documentation

  • ModelItem

    ModelItem wraps your single entity and provides you with all kind of basic methods.

Basic Usage -

import { ModelItem } from '@devslane/mobx-entity-manager';
import { UserModel } from 'models';

loggedInUser: ModelItem<UserModel> = new ModelItem<UserModel>(UserModel);

// Initializing value in ModelItem
await this.loggedInUser.load(`/your-api`, {
                param_key: param_value,
            });

// Accessing the entity stored in Model Item
console.log(loggedInUser.item);

// Accessing other helper properties
console.log('Is Item Loaded: ', loggedInUser.loaded);
console.log('Is Item Loading: ', loggedInUser.loading);

Methods available -

MethodsArgumentsReturn TypeDescription
setItem()item: TvoidSets the item received in argument in the ModelItem
deserialize()item: ModelJsonvoidSuperset of setItem that converts the JSON object into Model class itself.
load()url: string, params?: { [p: string]: any }, config?: { dataKey?: string; forceRefresh?: boolean; itemId?: number or string; useAuth?: boolean; }Promise<void>Loads your Model Item using response from a remote URL.
setLoading()loading: booleanvoidSets the loading property.
setLoaded()loaded: booleanvoidSets the loaded property.
setError()error: BaseError or nullvoidSets the error property.

Properties available -

PropertiesReturn TypeDescription
itemitem or undefinedIf set, fetches the wrapped item or undefined otherwise
loadedbooleanIndicates whether item has been loaded or not
loadingbooleanIndicates whether item is currently being loaded
errorbooleanIndicates whether some error has occurred while loading the item

load() and deserialize() methods handle loaded, loading and error internally.

  • ModelList

    ModelList wraps your list of entities and provides you with all kind of basic methods to manage your list.

Basic Usage -

import { ModelList } from '@devslane/mobx-entity-manager';

users: ModelList<UserModel> = new ModelList<UserModel>(UserModel);

// Initializing value in ModelList
this.users.load('/your-api');

// Accessing the entity stored in Model List
users.items.map((item) => console.log(item));

// Accessing other helper properties
console.log('Is List Loaded: ', users.loaded);
console.log('Is List Loading: ', users.loading);

Methods available -

MethodsArgumentsReturn TypeDescription
setItems()items: T[]voidClears the existing list and sets the items received in argument in the ModelList
appendItems()items: T[]voidAppends the items to already existing list
appendItem()item: TvoidAppends an item to the end of list
unshiftItem()item: TvoidAppends an item to the start of list
deserialize()items: ModelJson[]voidSuperset of setItems that converts the JSON objects into Model class itself.
clearItems()-voidClears all the existing items in the list and resets the loaded property.
setLoading()loading: booleanvoidSets the loading property.
setLoaded()loaded: booleanvoidSets the loaded property.
setError()error: BaseError or nullvoidSets the error property.
load()url: string, params?: { [p: string]: any }, config?: { dataKey?: string; forceRefresh?: boolean; itemId?: number or string; useAuth?: boolean; }Promise<void>Loads your Model List using response from a remote URL.

Properties available -

PropertiesReturn TypeDescription
itemsitem[] or undefinedIf set, fetches the wrapped list or undefined otherwise
loadedbooleanIndicates whether list has been loaded or not
loadingbooleanIndicates whether list is currently being loaded
errorbooleanIndicates whether some error has occurred while loading the list
  • PaginatedModelList

    PaginatedModelList extends basic ModelList with all its features and additional support for pagination. This proves to be really helpful when dealing with entities whose lists are not fully loaded initially. So you don't have to worry about maintaining variables like lastPage, totalPages etc.

Basic Usage -

import { PaginatedModelList } from '@devslane/mobx-entity-manager';

users: PaginatedModelList<UserModel> = new PaginatedModelList<UserModel>(UserModel);

// Load initial values in PaginatedModelList
this.users.load('/your-api');

// Load next page of entities
this.users.loadNext();

// Accessing the entity stored in List
users.items.map((item) => console.log(item));

// Accessing other helper properties
console.log('Is Last Page: ', users.isLastPage);
console.log('Total Pages: ', users.totalPages);

Methods available -

MethodsArgumentsReturn TypeDescription
loadNext()-Promise<void>Loads next page of entity items from the remote URL you passed in load method.
setIsLoadingNextPage()loading: booleanvoidSets the loading next page property.

Properties available -

PropertiesReturn TypeDescription
isLoadingNextPagebooleanIndicates whether next page is being loaded
totalPagesnumberReturns total number of pages of entity
perPagenumberReturns number of items per page
lastPagenumberReturns last page number
currentPagenumberReturns current page number
nextPagenumberReturns next page number
prevPagenumberReturns previous page number
firstPageUrlstringReturns url pointing to first page
lastPageUrlstringReturns url pointing to last page
isFirstPagebooleanReturns whether current page is the first page
isLastPagebooleanReturns whether current page is the last page
isLoadedAllbooleanReturns whether all the pages have been loaded

Since PaginatedModelList extends ModelList so all methods and properties of the latter are available in the former.

loadNext() method handles isLoadingNextPage internally.

  • EntityBaseModel

    Extending EntityBaseModel class in your Entity Model classes provides you with multiple ready to use properties without writing repetitive properties in each of your model.

Basic Usage -

class UserModel extends ChildStore<UserModel> {
    @observable loggedInUser?: UserModel;
    
    setLoggedInUser(data: ModelJson) {
        this.loggedInUser = UserModel.fromJson(data) as UserModel;
    }
    
    updateName(name: string) {
        this.loggedInUser.name = name;
    }
}

Example of a UserModel extending EntityBaseModel is shown above.

If you have ModelItem, or ModelList wrapped property inside Model Class then you will have to write a deserializer method for it.

  • Deserializer method name must follow the convention deserializer_{property_name}

Check example for deserializer method above.

Static Methods -

MethodsArgumentsReturn TypeDescription
fromJson()json: ModelJson, identifierKey?: stringEntityBaseModel or nullCreate and returns a new entry in store if not already present, otherwise update and returns the existing entry.
getOrNew()id: EntityIdentifierEntityBaseModelIt looks for the item in store based on id and creates a new entry in store if not found
get()id: EntityIdentifierEntityBaseModel or undefinedReturns the item from store with same id or undefined if not found

Regular Methods -

MethodsArgumentsReturn TypeDescription
updateFromJson()json: ModelJsonvoidUpdates the existing entry of item in the store.
1.0.15

3 years ago

1.0.14

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.11

4 years ago

1.0.10

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago