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", "name": "axp-ts",
"version": "1.9.7", "version": "1.13.0",
"description": "TypeScript helper library", "description": "TypeScript helper library",
"author": "AntoXa PRO <info@antoxa.pro>", "author": "AntoXa PRO <info@antoxa.pro>",
"homepage": "https://antoxahub.ru/antoxa/axp-ts", "homepage": "https://antoxahub.ru/antoxa/axp-ts",
@@ -8,20 +8,36 @@
"type": "git", "type": "git",
"url": "https://antoxahub.ru/antoxa/axp-ts.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": [ "files": [
"dist", "dist",
"tsconfig.ts" "src",
"tsconfig.json"
], ],
"scripts": { "scripts": {
"build": "tsc", "build": "vite build",
"prepare": "npm run build" "prepare": "npm run build"
}, },
"dependencies": { "peerDependencies": {
"zod": "^3.22.1" "zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {
"prettier": "^2.8.8", "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' } from './helpers'
import { FormSchemaCtrl } from './ctrl' import { FormSchemaCtrl } from './ctrl'
export type TUiFieldSelectOption = {
text: string
value: string
}
/** /**
* Create field schema. * Create field schema.
*/ */
export const fieldSchema = <T extends ZodTypeAny>( export const fieldSchema = <T extends ZodTypeAny>(
base: T, base: T,
args?: TFormSchemaCtrlArgs args: TFormSchemaCtrlArgs = {}
) => base.describe(FormSchemaCtrl.toString(args, base.description)) ) => base.describe(FormSchemaCtrl.toString(args, base.description))
/** /**

View File

@@ -3,7 +3,6 @@ import type { TNotificationItem } from '../notification'
import { FormSchemaCtrl } from './ctrl' import { FormSchemaCtrl } from './ctrl'
/** /**
* Интерфейс базовой формы для сущностей в БД. * Интерфейс базовой формы для сущностей в БД.
*/ */
@@ -17,7 +16,7 @@ export interface IFormModel<T> {
obj: T obj: T
ctrls: FormSchemaCtrl[] ctrls: FormSchemaCtrl[]
_errors: {[PropKey in keyof T]?: string} _errors: { [PropKey in keyof T]?: string }
errors: TNotificationItem[] errors: TNotificationItem[]
isValid(): boolean isValid(): boolean
@@ -38,7 +37,7 @@ export class BaseFormModel<T extends object = {}> implements IFormModel<T> {
schema: z.ZodObject<z.ZodRawShape> schema: z.ZodObject<z.ZodRawShape>
ctrls: FormSchemaCtrl[] = [] ctrls: FormSchemaCtrl[] = []
_errors: {[PropKey in keyof T]?: string} = {} _errors: { [PropKey in keyof T]?: string } = {}
constructor(obj: any = {}, schema: z.ZodObject<z.ZodRawShape>) { constructor(obj: any = {}, schema: z.ZodObject<z.ZodRawShape>) {
this._id = obj._id || 'create' this._id = obj._id || 'create'
@@ -74,7 +73,7 @@ export class BaseFormModel<T extends object = {}> implements IFormModel<T> {
let items: TNotificationItem[] = [] let items: TNotificationItem[] = []
for (const code in this._errors) { for (const code in this._errors) {
const text = this._errors[code] const text = this._errors[code]
items.push({ code, text }) if (text) items.push({ code, text })
} }
return items return items
} }
@@ -95,6 +94,17 @@ export class BaseFormModel<T extends object = {}> implements IFormModel<T> {
} }
setValidError(code: string, text: string) { 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 code: string
text: string text: string
constructor(args: { code: string; text: string }) { constructor(args: { text: string, code?: string }) {
this.code = args.code
this.text = args.text this.text = args.text
this.code = args.code || 'info'
} }
} }

View File

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

View File

@@ -1,11 +1,10 @@
import type { TPagination } from './pagination' import type { TPaginationQuery } from './pagination'
import { z } from 'zod' import { z } from 'zod'
import { isEqual } from '../utils' import { isEqual } from '../utils'
import { Pagination, paginationQuerySchema } from './pagination' import { Pagination, paginationQuerySchema } from './pagination'
import { bFieldsSchema, cFieldsSchema, fieldSchema } from '../forms' import { bFieldsSchema, cFieldsSchema, fieldSchema } from '../forms'
export const querySchema = cFieldsSchema export const querySchema = cFieldsSchema
.pick({ q: true }) .pick({ q: true })
.extend(paginationQuerySchema.shape) .extend(paginationQuerySchema.shape)
@@ -14,31 +13,52 @@ export const querySchema = cFieldsSchema
label: 'Сортировка' label: 'Сортировка'
}) })
}) })
.partial()
.describe('Параметры базового запроса')
export type TQuery = z.infer<typeof querySchema> export type TQuery = z.infer<typeof querySchema>
/** /**
* Объект для преобразования фильтра в URL. * Класс для работы с запросами (для удобства).
*/ */
export type TFindFilter<T extends TQuery> = { export type TFindFilter<T extends TQuery> = {
obj?: Omit<T, 'page' | 'limit' | 'sort'> obj?: Omit<T, 'page' | 'limit' | 'sort'>
pagination?: TPagination pagination?: TPaginationQuery
sort?: string sort?: string
} }
/**
* Класс для работы с запросами (для удобства).
*/
export class FindFilter<T extends TQuery> implements TFindFilter<T> { export class FindFilter<T extends TQuery> implements TFindFilter<T> {
obj?: Omit<T, 'page' | 'limit' | 'sort'> obj?: Omit<T, 'page' | 'limit' | 'sort'>
pagination?: TPagination pagination?: TPaginationQuery
sort?: string 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) { constructor(query?: T) {
let queryCopy = Object.assign({}, query) // Copy fiends.
let queryCopy: T = Object.assign({}, query)
// Pagination. // Pagination.
this.setPagination(queryCopy) this.pagination = new Pagination(queryCopy).getQuery()
for (const key of Object.keys(this.pagination)) { // 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] if (queryCopy[key]) delete queryCopy[key]
} }
}
// Sort. // Sort.
if (queryCopy.sort) { if (queryCopy.sort) {
@@ -50,19 +70,11 @@ export class FindFilter<T extends TQuery> implements TFindFilter<T> {
this.obj = queryCopy this.obj = queryCopy
} }
setPagination(pagination?: TPagination) { /**
this.pagination = new Pagination(pagination).toObject() * @deprecated.
} */
setPagination(pagination?: TPaginationQuery) {
static getQuery <T extends TQuery = {}>(filter: TFindFilter<T>): T { this.pagination = new Pagination(pagination).getQuery()
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
} }
toObject(): TFindFilter<T> { 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>[]) { isEqual(filters: TFindFilter<T>[]) {
return isEqual([this, ...filters]) return isEqual([this, ...filters])
} }

View File

@@ -1,6 +1,9 @@
import { z } from 'zod' import { z } from 'zod'
import { cFieldsSchema, fieldSchema } from '../forms' import { cFieldsSchema, fieldSchema } from '../forms'
/**
* Модель данных для пагинайи.
*/
export const paginationSchema = cFieldsSchema export const paginationSchema = cFieldsSchema
.pick({ .pick({
page: true, page: true,
@@ -17,27 +20,43 @@ export const paginationSchema = cFieldsSchema
label: 'Кол-во всех страниц' label: 'Кол-во всех страниц'
}) })
}) })
.describe('Пагинация') .describe('Данные пагинации')
/**
* Модель данных для пагинайи.
*/
export type TPagination = z.infer<typeof paginationSchema> 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> export type TPaginationQuery = z.infer<typeof paginationQuerySchema>
// Константы. //
// Переделать.
//
const DEFAULTS = { page: 1, limit: 10, maxLimit: 100 } const DEFAULTS = { page: 1, limit: 10, maxLimit: 100 }
export type TPaginationParseArg = number | string | undefined export type TPaginationParseArg = number | string | undefined
export type TPaginationArguments = { export type TPaginationArguments = {
page?: TPaginationParseArg page?: TPaginationParseArg
limit?: TPaginationParseArg limit?: TPaginationParseArg
total?: number total?: number
} }
/**
* @todo Переделать логику.
*/
export class Pagination implements TPagination { export class Pagination implements TPagination {
/** /**
* Максимальный лимит элементов. * Максимальный лимит элементов.
@@ -113,9 +132,12 @@ export class Pagination implements TPagination {
page: this.page, page: this.page,
limit: this.limit, limit: this.limit,
total: this.total, total: this.total,
skip: this.skip, skip: this.skip,
pages: this.pages 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[]) => { export const isEqual = <T extends object>(objects: T[]) => {
for (let i = 0; i < objects.length; i++) { 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) { if (obj2) {
const keys1 = Object.keys(obj1) const keys1 = Object.keys(obj1) as [keyof T]
const keys2 = Object.keys(obj2) const keys2 = Object.keys(obj2) as [keyof T]
if (keys1.length !== keys2.length) { if (keys1.length !== keys2.length) {
return false return false
@@ -16,7 +18,7 @@ export const isEqual = <T extends object>(objects: T[]) => {
return false return false
} }
} else { } else {
if (!isEqual([obj1[key], obj2[key]])) { if (!isEqual([obj1[key], obj2[key]] as T[])) {
return false return false
} }
} }

View File

@@ -1,13 +1,15 @@
{ {
"compilerOptions": { "compilerOptions": {
"rootDir": "src", "target": "ESNext",
"outDir": "dist", "module": "ESNext",
"target": "ES6",
"module": "CommonJS", "strict": true,
"moduleResolution": "node", "moduleResolution": "Node",
"lib": ["es2017"], "isolatedModules": true,
"declaration": true, "esModuleInterop": true,
"sourceMap": 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'
}
}
})