From 17f05dd9e214fc5ac99980a74a994f2be127da30 Mon Sep 17 00:00:00 2001 From: AntoXa PRO Date: Fri, 6 Oct 2023 12:43:46 +0300 Subject: [PATCH] fix FindFilter --- package.json | 2 +- src/requests/find-filter.ts | 41 +++++++++++++++++++++++++++++++++---- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index a91799c..e7bdae9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "axp-ts", - "version": "1.11.0", + "version": "1.11.1", "description": "TypeScript helper library", "author": "AntoXa PRO ", "homepage": "https://antoxahub.ru/antoxa/axp-ts", diff --git a/src/requests/find-filter.ts b/src/requests/find-filter.ts index 3e53517..d156f03 100644 --- a/src/requests/find-filter.ts +++ b/src/requests/find-filter.ts @@ -22,8 +22,8 @@ export type TQuery = z.infer * Класс для работы с запросами (для удобства). */ export type TFindFilter = { - obj: Omit - pagination: TPaginationQuery + obj?: Omit + pagination?: TPaginationQuery sort?: string } @@ -31,8 +31,8 @@ export type TFindFilter = { * Класс для работы с запросами (для удобства). */ export class FindFilter implements TFindFilter { - obj: Omit - pagination: TPaginationQuery + obj?: Omit + pagination?: TPaginationQuery sort?: string constructor(query?: T) { @@ -74,4 +74,37 @@ export class FindFilter implements TFindFilter { isEqual(filters: TFindFilter[]) { return isEqual([this, ...filters]) } + + toString(filter?: TFindFilter, opt?: { base?: string }): string { + let url = opt?.base?.replace(/[?]$/, '') || '' + + if (filter) { + const query: string[] = [] + + // Params and Pagination. + for (const [key, val] of Object.entries({ + ...filter.obj, + ...filter.pagination + })) { + if (val) { + const keyEncode = encodeURIComponent(key) + const valEncode = encodeURIComponent(val) + query.push(keyEncode + '=' + valEncode) + } + } + + // Sort. + if (filter.sort) { + try { + query.push('sort=' + encodeURIComponent(filter.sort)) + } catch (e) {} + } + + if (query.length) { + url += '?' + query.join('&') + } + } + + return url + } }