typeline
v0.0.1
Published
TypeLine is a simple ES6 class utility inspired by React.PropTypes, developed to handle inline and hairy type of validation/sanitization for any type of value, it was written to be used on both browser and server.
Downloads
9
Maintainers
Readme
TypeLine is a simple ES6 class utility to be used on both browser and server, it was developed to handle inline and hairy type of validation/sanitization for any value. Inspired by React.PropTypes.
TypeLine can cross validate the front and back-end of your apps with the same methods. With TypeLine you have validation and sanitization methods for specific types of value, even custom types.
This is still under development, behaviors of this module can change.
how it works
import TypeLine from 'typeline';
let body = {
firstName: " John",
middleName: null,
lastName: " Doe ",
email: " [email protected]",
birthday: undefined,
password: "123456",
metadata: {
timezone: "America/Sao_Paulo",
extraKey: "something not to be parsed"
}
};
TypeLine.Object.map({
firstName: TypeLine.String.isRequired().trim().notEmpty().isAlpha(),
middlename: TypeLine.toString().trim().isAlpha(),
lastName: TypeLine.String.isRequired().trim().notEmpty().isAlpha(),
email: TypeLine.String.isRequired().trim().notEmpty().isEmail(),
password: TypeLine.String.isRequired().trim().notEmpty().isPassword(),
birthday: TypeLine.oneOf(
TypeLine.String.trim().toDate(),
TypeLine.Date
), //if no isRequired mehtod than is optional
password: TypeLine.String.isRequired().trim().notEmpty().isPassword(),
registeredAt: TypeLine.Date.setDefault(() => new Date()).toString(),
metadata: {
timezone: TypeLine.String
}
}).exec(value).then((bodySafe) => {
console.log("value is now", bodySafe)
}, (errors) => {
console.log("errors", errors);
})
------- stdout -------
Value is now {
firstName: "John",
middleName: "",
lastName: "Doe",
email: "[email protected]",
password: "Abc@123-456",
registeredAt: "2015-10-25 04:15:14",
metadata: {
timezone: "America/Sao_Paulo"
}
}
How to extend existing types
import TypeLine, {TypeLineError} from 'typeline';
TypeLineError.extend({
NumberOutOfRange(min, max) {
return this.i18n `The value is out of range(${min}, ${max})`;
}
})
TypeLine.extend('Number', {
range(min, max) {
if(typeof min !== 'number')
throw new Error("The min argument must be a number");
if(typeof max !== 'number')
throw new Error("The max argument must be a number");
if(max > min)
throw new Error("The max argument should be bigger than min");
return (value) => {
if(value < min)
throw new TypeLineError.NumberOutOfRange(min, max);
}
},
ceil() {
return (value) => {
return Math.round(value);
}
}
})
How to extend new custom types
import TypeLine, {TypeLineError} from 'typeline';
const __DATA__ = Symbol('__DATA__')
, __VALID__ = Symbol('__VALID__')
, __PARSING__ = Symbol('__PARSING__');
class Model {
static schema = {};
constructor(data) {
this[__DATA__] = new Map();
this[__VALID__] = false;
this[__PARSING__] = 0;
if(data) {
if(typeof data !== 'object' || Array.isArray(data))
throw new Error("The first argument must be an object");
Object.getOwnPropertyNames(data).forEach((propName) => {
this[__DATA__].set(propName, data[propName]);
})
}
}
async parse() {
const {schema} = this.constructor;
this[__PARSING__]++;
try {
let data = await TypeLine.Object.map(schema).exec(this[__DATA__]);
} catch(err) {
this[__PARSING__]--;
throw err;
}
this[__PARSING__]--;
this[__DATA__] = new Map();
this[__VALID__] = true;
Object.getOwnPropertyNames(data).forEach((propName) => {
this[__DATA__].set(propName, data[propName]);
Object.defineProperty(this, propName, () => {
enumerable: true,
configurable: true,
get() {
return this[__DATA__].get(propName)
},
async set(value) {
this[__PARSING__]++;
try {
value = await schema[propName].exec(value);
} catch(err) {
this[__PARSING__]--;
throw err;
}
this[__PARSING__]--;
this[__DATA__].set(propName, value);
}
});
})
}
isParsing() {
return this[__PARSING__].length > 0;
}
isValid() {
return this[__VALID__];
}
}
class User extends Model {
static schema = {
firstName: TypeLine.String.isRequired().trim().notEmpty().isAlpha(),
middlename: TypeLine.toString().trim().isAlpha(),
lastName: TypeLine.String.isRequired().trim().notEmpty().isAlpha(),
email: TypeLine.String.isRequired().trim().notEmpty().isEmail(),
};
}
TypeLineError.extend({
UserDataNotAnObject() {
return this.i18n `User data is not an object`;
}
})
TypeLine.extend('User', {
isType() {
return (value) => {
if(value instanceof User)
return value;
throw new TypeLineError.InvalidType;
}
},
toType() {
return (value) => {
if(value instanceof User)
return value;
if(typeof value !== 'object' || Array.isArray(value))
throw new TypeLineError.UserDataNotAnObject;
return new User(value);
}
},
parse() {
return async (value) => {
await value.parse();
return value;
}
}
})