All files / src/storage memory-datasource.ts

100% Statements 125/125
100% Branches 42/42
100% Functions 27/27
100% Lines 112/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 30521x 21x 21x 21x 21x           21x   1x           44x         44x                   44x         44x         44x           44x             44x 44x 44x 44x 44x       38x 38x 38x   38x 38x                 76x 76x 76x 76x 76x 76x 76x 76x 76x   76x 76x             4x 4x 4x 4x             76x 24x   76x                 24x 24x 24x 24x 24x 24x   24x             76x 76x 76x 14x 14x 14x   76x                 1x 1x                   4x 2x 1x 1x   1x                   5x 3x 2x   2x 1x     2x   1x                   150x                                     154x 72x 72x 4x   68x   82x 9x 3x   6x     73x 73x   73x 39x 39x     73x 36x   37x       78x 78x 16x     62x 16x 16x     46x 32x 32x 32x 32x     14x             57x 27x                 27x 60x   41x   37x 37x 32x 32x     27x       1x 1x       2x                
import { Config } from '../config';
import { dayjs } from '../dayjs';
import { I18n } from '../i18n/i18n';
import { IDictionary, Utils } from '../utils';
import { Datasource } from './datasource';
import { IMemoryDatasource } from './interfaces';
 
/**
 * Base class to perform CRUD methods using data stored in memory.
 */
export class MemoryDatasource extends Datasource implements IMemoryDatasource {
	public getLoadedData(): IDictionary[] {
		return this.allData;
	}
 
	/**
	 * All memory data
	 */
	public allData: IDictionary<any>[] = [];
 
	/**
	 * Translate columns
	 */
	public translate: boolean | string[] = false;
 
	/**
	 *  Function to overwrite the sort function
	 */
	public sortFunction?: (value1: any, value2: any, columnName: string) => boolean;
 
	/**
	 *  Params to control sorting
	 */
	public sortParams: IDictionary<any> = {};
 
	/**
	 * Filtered data
	 */
	protected filteredData: IDictionary<any>[] = [];
 
	/**
	 * Order types
	 */
	protected orderTypes: IDictionary<number> = {
		asc: 1,
		desc: -1,
		same: 0,
	};
 
	protected originalValues: IDictionary<any>[] = [];
 
	/**
	 * Creates a new Memory Datasource
	 * @param datasource Datasource structure
	 */
	constructor(datasource: IMemoryDatasource) {
		super(datasource);
		this.translate = this.getInitValue('translate', datasource.translate, this.translate);
		this.sortFunction = this.getInitValue('sortFunction', datasource.sortFunction, this.sortFunction);
		this.sortParams = this.getInitValue('sortParams', datasource.sortParams, this.sortParams);
		this.originalValues = [];
	}
 
	public initialize(): void {
		super.initialize();
		this.allData = this.data;
		this.translateData();
 
		this.get();
		if (this.translate) I18n.registerChangeListener(this.translateData.bind(this));
	}
 
	/**
	 * Retrieves a promise with data value ordered by order value
	 * and filtered by search, filter, limit and page
	 * @returns Promise with data value
	 */
	public async get(): Promise<any> {
		this.updateInternalProperties();
		this.updateFilteredData();
		this.sortFilteredData();
		const end = this.loadAll ? this.allData.length : this.limit * this.page;
		const start = this.loadAll ? 0 : end - this.limit;
		this.data = this.filteredData.slice(start, end);
		this.total = this.filteredData.length;
		this.currentRow = {};
		const data = await this.updateSelectedPage();
 
		await this.runGetCallbacks();
		return data;
	}
 
	/**
	 * Update datasource data
	 */
	public async updateData(data: IDictionary<any>[]): Promise<any> {
		this.allData = data;
		this.originalValues = [];
		this.translateData();
		return this.get();
	}
 
	/**
	 * Updates filtered data
	 */
	protected updateFilteredData() {
		this.filteredData = Object.keys(this.filter).length
			? this.allData.filter((row) => this.getRowByFilter(row))
			: Array.from(this.allData);
		this.filteredData = this.search ? this.filteredData.filter((row) => this.getRowBySearch(row)) : this.filteredData;
	}
 
	/**
	 * Checks if row passed on current filter
	 * @param row Each datasource row
	 * @returns Row passed
	 */
	protected getRowByFilter(row: IDictionary<any>) {
		let filtered = false;
		Object.keys(this.filter).every((key) => {
			const hasValue = row[key] && row[key].toString().indexOf(this.filter[key]) !== -1;
			const isNull = !row[key] && this.filter[key] === 'NULL';
			filtered = hasValue || isNull;
			return filtered;
		});
		return filtered;
	}
 
	/**
	 * Reorder filtered data based on order value
	 */
	protected sortFilteredData() {
		const columns: string[] = [];
		const order: string[] = [];
		this.order.forEach((value) => {
			const splitted = value.split('.');
			columns.push(splitted[0]);
			order.push(splitted[1]);
		});
		this.sortArray(this.filteredData, columns, order);
	}
 
	/**
	 * Adds a new row to datasource
	 * @param row Row to create
	 * @returns Promise with added row
	 */
	public async post(row: IDictionary<any>): Promise<any> {
		this.allData = this.allData.concat(row);
		return row;
	}
 
	/**
	 * Updates a datasource row using unique key
	 * @param row Row to update
	 * @returns Promise with updated row
	 * @throws Will throw if row doesn't exists
	 */
	public async put(row: IDictionary<any>): Promise<any> {
		const index = this.allData.findIndex((dataRow) => dataRow[this.uniqueKey] === row[this.uniqueKey]);
		if (index !== -1) {
			this.allData[index] = row;
			return row;
		}
		throw new Error(`Row with id ${row[this.uniqueKey]} not found`);
	}
 
	/**
	 * Deletes a datasource row using unique key
	 * @param row Row to delete
	 * @returns Promise with deleted row
	 * @throws Will throw if row doesn't exists
	 */
	public async delete(row: IDictionary<any>): Promise<any> {
		const index = this.allData.findIndex((dataRow) => dataRow[this.uniqueKey] === row[this.uniqueKey]);
		if (index !== -1) {
			this.allData.splice(index, 1);
 
			if (this.currentRow[this.uniqueKey] === row[this.uniqueKey]) {
				this.currentRow = {};
			}
 
			return row;
		}
		return Promise.reject(new Error(`Row with id ${row[this.uniqueKey]} not found`));
	}
 
	/**
	 * Sorts the data collection using the same principles of ordering in databases
	 * @param array Data collection
	 * @param columns Columns used to oreder the collection
	 * @param types Order orientation. All values must be asc or desc
	 */
	protected sortArray(collection: IDictionary<any>[], columns: string[], types: string[]) {
		collection.sort((row, nextRow) => this.sort(row, nextRow, columns, types));
	}
 
	/**
	 * Custom sort for collections
	 * @param row Collection row
	 * @param nextRow Next row from collection
	 * @param columns Columns used to oreder the collection
	 * @param types Order orientation. All values must be asc or desc
	 * @param index Columns and types position
	 * @returns Row's position
	 */
	protected sort(
		row: IDictionary<any>,
		nextRow: IDictionary<any>,
		columns: string[],
		types: string[],
		index = 0,
	): number {
		if (row[columns[index]] === nextRow[columns[index]]) {
			const nextIndex = index + 1;
			if (Object.prototype.hasOwnProperty.call(columns, nextIndex)) {
				return this.sort(row, nextRow, columns, types, nextIndex);
			}
			return this.orderTypes.same;
		}
		if (this.sortFunction instanceof Function) {
			if (this.sortFunction(row[columns[index]], nextRow[columns[index]], columns[index])) {
				return this.orderTypes[types[index]];
			}
			return this.orderTypes[types[index]] * -1;
		}
 
		let rowValue = row[columns[index]];
		let nextRowValue = nextRow[columns[index]];
 
		if (this.sortParams[columns[index]]) {
			rowValue = this.convertSortValue(rowValue, this.sortParams[columns[index]]);
			nextRowValue = this.convertSortValue(nextRowValue, this.sortParams[columns[index]]);
		}
 
		if (rowValue > nextRowValue) {
			return this.orderTypes[types[index]];
		}
		return this.orderTypes[types[index]] * -1;
	}
 
	protected convertSortValue(value: any, sortParam: any) {
		const columnType = typeof sortParam === 'string' ? sortParam : sortParam.type;
		if (columnType === 'number') {
			return parseFloat(value);
		}
 
		if (columnType === 'date') {
			const dateFormat = sortParam.dateFormat || Config.dateFormat;
			return dayjs(value.toString(), dateFormat).toDate();
		}
 
		if (columnType === 'string') {
			let sortValue = value.toString();
			if (sortParam.caseInsensitive) sortValue = sortValue.toLowerCase();
			if (sortParam.normalize) sortValue = Utils.normalize(sortValue);
			return sortValue;
		}
 
		return value;
	}
 
	/**
	 * Translate all data.
	 */
	protected translateData() {
		if (!this.translate) return;
		this.allData = this.allData.map((row, index) => this.translateRow(row, index));
	}
 
	/**
	 * Translate row
	 * @param row Row to translate
	 * @param index Row index
	 */
	protected translateRow(row: IDictionary<any>, index: number) {
		Object.keys(row).forEach((key) => {
			if (key === this.uniqueKey) return;
 
			if (typeof row[key] !== 'string') return;
 
			if (!this.originalValues[index]) this.originalValues[index] = {};
			if (this.translate === true || (this.translate as string[]).indexOf(key) !== -1) {
				if (!this.originalValues[index][key]) this.originalValues[index][key] = row[key];
				row[key] = I18n.translate(this.originalValues[index][key]);
			}
		});
		return row;
	}
 
	public destroy() {
		I18n.unregisterChangeListener(this.translateData);
		this.originalValues = [];
	}
 
	public clone(): IMemoryDatasource {
		return {
			...super.clone(),
			data: this.allData,
			translate: this.translate,
			type: 'memory',
		};
	}
}