All files / src/utils/datasource-searcher datasource-searcher.ts

100% Statements 21/21
100% Branches 3/3
100% Functions 8/8
100% Lines 18/18

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 5395x     95x 35x 30x       1x         1x           3x 6x 3x 3x                   35x             35x 35x 35x   35x   35x 7x   33x      
import { Datasource, DatasourceFactory, IDatasource, IDictionary } from '@zeedhi/core';
import { IDatasourceSearcher, SearchParam } from './interfaces';
 
export class DatasourceSearcher implements IDatasourceSearcher {
	private dsSearch = {
		SEARCH: (value: any, searchIn: string) => ({
			searchIn: [searchIn],
			search: String(value),
		}),
		FILTER: (value: any, searchIn: string) => ({
			filter: {
				[searchIn]: value,
			},
		}),
		FIND: (value: any, searchIn: string) => ({
			find: {
				[searchIn]: value,
			},
		}),
		DYNAMIC_FILTER: (value: unknown, search_in: string) => {
			const arrayValue = Array.isArray(value) ? value : Array.of(value);
			const filter = arrayValue.map((item) => ({ operation: 'EQUALS', relation: 'OR', value: item }));
			const dynamicFilter = { [search_in]: filter };
			return { dynamicFilter };
		},
	};
 
	async search(
		datasource: Datasource,
		searchValue: string | number | (string | number)[],
		searchIn: string,
		searchParam: SearchParam,
	): Promise<IDictionary[]> {
		const config: IDatasource = {
			...datasource.clone(),
			...this.dsSearch[searchParam](searchValue, searchIn),
			lazyLoad: true,
			loadAll: Array.isArray(searchValue),
		};
 
		const cloneDatasource: Datasource = DatasourceFactory.factory(config);
		await cloneDatasource.initialize();
		const items: IDictionary[] = await cloneDatasource.get();
 
		cloneDatasource.destroy();
 
		if (Array.isArray(searchValue)) {
			return items.filter((item) => searchValue.includes(item[searchIn]));
		}
		return items.filter((row) => row[searchIn] === searchValue);
	}
}