Skip to content

Latest commit

 

History

History
119 lines (88 loc) · 3.42 KB

README.md

File metadata and controls

119 lines (88 loc) · 3.42 KB

NativeModels

npm pack age

Version Build Status

Maintainability Test Coverage Greenkeeper badge

Weekly Downloads Monthly Downloads Yearly Downloads

Issues Pull Requests

Dependencies Dev Dependencies

Native Models provides a way to map objects in a clean and typed way. The main goal is to ensure runtime type checking and consistent models for APIs.

Getting Started

import { createModel } from 'nativemodels';
import { array, boolean, computed, date, int, object, string } from 'nativemodels/datatypes';

const photoSchema = {
	ext: string(),
	url: string().required(),
};

const contactSchema = {
	email: string(),
	phone: string(),
	url: string(),
};

const userSchema = {
	accountID: int().nullable(),
	contact: object(contactSchema),
	created: date(),
	firstName: string().required(),
	fullName: computed((record) => `${record.firstName} ${record.lastName}`),
	isAdmin: boolean().nullable(),
	lastName: string().required(),
	photos: array(object(photoSchema)),
	typeID: int().default(2),
};

const userModel = createModel(userSchema);

const johnSmith = userModel({
	contact: {
		email: 'j.smith@example.com',
	},
	firstName: 'John',
	lastName: 'Smith',
	photos: [
		{
			ext: '.jpg',
			url: 'https://example.com/img.jpg',
		},
	],
});
// => { firstName: 'John', lastName: 'Smith', fullName: 'John Smith', ...}

const userRecords = [
	{
		firstName: 'John',
		lastName: 'Smith',
	},
	{
		firstName: 'Jane',
		lastName: 'Doe',
	},
];
const users = userRecords.map(userModel);
// => [{ firstName: 'John', lastName: 'Smith', fullName: 'John Smith', ...}]

const janeDoe = userModel({
	...johnSmith,
	firstName: 'Jane',
	lastName: 'Doe',
});
// => { firstName: 'Jane', lastName: 'Doe', fullName: 'Jane Doe', ...}

Datatype API

Datatype methods that can be chained when defining schema.

datatypes.default(defaultValue)

Sets a default value if no value is set

datatypes.nullable()

Allows the value set to be null (useful for database models)

datatypes.required()

Forces the value to be required. Is ignored if default value is set

Datatypes

  • array
  • boolean
  • computed
  • date
  • float
  • int
  • object
  • string

Extending Datatypes

datatypes.validate(value, name)

If value is valid, returns true, else throws error. Name is key on object;

datatypes.parse(value)

Parses the value being set. Used to extend base datatype