UNPKG

@calf/angular

Version:

Angular module of Calf framework.

118 lines (117 loc) 3.79 kB
// Data import { FilterType } from "./filter-type.enum"; /** Filter item */ export class FilterItem { /** * Constructor * @param type * @param value * @param service */ constructor(type, value, service) { // Assign type this.type = type; // Assign value this.value = value; // Assign service this.service = service; } /** * Check if value is set */ isSet() { return (typeof this.value !== 'undefined') && this.value !== null && this.value !== '' && (!(this.value instanceof Array) || this.value.length !== 0); } /** * Convert filter item value * to param value */ toParam() { // Get param value switch (this.type) { // Serializable case FilterType.SERIALIZABLE: return this.value._id; // Array of serializable case FilterType.ARRAY_OF_SERIALIZABLE: return this.value.map((v) => v._id); // Date case FilterType.DATE: return this.value.toISOString(); // Boolean case FilterType.BOOLEAN: return this.value ? 1 : 0; // All other case FilterType.NUMBER: case FilterType.TEXT: case FilterType.ARRAY: default: return this.value; } } /** * Get value from param * @param value */ fromParam(params) { // Get value from param value switch (this.type) { // Serializable case FilterType.SERIALIZABLE: this.value = { _id: params.pop() }; break; // Array of serializable case FilterType.ARRAY_OF_SERIALIZABLE: this.value = params.map((v) => { return { _id: v }; }); break; // Number case FilterType.NUMBER: this.value = parseFloat(params.pop()); break; // Date case FilterType.DATE: this.value = new Date(params.pop()); break; case FilterType.BOOLEAN: this.value = !!Number(params.pop()); break; // Array case FilterType.ARRAY: this.value = params; break; // All other case FilterType.TEXT: default: this.value = params.pop(); } // We might also need to load serializable if (this.type === FilterType.SERIALIZABLE && this.service) { // Get serializable this.service.get(this.value) .then((validation) => { // Check validation if (!validation.isValid) { return; } // Assign data Object.assign(this.value, validation.data); }); } // Also we might need to load serializable in case of array of them if (this.type === FilterType.ARRAY_OF_SERIALIZABLE && this.service) { // Get each serializable Promise.all(this.value.map((serializable) => this.service.get(serializable))) .then((validations) => { // Process validations this.value = validations // Only valid .filter((validation) => validation.isValid) // Get data .map((validation) => validation.data); }); } } }