axp-ts/src/requests/find-filter.ts

74 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-09-14 18:19:36 +03:00
import type { TPagination } from './pagination'
import { z } from 'zod'
import { isEqual } from '../utils'
import { Pagination, paginationQuerySchema } from './pagination'
import { bFieldsSchema, cFieldsSchema, fieldSchema } from '../forms'
export const querySchema = cFieldsSchema
.pick({ q: true })
.extend(paginationQuerySchema.shape)
.extend({
sort: fieldSchema(bFieldsSchema.string.min(1).max(64), {
label: 'Сортировка'
})
})
2023-10-05 17:01:45 +03:00
.partial()
.describe('Параметры базового запроса')
2023-09-14 18:19:36 +03:00
export type TQuery = z.infer<typeof querySchema>
/**
* Объект для преобразования фильтра в URL.
*/
export type TFindFilter<T extends TQuery> = {
obj?: Omit<T, 'page' | 'limit' | 'sort'>
pagination?: TPagination
sort?: string
}
export class FindFilter<T extends TQuery> implements TFindFilter<T> {
obj?: Omit<T, 'page' | 'limit' | 'sort'>
pagination?: TPagination
sort?: string
constructor(query?: T) {
2023-10-05 17:01:45 +03:00
let queryCopy: T = Object.assign({}, query)
2023-09-14 18:19:36 +03:00
// Pagination.
this.setPagination(queryCopy)
2023-10-05 17:01:45 +03:00
if (this.pagination) {
// Delete pagination props.
const paginationKeys = Object.keys(this.pagination) as [keyof T]
for (const key of paginationKeys) {
if (queryCopy[key]) delete queryCopy[key]
}
2023-09-14 18:19:36 +03:00
}
// Sort.
if (queryCopy.sort) {
this.sort = queryCopy.sort
2023-10-05 17:01:45 +03:00
queryCopy.sort = undefined
2023-09-14 18:19:36 +03:00
}
// Obj.
this.obj = queryCopy
}
2023-10-05 17:01:45 +03:00
setPagination(pagination?: Partial<TPagination>) {
2023-09-14 18:19:36 +03:00
this.pagination = new Pagination(pagination).toObject()
}
toObject(): TFindFilter<T> {
return {
obj: this.obj,
pagination: this.pagination,
sort: this.sort
}
}
isEqual(filters: TFindFilter<T>[]) {
return isEqual([this, ...filters])
}
}