add custom condition to required decorator

This commit is contained in:
Dan Percic 2021-08-06 18:26:04 +03:00
parent ad03f28a49
commit ce112e57c0
4 changed files with 12 additions and 7 deletions

View File

@ -1,8 +1,8 @@
import { KeysOf } from '../../utils/types/utility-types';
export interface TableColumnConfig<T extends object> {
readonly column?: KeysOf<T>;
readonly label: string;
readonly column?: KeysOf<T>;
readonly withSort?: boolean;
readonly class?: string;
readonly leftIcon?: string;

View File

@ -4,6 +4,9 @@ import { Required } from '../../utils/decorators/required.decorator';
import { KeysOf } from '../../utils/types/utility-types';
import { SortingService } from '../../sorting/sorting.service';
const ifNeedsSort = <T extends object>(thisArg: TableColumnNameComponent<T>) => thisArg.withSort;
const ifHasRightIcon = <T extends object>(thisArg: TableColumnNameComponent<T>) => !!thisArg.rightIcon;
@Component({
selector: 'iqser-table-column-name',
templateUrl: './table-column-name.component.html',
@ -14,12 +17,12 @@ export class TableColumnNameComponent<T extends object> {
readonly sortingOrders = SortingOrders;
@Input() @Required() label!: string;
@Input() column?: KeysOf<T>;
@Input() @Required(ifNeedsSort) column?: KeysOf<T>;
@Input() withSort = false;
@Input() class?: string;
@Input() leftIcon?: string;
@Input() rightIcon?: string;
@Input() rightIconTooltip?: string;
@Input() @Required(ifHasRightIcon) rightIconTooltip?: string;
constructor(@Optional() readonly sortingService: SortingService<T>) {}
}

View File

@ -1,8 +1,10 @@
export function Required(message?: string): PropertyDecorator {
export type Condition<T> = (thisArg: T) => boolean;
export function Required<T>(condition: Condition<T> = () => true): PropertyDecorator {
return function (target: Object, propertyKey: PropertyKey) {
Object.defineProperty(target, propertyKey, {
get() {
throw new Error(message || `Attribute ${String(propertyKey)} is required`);
if (condition(this)) throw new Error(`Attribute ${String(propertyKey)} is required`);
},
set(value) {
Object.defineProperty(this, propertyKey, {

View File

@ -3,7 +3,7 @@ export function capitalize(value: string): string {
}
export function humanize(value: string, lowercase = true): string {
const frags = (lowercase ? value.toLowerCase() : value).split(/[ \-_]+/);
const words = (lowercase ? value.toLowerCase() : value).split(/[ \-_]+/);
return frags.map(capitalize).join(' ');
return words.map(capitalize).join(' ');
}