@trademe/ensure - utility decorators for Angular applications.
@Singleton
:
This decorator can be applied to @Injectable
classes to ensure that they are instantiated only once. This is useful for stateful services that belong at the root of the application.
Example:
import { Singleton } from '@trademe/ensure';
@Singleton
@Injectable
export class MyStatefulService { }
let instance = new MyStatefulService();
let another = new MyStatefulService();
@Value
:
This decorator can be applied to properties on a class to ensure that they conform to rules when they are set. The rules also act as a mechanism for casting values from HTML attributes, which makes for nicer component APIs.
Example:
import { Value } from '@trademe/ensure';
export class MyClass {
@Value(isOne) mustBeOne: number;
@Value([isString, isLengthFive]) verySpecificString: string;
}
export function isOne (value: any) {
if (value === 1) {
return value;
}
throw new Error();
}
export function isString (value: string) {
if (typeof value === 'string') {
return value;
}
throw new Error();
}
export function isLengthFive (value: string) {
if (value.length === 5) {
return value;
}
throw new Error();
}
Built in rules:
isNotNull
Ensure that a value is not null
. isNotNull
is special in that it acts when getting the value, not setting it.
Example:
import { isNotNull } from '@trademe/ensure';
export class MyClass {
@Value(isNotNull) mustNotBeNull: boolean;
}
let instance = new MyClass();
instance.mustNotBeNull = true;
instance.mustNotBeNull = null;
console.log(instance.mustNotBeNull):
isBool
Ensure that a value is boolean. Also casts from 'true'
or ''
to true
and 'false'
to false
.
Example:
import { isBool } from '@trademe/ensure';
export class MyClass {
@Value(isBool) mustBeBoolean: boolean;
}
let instance = new MyClass();
instance.mustBeBoolean = true;
instance.mustBeBoolean = 'hello';
instance.mustBeBoolean = 'false';
console.log(instance.mustBeBoolean)
isBool
is particularly useful for simplifying component APIs when combined with @Input
.
Example:
import { isBool } from '@trademe/ensure';
@Component({ ... })
export class MyComponent {
@Input() @Value(isBool) mustBeBoolean: boolean;
}
<my-component
mustBeBoolean>
</my-component>
isEnum
Ensure that a value is a valid enum value.
Example:
import { isEnum } from '@trademe/ensure';
export enum MyEnum {
foo,
bar
}
export class MyClass {
@Value(isEnum<typeof MyEnum>(MyEnum)) mustBeEnum: MyEnum;
}
let instance = new MyClass();
instance.mustBeEnum = 'foo';
console.log(instance.mustBeEnum);
instance.mustBeEnum = 'bar';
console.log(instance.mustBeEnum);
instance.mustBeEnum = 'baz';
isNumber
Ensure that a value is a valid number.
Example:
import { isNumber } from '@trademe/ensure';
export class MyClass {
@Value(isNumber) mustBeNumber: number;
}
let instance = new MyClass();
instance.mustBeNumber = 5;
console.log(instance.mustBeNumber);
instance.mustBeNumber = '1.33';
console.log(instance.mustBeNumber);
instance.mustBeNumber = 'baz';