1.0.0 • Published 1 year ago

@mathquis/modelx v1.0.0

Weekly downloads
54
License
ISC
Repository
-
Last release
1 year ago

ModelX

An API connected model and collection library using MobX v6

Installation

npm install -D @mathquis/modelx

Models

Create a model

A model is a set of attributes

import {Model, Collection} from '@mathquis/modelx';

// Create a model class
class User extends Model {
	static get path() {
		return '/app/{app.id}/users/{?id}';
	}
	// You can assign default values to the mode attributes
	static get defaults() {
		id: 0
		lastName: '',
		firstName: '',
		email: '',
		tags: []
	}
}

const user = new User({
	id: 1,
	lastName: 'Doe',
	firstName: 'John',
	email: 'john@doe.com',
	address: {
		country: 'FR'
	},
	tags: ['a', 'b']
});

Accessing a model attributes

You can access a model attributes using the get() method (using MobX observable magic) or accessing it directly on attributes (directly as a Javascript object).

console.log(user.get('lastName')); // Outputs: "Doe"
console.log(user.get('unknownProperty')); // Output undefined
console.log(user.get('unknownProperty', 'defaultValue')); // Outputs: "defaultValue"
console.log(user.get(['address', 'country']); // Outputs: "FR"

Setting model attributes

To set a model attributes, use the set() method.

// Set a single property
user.set('lastName', 'Smith');
console.log(user.get('lastName')); // Outputs: "Smith"

user.set(['address', 'country'], 'IT');
console.log(user.get('address.country')); // Outputs: "IT"

// Set multiple properties
user.set({
	lastName: 'Jack',
	firstName: 'Burton'
});

// Handling arrays
user.set('tags', ['c']);

// user.get('tags') will return ['c']

// Merge arrays
user.merge('tags', ['d']);

// user.get('tags') will return ['c', 'd']

// Handling objects
user.set('address', {street: 12});
// OR
user.set({address: {street: 12}});

// user.get('address') will return {street: 12} because the address attribute has been replaced

// Merging objects
user.merge('address', {street: 12}); // Shortcut for: user.set('address', {street: 12}, {merge: true});
// OR
user.merge({address: {street: 12}}); // Shortcut for: user.set({address: {street: 12}}, {merge: true});

// user.get('address') will return {country: 'FR', street: 12}

Checking if a model has an attribute

To check if a model has a specific attribute, use the has()method.

user.has('email'); // Returns: true
user.has('unknown'); // Returns: false

Test an attribute

To check if an attribute contains a specific value you can use the is() method.

user.is('email', 'jack@burton.com'); // Returns: true

Validating attributes

You can validate a model's attributes at runtime using the validator static getter. It must return a validation function that returns either true or throw an Error. If the attributes do not pass the validation, a ModelError is thrown.

function validationFn(attributes: object): boolean {
	if ( isNumber(attributes.id) ) return true;
	throw new Error('Missing id attribute');
}

class ValidatedModel extends Model {
	static get validator(): (attributes: object) => boolean {
		return validationFn;
	}
}

const model = new ValidatedModel(); // Throws ModelError

const model = new ValidatedModel({id: 1}); // This is fine

model.set('id', 'NotFine'); // Throws ModelError

Properties

A model has some usefull properties like isNew (tells if the model has a non null id attribute), isDirty (tells if the model's attributes has been modified since the last sync), isDestroyed (tells if the model has been destroyed).

Collections

Collections are list of models. They provides lots methods to work on the models. Here are the supported methods: set, add, remove, clear, getById, removeById, shift, unshift, pop, push, indexOf, map, reduce, forEach, pluck, countBy, filter, every, some, find, findById, at, first, last, shuffle, distinct, sortBy, reverse, clone

Create a collection

To create a collection, we need to define the type of model that the collection will accept. A collection accepts some options: comparator to automatically sort the models and order to define the sorting order (asc or desc).

import {Collection} from 'modelx';

const user1 = new User({id: 1, category: 'food'});
const user2 = new User({id: 2, category: 'movie'});
const user3 = new User({id: 3, category: 'food'});

const list = new Collection( User, [user1, user2, user3], {comparator: 'id', order: 'asc'});

list.forEach((model) => {
	console.log(model.id);
});
// Outputs:
// 1
// 2
// 3

list.pluck('category'); // Returns: ['food', 'movie', 'food']

Virtual collection

Virtual collection are a subset of a collection. A collection and its virtual collections automatically stay in sync.

const virtualList = list.createVirtualCollection((model) => model.is('category', 'food'));

virtualList.forEach((model) => {
	console.log(model.id);
});
// Outputs:
// 1
// 3

You can unsubscribe the virtual collection from its source with its cancelSubscription() method.

virtualList.cancelSubscription();

Once unsubscribed, the virtual collection will not be kept in sync with the source collection but its models will still be shared between both collections.

Extending a collection

You can create more advanced collections by extending the default Collection.

import {Collection} from 'modelx';

export default class PagedCollection extends Collection {
	public offset: number = 0;
	public limit: number = 10;
	public total: number = 0;
	protected prepareListOptions(options: object) {
		options = super.prepareListOptions(options);
		options.offset = this.offset = options.offset || this.offset;
		options.limit = this.limit = options.limit || this.limit;
		return options;
	}
	protected onListSuccess(results){
		this.total = results.total;
		return super.onListSuccess(results);
	}
}

Connectors

Connectors allow models and collections to interact with an API (http, levelDB, localStorage, etc.). ModelX does not come with predefined connectors. You will have to write it yourself. All models and collection have isLoading and isLoaded properties reacting to connector requests.

Creating a connector

A connector implements a list of specific methods: list() (get a list of models), fetch() (get a model), save() (persist a model), destroy() (unpersist a model). Here is an example of a simple HTTP JSON connector.

import {Model, Collection, Connector, ConnectorResult, ConnectorResults} from 'modelx';
import Axios,{AxiosInstance} from 'axios';

export default class JsonApiConnector extends Connector {
	private client: AxiosInstance;

	initialize() {
		this.client = Axios.create({
			headers: {
				'Accept': 'application/json'
			},
			responseType: 'json'
		});
	}

	// Collection methods
	list(collection: Collection, options: object = {}): Promise<ConnectorResults> {
		this.onConnect();
		return this.client( collection.path, {
			...options,
			method: 'get'
		}).then((response) => {
			this.onDisconnect();
			return new ConnectorResults(response.data, response);
		})
		.catch((err) => {
			this.onDisconnect();
			throw err;
		});
	}

	// Model methods
	fetch(model: Model, options: object = {}): Promise<ConnectorResult> {
		this.onConnect();
		return this.client( model.path, {
			...options,
			method: 'get'
		}).then((response) => {
			this.onDisconnect();
			return new ConnectorResult(response.data, response);
		})
		.catch((err) => {
			this.onDisconnect();
			throw err;
		});
	}

	save(model: Model, attributes: object, options: object = {}): Promise<ConnectorResult> {
		this.onConnect();
		return this.client( model.path, model.untransform(), {
			...options,
			method: model.id ? 'put' : 'post',
			data: attributes
		}).then((response) => {
			this.onDisconnect();
			return new ConnectorResult(response.data, response);
		})
		.catch((err) => {
			this.onDisconnect();
			throw err;
		});
	}

	destroy(model: Model, options: object = {}): Promise<ConnectorResult> {
		this.onConnect();
		return this.client( model.path, {
			...options,
			method: 'delete'
		}).then((response) => {
			this.onDisconnect();
			return new ConnectorResult(model.attributes, response);
		})
		.catch((err) => {
			this.onDisconnect();
			throw err;
		});
	}
}

Once the connector is defined. We can create a model that will use it. Collections using this model will use the connector defined on the model.

import {Model, Collection} from 'modelx';
import {JsonApiConnector} from './jsonApiConnector';

const jsonApiClient = new JsonApiConnector();

class User extends Model {
	static get connector(): Connector {
		return jsonApiClient;
	}
}

// We create a new User model
const user = new User({
	id: 1,
	lastName: 'Doe',
	firstName: 'John'
});

user.save()
.then((model: Model) => {
	// My model is now created on the API
	return model.destroy();
})
.then((model: Model) => {
	// My model is now deleted from the API
});

const users = new Collection( User );

users.list().then((collection: Collection) => {
	console.log(collection.length);
});

Transforming model attributes

The attributes received from the connector can be manipulated using the model transform() method. The model will provide attributes returned by its untransform() method to the connector save() method.

class MappedUser extends User {
	protected transform(attributes: any): object {
		return {
			id: attributes._id,
			familyName: attributes.lastName,
			firstName: attributes.firstName
		};
	}
	protected untransform(): object {
		return {
			_id: this.id,
			lastName: this.attributes.familyName,
			firstName: this.attributes.firstName
		}
	}
}
1.0.0

1 year ago

0.5.10

2 years ago

0.5.9

2 years ago

0.5.8

3 years ago

0.5.7

3 years ago

0.5.6

3 years ago

0.5.5

3 years ago

0.5.4

4 years ago

0.5.3

4 years ago

0.4.7

4 years ago

0.5.0

4 years ago

0.5.2

4 years ago

0.5.1

4 years ago

0.4.6

4 years ago

0.4.5

5 years ago

0.4.4

5 years ago