Compare commits

..

16 Commits

Author SHA1 Message Date
e6e67c2f47 fix version 2024-10-04 11:28:40 +03:00
9be52f1f9a update packages 2024-10-04 11:27:26 +03:00
cf5827bab1 update packages 2024-02-08 10:40:22 +03:00
36bdd23de4 update packages 2024-01-11 15:05:24 +03:00
146d14a1b8 find-filter delete char ? 2023-10-10 11:07:40 +03:00
acda0ff525 find filter helpers 2023-10-06 13:23:13 +03:00
17f05dd9e2 fix FindFilter 2023-10-06 12:43:46 +03:00
b1a4be4cf8 refactor pagination and FindFilter 2023-10-06 12:08:58 +03:00
31235b363c fix version 2023-10-05 17:03:38 +03:00
a68f3964e1 vite 2023-10-05 17:01:45 +03:00
5cc8f45f90 update version 2023-10-03 11:19:54 +03:00
55f9050dc9 notify 2023-10-03 11:18:30 +03:00
4e7d00db9b update zod 2023-10-03 11:18:08 +03:00
13e639fa8d select option type 2023-09-20 10:25:01 +03:00
20c21ea73d update ctrl 2023-09-19 22:43:11 +03:00
a6c220b499 merge obj 2023-09-19 20:42:13 +03:00
10 changed files with 173 additions and 60 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "axp-ts",
"version": "1.9.7",
"version": "1.13.0",
"description": "TypeScript helper library",
"author": "AntoXa PRO <info@antoxa.pro>",
"homepage": "https://antoxahub.ru/antoxa/axp-ts",
@@ -8,20 +8,36 @@
"type": "git",
"url": "https://antoxahub.ru/antoxa/axp-ts.git"
},
"main": "dist/index.js",
"module": "./dist/index.mjs",
"main": "./dist/index.umd.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"requier": "./dist/index.umd.js"
},
"./dist/*": "./dist/*",
"./src/*": "./src/*",
"./package.json": "./package.json",
"./tsconfig.json": "./tsconfig.json"
},
"files": [
"dist",
"tsconfig.ts"
"src",
"tsconfig.json"
],
"scripts": {
"build": "tsc",
"build": "vite build",
"prepare": "npm run build"
},
"dependencies": {
"zod": "^3.22.1"
"peerDependencies": {
"zod": "^3.23.8"
},
"devDependencies": {
"prettier": "^2.8.8",
"typescript": "^4.9.5"
"typescript": "^5.6.2",
"vite": "^4.5.5",
"vite-plugin-dts": "^3.9.1"
}
}

View File

@@ -12,12 +12,17 @@ import {
} from './helpers'
import { FormSchemaCtrl } from './ctrl'
export type TUiFieldSelectOption = {
text: string
value: string
}
/**
* Create field schema.
*/
export const fieldSchema = <T extends ZodTypeAny>(
base: T,
args?: TFormSchemaCtrlArgs
args: TFormSchemaCtrlArgs = {}
) => base.describe(FormSchemaCtrl.toString(args, base.description))
/**

View File

@@ -3,7 +3,6 @@ import type { TNotificationItem } from '../notification'
import { FormSchemaCtrl } from './ctrl'
/**
* Интерфейс базовой формы для сущностей в БД.
*/
@@ -74,7 +73,7 @@ export class BaseFormModel<T extends object = {}> implements IFormModel<T> {
let items: TNotificationItem[] = []
for (const code in this._errors) {
const text = this._errors[code]
items.push({ code, text })
if (text) items.push({ code, text })
}
return items
}
@@ -95,6 +94,17 @@ export class BaseFormModel<T extends object = {}> implements IFormModel<T> {
}
setValidError(code: string, text: string) {
this._errors[code] = code + ' - ' + text
let obj:any = {}
obj[code] = code + ' - ' + text
this._errors = Object.assign(this._errors, obj)
}
mergeObj(obj: any) {
this.obj = Object.assign(this.obj, obj)
}
updateCtrl(key: keyof T, ctrl: Partial<FormSchemaCtrl>) {
const fieldIndex = this.ctrls.findIndex(e => e.key === key)
this.ctrls[fieldIndex] = Object.assign(this.ctrls[fieldIndex], ctrl)
}
}

View File

@@ -7,8 +7,8 @@ export class NotificationItem implements TNotificationItem {
code: string
text: string
constructor(args: { code: string; text: string }) {
this.code = args.code
constructor(args: { text: string, code?: string }) {
this.text = args.text
this.code = args.code || 'info'
}
}

View File

@@ -30,7 +30,7 @@ export class DataResultEntity<T> implements IDataResult<T> {
this.setData()
}
setData(data: T = null, pagination?: TPagination): void {
setData(data: T | null = null, pagination?: TPagination): void {
if (data !== null) {
this.data = data
}

View File

@@ -1,11 +1,10 @@
import type { TPagination } from './pagination'
import type { TPaginationQuery } 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)
@@ -14,31 +13,52 @@ export const querySchema = cFieldsSchema
label: 'Сортировка'
})
})
.partial()
.describe('Параметры базового запроса')
export type TQuery = z.infer<typeof querySchema>
/**
* Объект для преобразования фильтра в URL.
* Класс для работы с запросами (для удобства).
*/
export type TFindFilter<T extends TQuery> = {
obj?: Omit<T, 'page' | 'limit' | 'sort'>
pagination?: TPagination
pagination?: TPaginationQuery
sort?: string
}
/**
* Класс для работы с запросами (для удобства).
*/
export class FindFilter<T extends TQuery> implements TFindFilter<T> {
obj?: Omit<T, 'page' | 'limit' | 'sort'>
pagination?: TPagination
pagination?: TPaginationQuery
sort?: string
static getQuery<T extends TQuery>(filter: TFindFilter<T>): T {
return Object.assign(
{ ...filter.obj, ...filter.pagination },
{ sort: filter.sort }
) as T
}
static parse<T extends TQuery>(filter: TFindFilter<T>): FindFilter<T> {
return new FindFilter<T>(this.getQuery(filter))
}
constructor(query?: T) {
let queryCopy = Object.assign({}, query)
// Copy fiends.
let queryCopy: T = Object.assign({}, query)
// Pagination.
this.setPagination(queryCopy)
for (const key of Object.keys(this.pagination)) {
this.pagination = new Pagination(queryCopy).getQuery()
// Delete pagination fields.
if (this.pagination as TPaginationQuery) {
const paginationKeys = Object.keys(this.pagination) as [keyof T]
for (const key of paginationKeys) {
if (queryCopy[key]) delete queryCopy[key]
}
}
// Sort.
if (queryCopy.sort) {
@@ -50,19 +70,11 @@ export class FindFilter<T extends TQuery> implements TFindFilter<T> {
this.obj = queryCopy
}
setPagination(pagination?: TPagination) {
this.pagination = new Pagination(pagination).toObject()
}
static getQuery <T extends TQuery = {}>(filter: TFindFilter<T>): T {
let query: any = {}
for(const key of Object.keys(filter.obj)) {
query[key] = filter.obj[key]
}
if (filter.pagination?.page) query.page = filter.pagination.page
if (filter.pagination?.limit) query.limit = filter.pagination.limit
if (filter.sort) query.sort = filter.sort
return query
/**
* @deprecated.
*/
setPagination(pagination?: TPaginationQuery) {
this.pagination = new Pagination(pagination).getQuery()
}
toObject(): TFindFilter<T> {
@@ -73,6 +85,37 @@ export class FindFilter<T extends TQuery> implements TFindFilter<T> {
}
}
toString(opt?: { base?: string }): string {
let url = opt?.base?.replace(/[?]$/, '') || ''
const query: string[] = []
// Params and Pagination.
for (const [key, val] of Object.entries({
...this.obj,
...this.pagination
})) {
if (val) {
const keyEncode = encodeURIComponent(key)
const valEncode = encodeURIComponent(val)
query.push(keyEncode + '=' + valEncode)
}
}
// Sort.
if (this.sort) {
try {
query.push('sort=' + encodeURIComponent(this.sort))
} catch (e) {}
}
if (query.length) {
url += query.join('&')
}
return url
}
isEqual(filters: TFindFilter<T>[]) {
return isEqual([this, ...filters])
}

View File

@@ -1,6 +1,9 @@
import { z } from 'zod'
import { cFieldsSchema, fieldSchema } from '../forms'
/**
* Модель данных для пагинайи.
*/
export const paginationSchema = cFieldsSchema
.pick({
page: true,
@@ -17,27 +20,43 @@ export const paginationSchema = cFieldsSchema
label: 'Кол-во всех страниц'
})
})
.describe('Пагинация')
.describe('Данные пагинации')
/**
* Модель данных для пагинайи.
*/
export type TPagination = z.infer<typeof paginationSchema>
export const paginationQuerySchema = paginationSchema.pick({
page: true, limit: true
/**
* Модель данных для пагинайи для запросе.
*/
export const paginationQuerySchema = paginationSchema
.pick({
page: true,
limit: true
})
.partial()
.describe('Параметры разбиения на страницы')
/**
* Модель данных для пагинайи для запросе.
*/
export type TPaginationQuery = z.infer<typeof paginationQuerySchema>
// Константы.
//
// Переделать.
//
const DEFAULTS = { page: 1, limit: 10, maxLimit: 100 }
export type TPaginationParseArg = number | string | undefined
export type TPaginationArguments = {
page?: TPaginationParseArg
limit?: TPaginationParseArg
total?: number
}
/**
* @todo Переделать логику.
*/
export class Pagination implements TPagination {
/**
* Максимальный лимит элементов.
@@ -113,9 +132,12 @@ export class Pagination implements TPagination {
page: this.page,
limit: this.limit,
total: this.total,
skip: this.skip,
pages: this.pages
}
}
getQuery(): TPaginationQuery {
return { page: this.page, limit: this.limit }
}
}

View File

@@ -1,10 +1,12 @@
export const isEqual = <T extends object>(objects: T[]) => {
for (let i = 0; i < objects.length; i++) {
const obj1 = objects[i]
const obj2 = objects[i + 1]
const obj1: T = objects[i]
const obj2: T = objects[i + 1]
if (obj2) {
const keys1 = Object.keys(obj1)
const keys2 = Object.keys(obj2)
const keys1 = Object.keys(obj1) as [keyof T]
const keys2 = Object.keys(obj2) as [keyof T]
if (keys1.length !== keys2.length) {
return false
@@ -16,7 +18,7 @@ export const isEqual = <T extends object>(objects: T[]) => {
return false
}
} else {
if (!isEqual([obj1[key], obj2[key]])) {
if (!isEqual([obj1[key], obj2[key]] as T[])) {
return false
}
}

View File

@@ -1,13 +1,15 @@
{
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"target": "ES6",
"module": "CommonJS",
"moduleResolution": "node",
"lib": ["es2017"],
"declaration": true,
"sourceMap": true
"target": "ESNext",
"module": "ESNext",
"strict": true,
"moduleResolution": "Node",
"isolatedModules": true,
"esModuleInterop": true,
"useDefineForClassFields": true,
"declaration": true
},
"exclude": ["node_modules", "dist"]
"include": ["src/**/*.ts", "src/**/*.d.ts"]
}

13
vite.config.ts Normal file
View File

@@ -0,0 +1,13 @@
import { defineConfig } from 'vite'
import dts from 'vite-plugin-dts'
export default defineConfig({
plugins: [dts()],
build: {
lib: {
entry: 'src/index.ts',
name: 'axp-ts',
fileName: 'index'
}
}
})