@anjianshi/utils 2.7.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/env-browser/device.d.ts +24 -0
- package/env-browser/device.js +50 -0
- package/env-browser/global.d.ts +10 -0
- package/env-browser/global.js +15 -0
- package/env-browser/load-script.d.ts +5 -0
- package/env-browser/load-script.js +13 -0
- package/env-browser/logging.d.ts +18 -0
- package/env-browser/logging.js +49 -0
- package/env-browser/manage-vconsole.d.ts +16 -0
- package/env-browser/manage-vconsole.js +38 -0
- package/env-node/crypto-random.d.ts +13 -0
- package/env-node/crypto-random.js +28 -0
- package/env-node/fs.d.ts +19 -0
- package/env-node/fs.js +48 -0
- package/env-node/index.d.ts +6 -0
- package/env-node/index.js +6 -0
- package/env-node/logging/handlers.d.ts +58 -0
- package/env-node/logging/handlers.js +154 -0
- package/env-node/logging/index.d.ts +11 -0
- package/env-node/logging/index.js +14 -0
- package/env-node/safe-request.d.ts +26 -0
- package/env-node/safe-request.js +40 -0
- package/env-react/emotion.d.ts +20 -0
- package/env-react/emotion.jsx +34 -0
- package/env-service/controllers.d.ts +30 -0
- package/env-service/controllers.js +41 -0
- package/env-service/env-reader.d.ts +55 -0
- package/env-service/env-reader.js +79 -0
- package/env-service/index.d.ts +6 -0
- package/env-service/index.js +6 -0
- package/env-service/prisma/adapt-logging.d.ts +21 -0
- package/env-service/prisma/adapt-logging.js +30 -0
- package/env-service/prisma/extensions/exist.d.ts +10 -0
- package/env-service/prisma/extensions/exist.js +16 -0
- package/env-service/prisma/extensions/find-and-count.d.ts +7 -0
- package/env-service/prisma/extensions/find-and-count.js +19 -0
- package/env-service/prisma/extensions/soft-delete.d.ts +52 -0
- package/env-service/prisma/extensions/soft-delete.js +123 -0
- package/env-service/prisma/extensions/with-transaction.d.ts +9 -0
- package/env-service/prisma/extensions/with-transaction.js +54 -0
- package/env-service/prisma/index.d.ts +6 -0
- package/env-service/prisma/index.js +6 -0
- package/env-service/prisma/transaction-contexted.d.ts +11 -0
- package/env-service/prisma/transaction-contexted.js +52 -0
- package/env-service/redis-cache.d.ts +39 -0
- package/env-service/redis-cache.js +116 -0
- package/env-service/tasks.d.ts +12 -0
- package/env-service/tasks.js +37 -0
- package/index.d.ts +3 -0
- package/index.js +3 -0
- package/init-dayjs.d.ts +2 -0
- package/init-dayjs.js +7 -0
- package/lang/async.d.ts +19 -0
- package/lang/async.js +34 -0
- package/lang/color.d.ts +37 -0
- package/lang/color.js +111 -0
- package/lang/index.d.ts +7 -0
- package/lang/index.js +7 -0
- package/lang/may-success.d.ts +40 -0
- package/lang/may-success.js +27 -0
- package/lang/object.d.ts +12 -0
- package/lang/object.js +41 -0
- package/lang/random.d.ts +13 -0
- package/lang/random.js +24 -0
- package/lang/string.d.ts +29 -0
- package/lang/string.js +92 -0
- package/lang/time.d.ts +10 -0
- package/lang/time.js +18 -0
- package/{src/lang/types.ts → lang/types.d.ts} +23 -43
- package/lang/types.js +28 -0
- package/logging/adapt.d.ts +10 -0
- package/logging/adapt.js +43 -0
- package/logging/formatters.d.ts +10 -0
- package/logging/formatters.js +22 -0
- package/logging/index.d.ts +45 -0
- package/logging/index.js +90 -0
- package/md5.d.ts +30 -0
- package/md5.js +308 -0
- package/package.json +14 -20
- package/url.d.ts +77 -0
- package/url.js +149 -0
- package/validators/array.d.ts +30 -0
- package/validators/array.js +47 -0
- package/validators/base.d.ts +82 -0
- package/validators/base.js +42 -0
- package/validators/boolean.d.ts +3 -0
- package/validators/boolean.js +22 -0
- package/validators/datetime.d.ts +12 -0
- package/validators/datetime.js +30 -0
- package/validators/factory.d.ts +70 -0
- package/validators/factory.js +121 -0
- package/validators/index.d.ts +9 -0
- package/validators/index.js +9 -0
- package/validators/number.d.ts +19 -0
- package/validators/number.js +26 -0
- package/validators/object.d.ts +28 -0
- package/validators/object.js +49 -0
- package/validators/one-of.d.ts +10 -0
- package/validators/one-of.js +15 -0
- package/validators/string.d.ts +22 -0
- package/validators/string.js +35 -0
- package/README.md +0 -10
- package/eslint.config.cjs +0 -33
- package/publish-prepare.cjs +0 -16
- package/src/env-browser/device.ts +0 -62
- package/src/env-browser/global.ts +0 -21
- package/src/env-browser/load-script.ts +0 -13
- package/src/env-browser/logging.ts +0 -58
- package/src/env-browser/manage-vconsole.ts +0 -54
- package/src/env-node/crypto-random.ts +0 -30
- package/src/env-node/fs.ts +0 -50
- package/src/env-node/index.ts +0 -6
- package/src/env-node/logging/handlers.ts +0 -190
- package/src/env-node/logging/index.ts +0 -16
- package/src/env-node/safe-request.ts +0 -66
- package/src/env-react/emotion.tsx +0 -42
- package/src/env-service/controllers.ts +0 -93
- package/src/env-service/env-reader.ts +0 -141
- package/src/env-service/index.ts +0 -6
- package/src/env-service/prisma/adapt-logging.ts +0 -39
- package/src/env-service/prisma/extensions/exist.ts +0 -21
- package/src/env-service/prisma/extensions/find-and-count.ts +0 -24
- package/src/env-service/prisma/extensions/soft-delete.ts +0 -162
- package/src/env-service/prisma/extensions/with-transaction.ts +0 -65
- package/src/env-service/prisma/index.ts +0 -6
- package/src/env-service/prisma/transaction-contexted.ts +0 -80
- package/src/env-service/redis-cache.ts +0 -142
- package/src/env-service/tasks.ts +0 -45
- package/src/index.ts +0 -3
- package/src/init-dayjs.ts +0 -8
- package/src/lang/async.ts +0 -47
- package/src/lang/color.ts +0 -119
- package/src/lang/index.ts +0 -7
- package/src/lang/may-success.ts +0 -57
- package/src/lang/object.ts +0 -39
- package/src/lang/random.ts +0 -25
- package/src/lang/string.ts +0 -95
- package/src/lang/time.ts +0 -19
- package/src/logging/adapt.ts +0 -49
- package/src/logging/formatters.ts +0 -23
- package/src/logging/index.ts +0 -106
- package/src/md5.ts +0 -318
- package/src/url.ts +0 -185
- package/src/validators/array.ts +0 -97
- package/src/validators/base.ts +0 -145
- package/src/validators/boolean.ts +0 -21
- package/src/validators/datetime.ts +0 -39
- package/src/validators/factory.ts +0 -244
- package/src/validators/index.ts +0 -9
- package/src/validators/number.ts +0 -54
- package/src/validators/object.ts +0 -101
- package/src/validators/one-of.ts +0 -33
- package/src/validators/string.ts +0 -72
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type MaySuccess } from '../lang/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* 支持传入进行验证的值类型
|
|
4
|
+
*/
|
|
5
|
+
export type AllowedInputValue = PrimitiveType | null | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* JavaScript 基础值类型
|
|
8
|
+
*/
|
|
9
|
+
export type PrimitiveType = string | boolean | number | PrimitiveType[] | [...PrimitiveType[]] | {
|
|
10
|
+
[key: string]: PrimitiveType;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* validator 通用参数
|
|
14
|
+
*/
|
|
15
|
+
export interface CommonOptions<Value = any> {
|
|
16
|
+
/** 是否允许 null 值 @default false */
|
|
17
|
+
null?: boolean;
|
|
18
|
+
/** 字段是否必须有值(不能是 undefined) @default true */
|
|
19
|
+
required?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* 默认值,字段无值(或值为 undefined)时生效,值为 null 不会生效。
|
|
22
|
+
* 指定后 required 选项将失去作用。
|
|
23
|
+
*/
|
|
24
|
+
defaults?: Value;
|
|
25
|
+
custom?: (input: Value) => MaySuccess<Value>;
|
|
26
|
+
[key: string]: unknown;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* 补全了的 Options
|
|
30
|
+
*/
|
|
31
|
+
type FullfiledOptions<Options extends Partial<CommonOptions>> = Omit<Options, keyof CommonOptions> & {
|
|
32
|
+
null: Options['null'] extends true ? true : false;
|
|
33
|
+
required: Options['required'] extends false ? false : true;
|
|
34
|
+
defaults: Options extends {
|
|
35
|
+
defaults: infer T;
|
|
36
|
+
} ? T : undefined;
|
|
37
|
+
custom: Options extends {
|
|
38
|
+
custom: infer T;
|
|
39
|
+
} ? T : undefined;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* 验证完成后能得到的值类型
|
|
43
|
+
*/
|
|
44
|
+
export type Validated<Value, InputOptions extends CommonOptions> = FullfiledOptions<InputOptions> extends {
|
|
45
|
+
defaults: undefined;
|
|
46
|
+
} ? FullfiledOptions<InputOptions> extends {
|
|
47
|
+
required: false;
|
|
48
|
+
null: false;
|
|
49
|
+
} ? Value | undefined : FullfiledOptions<InputOptions> extends {
|
|
50
|
+
required: false;
|
|
51
|
+
null: true;
|
|
52
|
+
} ? Value | undefined | null : FullfiledOptions<InputOptions> extends {
|
|
53
|
+
required: true;
|
|
54
|
+
null: false;
|
|
55
|
+
} ? Value : FullfiledOptions<InputOptions> extends {
|
|
56
|
+
required: true;
|
|
57
|
+
null: true;
|
|
58
|
+
} ? Value | null : Value : FullfiledOptions<InputOptions> extends {
|
|
59
|
+
defaults: infer T;
|
|
60
|
+
null: false;
|
|
61
|
+
} ? Value | T : FullfiledOptions<InputOptions> extends {
|
|
62
|
+
defaults: infer T;
|
|
63
|
+
null: true;
|
|
64
|
+
} ? Value | T | null : never;
|
|
65
|
+
/**
|
|
66
|
+
* 最终生成的 validator 函数类型
|
|
67
|
+
*/
|
|
68
|
+
export interface Validator<Value, InputOptions extends CommonOptions> {
|
|
69
|
+
(input: AllowedInputValue): MaySuccess<Validated<Value, InputOptions>>;
|
|
70
|
+
(field: string, input: AllowedInputValue): MaySuccess<Validated<Value, InputOptions>>;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* 返回支持指定格式的 options、并按照传入的逻辑进行验证的 validator 的生成器。
|
|
74
|
+
* 对 CommonOptions 相关内容的验证以自动包含在里面,只需要传入额外的验证逻辑即可。
|
|
75
|
+
*/
|
|
76
|
+
export declare function getValidatorGenerator<Value, Options extends CommonOptions>(validate: (field: string, input: PrimitiveType | Validated<Value, Options>, options: Options) => MaySuccess<Value>): <const InputOptions extends Options>(inputOptions: InputOptions) => Validator<Value, InputOptions>;
|
|
77
|
+
/**
|
|
78
|
+
* 返回只进行基本检查,不带定制的验证逻辑的 validator。
|
|
79
|
+
* 同时也是定制 validator 最小化实现的例子。
|
|
80
|
+
*/
|
|
81
|
+
export declare const getAnyValidator: <const InputOptions extends CommonOptions<any>>(inputOptions: InputOptions) => Validator<unknown, InputOptions>;
|
|
82
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { success, failed } from '../lang/index.js';
|
|
2
|
+
// -----------------------------------
|
|
3
|
+
/**
|
|
4
|
+
* 返回支持指定格式的 options、并按照传入的逻辑进行验证的 validator 的生成器。
|
|
5
|
+
* 对 CommonOptions 相关内容的验证以自动包含在里面,只需要传入额外的验证逻辑即可。
|
|
6
|
+
*/
|
|
7
|
+
export function getValidatorGenerator(validate) {
|
|
8
|
+
return function validatorGenerator(inputOptions) {
|
|
9
|
+
function validator(field, input) {
|
|
10
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
11
|
+
const { null: allowNull = false, required = true, defaults, custom } = inputOptions;
|
|
12
|
+
if (typeof field !== 'string') {
|
|
13
|
+
input = field;
|
|
14
|
+
field = 'value';
|
|
15
|
+
}
|
|
16
|
+
let value = input;
|
|
17
|
+
if (typeof value === 'undefined') {
|
|
18
|
+
if (typeof defaults !== 'undefined') {
|
|
19
|
+
value = defaults;
|
|
20
|
+
}
|
|
21
|
+
else if (required) {
|
|
22
|
+
return failed(`${field} is required`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (value === null && !allowNull)
|
|
26
|
+
return failed(`${field} cannot be null`);
|
|
27
|
+
if (value === null || value === undefined)
|
|
28
|
+
return success(value);
|
|
29
|
+
const validated = validate(field, value, inputOptions);
|
|
30
|
+
return validated.success && custom ? custom(validated.data) : validated;
|
|
31
|
+
}
|
|
32
|
+
return validator;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
// -----------------------------------
|
|
36
|
+
/**
|
|
37
|
+
* 返回只进行基本检查,不带定制的验证逻辑的 validator。
|
|
38
|
+
* 同时也是定制 validator 最小化实现的例子。
|
|
39
|
+
*/
|
|
40
|
+
export const getAnyValidator = getValidatorGenerator(function validate(field, input) {
|
|
41
|
+
return success(input);
|
|
42
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { success, failed } from '../lang/index.js';
|
|
2
|
+
import { getValidatorGenerator } from './base.js';
|
|
3
|
+
export const getBooleanValidator = getValidatorGenerator(function validate(field, input) {
|
|
4
|
+
let value = null;
|
|
5
|
+
if (typeof input === 'boolean') {
|
|
6
|
+
value = input;
|
|
7
|
+
}
|
|
8
|
+
else if (typeof input === 'string') {
|
|
9
|
+
const str = input.trim().toLowerCase();
|
|
10
|
+
if (['1', 'true', 'on', 'yes'].includes(str))
|
|
11
|
+
value = true;
|
|
12
|
+
else if (['0', 'false', 'off', 'no'].includes(str))
|
|
13
|
+
value = false;
|
|
14
|
+
}
|
|
15
|
+
else if (typeof input === 'number') {
|
|
16
|
+
if (input === 1)
|
|
17
|
+
value = true;
|
|
18
|
+
else if (input === 0)
|
|
19
|
+
value = false;
|
|
20
|
+
}
|
|
21
|
+
return value === null ? failed(`${field} must be true or false`) : success(value);
|
|
22
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 验证日期时间类型的值,依赖 dayjs
|
|
3
|
+
*/
|
|
4
|
+
import { Dayjs } from 'dayjs';
|
|
5
|
+
import { type CommonOptions } from './base.js';
|
|
6
|
+
export interface DatetimeOptions extends CommonOptions<number> {
|
|
7
|
+
raw?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export type DatetimeValue<Options extends DatetimeOptions> = Options extends {
|
|
10
|
+
raw: true;
|
|
11
|
+
} ? Date : Dayjs;
|
|
12
|
+
export declare function getDatetimeValidator<const Options extends DatetimeOptions>(options?: Options): import("./base.js").Validator<DatetimeValue<Options>, Options>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 验证日期时间类型的值,依赖 dayjs
|
|
3
|
+
*/
|
|
4
|
+
import dayjs, { Dayjs } from 'dayjs';
|
|
5
|
+
import { success, failed } from '../lang/index.js';
|
|
6
|
+
import { getValidatorGenerator } from './base.js';
|
|
7
|
+
export function getDatetimeValidator(options = {}) {
|
|
8
|
+
return getValidatorGenerator(function validate(field, value) {
|
|
9
|
+
let dayjsValue;
|
|
10
|
+
if (typeof value === 'number') {
|
|
11
|
+
dayjsValue = dayjs.unix(value);
|
|
12
|
+
if (!dayjsValue.isValid())
|
|
13
|
+
return failed(`${field} must be a valid unix timestamp`);
|
|
14
|
+
}
|
|
15
|
+
else if (typeof value === 'string') {
|
|
16
|
+
dayjsValue = dayjs(value);
|
|
17
|
+
if (!dayjsValue.isValid())
|
|
18
|
+
return failed(`${field} must be a valid datetime string`);
|
|
19
|
+
}
|
|
20
|
+
else if (value instanceof Date || value instanceof Dayjs) {
|
|
21
|
+
dayjsValue = dayjs(value);
|
|
22
|
+
if (!dayjsValue.isValid())
|
|
23
|
+
return failed(`${field} must be a valid Date or Dayjs object`);
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
return failed(`${field} must be a datetime string or unix timestamp`);
|
|
27
|
+
}
|
|
28
|
+
return success((options.raw ? dayjsValue.toDate() : dayjsValue));
|
|
29
|
+
})(options);
|
|
30
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 实现创建 validator 的快捷方式
|
|
3
|
+
*/
|
|
4
|
+
import { type ArrayOptions, type TupleOptions } from './array.js';
|
|
5
|
+
import { type Validator, type CommonOptions, type Validated } from './base.js';
|
|
6
|
+
import { type BooleanOptions } from './boolean.js';
|
|
7
|
+
import { type DatetimeOptions, type DatetimeValue } from './datetime.js';
|
|
8
|
+
import { type NumberOptions, type NumberValueWithChoices } from './number.js';
|
|
9
|
+
import { type RecordOptions, type StructOptions } from './object.js';
|
|
10
|
+
import { type OneOfOptions } from './one-of.js';
|
|
11
|
+
import { type StringOptions, type StringValueWithChoices } from './string.js';
|
|
12
|
+
export interface AnyDefinition extends CommonOptions {
|
|
13
|
+
type: 'any';
|
|
14
|
+
}
|
|
15
|
+
export interface BooleanDefinition extends BooleanOptions {
|
|
16
|
+
type: 'boolean';
|
|
17
|
+
}
|
|
18
|
+
export interface NumberDefinition extends NumberOptions {
|
|
19
|
+
type: 'number';
|
|
20
|
+
}
|
|
21
|
+
export interface StringDefinition extends StringOptions {
|
|
22
|
+
type: 'string';
|
|
23
|
+
}
|
|
24
|
+
export interface DatetimeDefinition extends DatetimeOptions {
|
|
25
|
+
type: 'datetime';
|
|
26
|
+
}
|
|
27
|
+
export interface ArrayDefinition extends Omit<ArrayOptions, 'item'> {
|
|
28
|
+
type: 'array';
|
|
29
|
+
item: Definition;
|
|
30
|
+
}
|
|
31
|
+
export interface TupleDefinition extends Omit<TupleOptions, 'tuple'> {
|
|
32
|
+
type: 'tuple';
|
|
33
|
+
tuple: Definition[];
|
|
34
|
+
}
|
|
35
|
+
export interface StructDefinition extends Omit<StructOptions, 'struct'> {
|
|
36
|
+
type: 'struct';
|
|
37
|
+
struct: Record<string, Definition>;
|
|
38
|
+
}
|
|
39
|
+
export interface RecordDefinition extends Omit<RecordOptions, 'record'> {
|
|
40
|
+
type: 'record';
|
|
41
|
+
record: Definition;
|
|
42
|
+
}
|
|
43
|
+
export interface OneOfDefinition extends Omit<OneOfOptions, 'validators'> {
|
|
44
|
+
type: 'oneOf';
|
|
45
|
+
validators: Definition[];
|
|
46
|
+
}
|
|
47
|
+
export type Definition = AnyDefinition | BooleanDefinition | NumberDefinition | StringDefinition | DatetimeDefinition | ArrayDefinition | TupleDefinition | StructDefinition | RecordDefinition | OneOfDefinition;
|
|
48
|
+
export type ValueOfDefinition<Def extends Definition> = Def extends AnyDefinition ? unknown : Def extends BooleanDefinition ? boolean : Def extends NumberDefinition ? NumberValueWithChoices<Def> : Def extends StringDefinition ? StringValueWithChoices<Def> : Def extends DatetimeDefinition ? DatetimeValue<Def> : Def extends ArrayDefinition ? Validated<ValueOfDefinition<Def['item']>, Def['item']>[] : Def extends TupleDefinition ? {
|
|
49
|
+
[Key in keyof Def['tuple']]: Def['tuple'][Key] extends Definition ? Validated<ValueOfDefinition<Def['tuple'][Key]>, Def['tuple'][Key]> : Def['tuple'][Key];
|
|
50
|
+
} : Def extends StructDefinition ? {
|
|
51
|
+
[Key in keyof Def['struct']]: Validated<ValueOfDefinition<Def['struct'][Key]>, Def['struct'][Key]>;
|
|
52
|
+
} : Def extends RecordDefinition ? Record<string, Validated<ValueOfDefinition<Def['record']>, Def['record']>> : Def extends OneOfDefinition ? {
|
|
53
|
+
[Key in keyof Def['validators']]: Def['validators'][Key] extends Definition ? Validated<ValueOfDefinition<Def['validators'][Key]>, Def['validators'][Key]> : Def['validators'][Key];
|
|
54
|
+
}[number] : never;
|
|
55
|
+
export type OptionsFromDefinition<Def extends Definition> = Def extends ArrayDefinition ? Omit<Def, 'item'> & {
|
|
56
|
+
item: ValidatorForDefinition<Def['item']>;
|
|
57
|
+
} : Def extends TupleDefinition ? Omit<Def, 'tuple'> & {
|
|
58
|
+
tuple: {
|
|
59
|
+
[Key in keyof Def['tuple']]: Def['tuple'][Key] extends Definition ? ValidatorForDefinition<Def['tuple'][Key]> : never;
|
|
60
|
+
};
|
|
61
|
+
} : Def extends StructDefinition ? Omit<Def, 'struct'> & {
|
|
62
|
+
struct: {
|
|
63
|
+
[Key in keyof Def['struct']]: ValidatorForDefinition<Def['struct'][Key]>;
|
|
64
|
+
};
|
|
65
|
+
} : Def extends RecordDefinition ? Omit<Def, 'record'> & {
|
|
66
|
+
record: ValidatorForDefinition<Def['record']>;
|
|
67
|
+
} : Def;
|
|
68
|
+
export type ValidatorForDefinition<Def extends Definition> = Validator<ValueOfDefinition<Def>, OptionsFromDefinition<Def>>;
|
|
69
|
+
export type ResultForDefinition<Def extends Definition> = ReturnType<ValidatorForDefinition<Def>>;
|
|
70
|
+
export declare function getValidator<const InputDefinition extends Definition>(definition: InputDefinition): ValidatorForDefinition<InputDefinition>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 实现创建 validator 的快捷方式
|
|
3
|
+
*/
|
|
4
|
+
import { getArrayValidator, getTupleValidator, } from './array.js';
|
|
5
|
+
import { getAnyValidator } from './base.js';
|
|
6
|
+
import { getBooleanValidator } from './boolean.js';
|
|
7
|
+
import { getDatetimeValidator } from './datetime.js';
|
|
8
|
+
import { getNumberValidator } from './number.js';
|
|
9
|
+
import { getRecordValidator, getStructValidator, } from './object.js';
|
|
10
|
+
import { getOneOfValidator } from './one-of.js';
|
|
11
|
+
import { getStringValidator } from './string.js';
|
|
12
|
+
export function getValidator(definition) {
|
|
13
|
+
switch (definition.type) {
|
|
14
|
+
case 'any':
|
|
15
|
+
return getAnyValidator(definition);
|
|
16
|
+
case 'boolean':
|
|
17
|
+
return getBooleanValidator(definition);
|
|
18
|
+
case 'number':
|
|
19
|
+
return getNumberValidator(definition);
|
|
20
|
+
case 'string':
|
|
21
|
+
return getStringValidator(definition);
|
|
22
|
+
case 'datetime':
|
|
23
|
+
return getDatetimeValidator(definition);
|
|
24
|
+
case 'array':
|
|
25
|
+
// @ts-ignore 允许递归类型推断
|
|
26
|
+
return getArrayValidator({
|
|
27
|
+
// @ts-ignore 允许递归类型推断
|
|
28
|
+
...definition,
|
|
29
|
+
item: getValidator(definition.item),
|
|
30
|
+
});
|
|
31
|
+
case 'tuple':
|
|
32
|
+
return getTupleValidator({
|
|
33
|
+
...definition,
|
|
34
|
+
tuple: definition.tuple.map(def => getValidator(def)),
|
|
35
|
+
});
|
|
36
|
+
case 'struct': {
|
|
37
|
+
const struct = {};
|
|
38
|
+
for (const [key, def] of Object.entries(definition.struct))
|
|
39
|
+
struct[key] = getValidator(def);
|
|
40
|
+
return getStructValidator({ ...definition, struct });
|
|
41
|
+
}
|
|
42
|
+
case 'record':
|
|
43
|
+
return getRecordValidator({
|
|
44
|
+
...definition,
|
|
45
|
+
record: getValidator(definition.record),
|
|
46
|
+
});
|
|
47
|
+
case 'oneOf':
|
|
48
|
+
return getOneOfValidator({
|
|
49
|
+
...definition,
|
|
50
|
+
validators: definition.validators.map(def => getValidator(def)),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
// ---------------- 测试用例 -----------------
|
|
55
|
+
// const v1 = getValidator({ type: 'string' })(1)
|
|
56
|
+
// const v2 = getValidator({ type: 'string', null: true })(1)
|
|
57
|
+
// const v3 = getValidator({ type: 'string', null: true, required: false })(1)
|
|
58
|
+
// const v4 = getValidator({ type: 'string', null: true, required: false, choices: ['a', 'b', 'c'] })(
|
|
59
|
+
// 1,
|
|
60
|
+
// )
|
|
61
|
+
// const v5 = getValidator({
|
|
62
|
+
// type: 'string',
|
|
63
|
+
// null: true,
|
|
64
|
+
// required: false,
|
|
65
|
+
// choices: ['a', 'b', 'c'],
|
|
66
|
+
// defaults: 'd',
|
|
67
|
+
// })(1)
|
|
68
|
+
// const v6 = getValidator({
|
|
69
|
+
// type: 'array',
|
|
70
|
+
// null: true,
|
|
71
|
+
// required: false,
|
|
72
|
+
// item: { type: 'string', null: true, choices: ['a', 'b', 'c'] },
|
|
73
|
+
// })(1)
|
|
74
|
+
// const v7 = getValidator({
|
|
75
|
+
// type: 'tuple',
|
|
76
|
+
// tuple: [
|
|
77
|
+
// { type: 'string', choices: ['a', 'b', 'c'] },
|
|
78
|
+
// { type: 'string', null: true },
|
|
79
|
+
// ],
|
|
80
|
+
// })(1)
|
|
81
|
+
// if (v7.success) {
|
|
82
|
+
// const [a, b] = v7.data
|
|
83
|
+
// }
|
|
84
|
+
// const v8 = getValidator({
|
|
85
|
+
// type: 'struct',
|
|
86
|
+
// struct: {
|
|
87
|
+
// x: { type: 'string', choices: ['a', 'b', 'c'] },
|
|
88
|
+
// y: { type: 'string', null: true },
|
|
89
|
+
// },
|
|
90
|
+
// })(1)
|
|
91
|
+
// if (v8.success) {
|
|
92
|
+
// const { x, y } = v8.data
|
|
93
|
+
// }
|
|
94
|
+
// const v9 = getValidator({
|
|
95
|
+
// type: 'record',
|
|
96
|
+
// record: { type: 'string', null: true, choices: ['a', 'b', 'c'] },
|
|
97
|
+
// })(1)
|
|
98
|
+
// const v10 = getValidator({
|
|
99
|
+
// type: 'oneOf',
|
|
100
|
+
// validators: [
|
|
101
|
+
// { type: 'string', choices: ['a', 'b', 'c'] },
|
|
102
|
+
// { type: 'number', null: true },
|
|
103
|
+
// ],
|
|
104
|
+
// defaults: true,
|
|
105
|
+
// })(1)
|
|
106
|
+
// const v11 = getValidator({
|
|
107
|
+
// type: 'string',
|
|
108
|
+
// custom(value) {
|
|
109
|
+
// return { success: true, data: value }
|
|
110
|
+
// },
|
|
111
|
+
// defaults: 'some text',
|
|
112
|
+
// })(1)
|
|
113
|
+
// const v12 = getValidator({
|
|
114
|
+
// type: 'datetime',
|
|
115
|
+
// null: true,
|
|
116
|
+
// required: false,
|
|
117
|
+
// })(1)
|
|
118
|
+
// const v13 = getValidator({
|
|
119
|
+
// type: 'datetime',
|
|
120
|
+
// raw: true,
|
|
121
|
+
// })(1)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './base.js';
|
|
2
|
+
export * from './boolean.js';
|
|
3
|
+
export * from './number.js';
|
|
4
|
+
export * from './string.js';
|
|
5
|
+
export * from './datetime.js';
|
|
6
|
+
export * from './array.js';
|
|
7
|
+
export * from './object.js';
|
|
8
|
+
export * from './one-of.js';
|
|
9
|
+
export * from './factory.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './base.js';
|
|
2
|
+
export * from './boolean.js';
|
|
3
|
+
export * from './number.js';
|
|
4
|
+
export * from './string.js';
|
|
5
|
+
export * from './datetime.js';
|
|
6
|
+
export * from './array.js';
|
|
7
|
+
export * from './object.js';
|
|
8
|
+
export * from './one-of.js';
|
|
9
|
+
export * from './factory.js';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type CommonOptions } from './base.js';
|
|
2
|
+
export interface NumberOptions extends CommonOptions<number> {
|
|
3
|
+
/** 数值最小值 */
|
|
4
|
+
min?: number;
|
|
5
|
+
/** 数值最大值 */
|
|
6
|
+
max?: number;
|
|
7
|
+
/** 是否允许小数 @default false */
|
|
8
|
+
float?: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* 指定可选值
|
|
11
|
+
* 若指定,前几个选项将不再生效 */
|
|
12
|
+
choices?: number[] | Record<number, string>;
|
|
13
|
+
}
|
|
14
|
+
export type NumberValueWithChoices<Options extends NumberOptions> = Options extends {
|
|
15
|
+
choices: (infer T)[];
|
|
16
|
+
} ? T : Options extends {
|
|
17
|
+
choices: Record<number, string>;
|
|
18
|
+
} ? Options['choices'][keyof Options['choices']] : number;
|
|
19
|
+
export declare function getNumberValidator<const Options extends NumberOptions>(options?: Options): import("./base.js").Validator<NumberValueWithChoices<Options>, Options>;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { truthy, success, failed } from '../lang/index.js';
|
|
2
|
+
import { getValidatorGenerator } from './base.js';
|
|
3
|
+
export function getNumberValidator(options = {}) {
|
|
4
|
+
return getValidatorGenerator(function validate(field, value) {
|
|
5
|
+
if (typeof value === 'string')
|
|
6
|
+
value = parseFloat(value);
|
|
7
|
+
if (typeof value !== 'number' || !isFinite(value))
|
|
8
|
+
return failed(`${field} must be a valid number`);
|
|
9
|
+
if ('choices' in options && options.choices) {
|
|
10
|
+
const choices = Array.isArray(options.choices)
|
|
11
|
+
? options.choices
|
|
12
|
+
: Object.values(options.choices).map(v => parseInt(v, 10));
|
|
13
|
+
if (!choices.includes(value))
|
|
14
|
+
return failed(`${field} can only be one of ${choices.join(', ')}.`);
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
if (!truthy(options.float) && value % 1 !== 0)
|
|
18
|
+
return failed(`${field} must be a integer`);
|
|
19
|
+
if (typeof options.min === 'number' && value < options.min)
|
|
20
|
+
return failed(`${field} must >= ${options.min}`);
|
|
21
|
+
if (typeof options.max === 'number' && value > options.max)
|
|
22
|
+
return failed(`${field} must <= ${options.max}`);
|
|
23
|
+
}
|
|
24
|
+
return success(value);
|
|
25
|
+
})(options);
|
|
26
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type CommonOptions, type Validator, type Validated } from './base.js';
|
|
2
|
+
/** 验证有明确键值对结构的对象 */
|
|
3
|
+
export interface StructOptions extends CommonOptions {
|
|
4
|
+
/** 定义对象结构,及各个值的验证规则 */
|
|
5
|
+
struct: Record<string, Validator<unknown, CommonOptions>>;
|
|
6
|
+
}
|
|
7
|
+
type StructValues<Options extends StructOptions> = {
|
|
8
|
+
[Key in keyof Options['struct']]: Options['struct'][Key] extends Validator<infer Value, infer Options> ? Validated<Value, Options> : never;
|
|
9
|
+
};
|
|
10
|
+
export declare function getStructValidator<const Options extends StructOptions>(options: Options): Validator<StructValues<Options>, Options>;
|
|
11
|
+
/**
|
|
12
|
+
* 验证有任意多个 key,但值的类型固定的对象
|
|
13
|
+
*/
|
|
14
|
+
export interface RecordOptions extends CommonOptions {
|
|
15
|
+
/** 验证单个值 */
|
|
16
|
+
record: Validator<unknown, CommonOptions>;
|
|
17
|
+
/** 对象至少要有几项 */
|
|
18
|
+
min?: number;
|
|
19
|
+
/** 对象最多有几项 */
|
|
20
|
+
max?: number;
|
|
21
|
+
}
|
|
22
|
+
type RecordValues<Options extends RecordOptions> = Record<string, Validated<Options extends {
|
|
23
|
+
record: Validator<infer T, CommonOptions>;
|
|
24
|
+
} ? T : never, Options extends {
|
|
25
|
+
record: Validator<unknown, infer T>;
|
|
26
|
+
} ? T : never>>;
|
|
27
|
+
export declare function getRecordValidator<Options extends RecordOptions>(options: Options): Validator<RecordValues<Options>, Options>;
|
|
28
|
+
export {};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import isPlainObject from 'lodash/isPlainObject.js';
|
|
2
|
+
import { success, failed } from '../lang/index.js';
|
|
3
|
+
import { getValidatorGenerator, } from './base.js';
|
|
4
|
+
export function getStructValidator(options) {
|
|
5
|
+
return getValidatorGenerator(function validate(field, value, options) {
|
|
6
|
+
if (!isPlainObject(value))
|
|
7
|
+
return failed(`${field} should be a plain object`);
|
|
8
|
+
const formatted = {};
|
|
9
|
+
for (const [key, itemValidator] of Object.entries(options.struct)) {
|
|
10
|
+
const itemResult = itemValidator(`${field}["${key}"]`, value[key]);
|
|
11
|
+
if (itemResult.success) {
|
|
12
|
+
if (itemResult.data !== undefined)
|
|
13
|
+
formatted[key] = itemResult.data;
|
|
14
|
+
}
|
|
15
|
+
else {
|
|
16
|
+
return itemResult;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return success(formatted);
|
|
20
|
+
})(options);
|
|
21
|
+
}
|
|
22
|
+
export function getRecordValidator(options) {
|
|
23
|
+
return getValidatorGenerator(function validate(field, value, options) {
|
|
24
|
+
if (!isPlainObject(value))
|
|
25
|
+
return failed(`${field} should be a plain object`);
|
|
26
|
+
const formatted = {};
|
|
27
|
+
for (const [key, itemValue] of Object.entries(value)) {
|
|
28
|
+
// record 场景下,值为 undefined 的项目视为不存在,不保留在验证结果里,
|
|
29
|
+
// 不然一些因为不想赋值而填充了 undefined 值的项目可能意外触发验证失败,或意外得到了默认值。
|
|
30
|
+
// (因此 validator 的 required 选项和 defaults 选项也没有意义了)
|
|
31
|
+
if (itemValue === undefined)
|
|
32
|
+
continue;
|
|
33
|
+
const itemResult = options.record(`${field}["${key}"]`, itemValue);
|
|
34
|
+
if (itemResult.success) {
|
|
35
|
+
if (itemResult.data !== undefined)
|
|
36
|
+
formatted[key] = itemResult.data;
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
return itemResult;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const length = Object.keys(formatted).length;
|
|
43
|
+
if (typeof options.min === 'number' && length < options.min)
|
|
44
|
+
return failed(`size of ${field} should >= ${options.min}`);
|
|
45
|
+
if (typeof options.max === 'number' && length > options.max)
|
|
46
|
+
return failed(`size of ${field} should <= ${options.max}`);
|
|
47
|
+
return success(formatted);
|
|
48
|
+
})(options);
|
|
49
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type CommonOptions, type Validator } from './base.js';
|
|
2
|
+
/** 要求返回值通过其中一个验证器的检查 */
|
|
3
|
+
export interface OneOfOptions extends CommonOptions {
|
|
4
|
+
/** 验证数组各元素 */
|
|
5
|
+
validators: Validator<unknown, CommonOptions>[];
|
|
6
|
+
}
|
|
7
|
+
export type OneOfValue<Options extends OneOfOptions> = Options extends {
|
|
8
|
+
validators: Validator<infer T, CommonOptions>[];
|
|
9
|
+
} ? T : never;
|
|
10
|
+
export declare function getOneOfValidator<const Options extends OneOfOptions>(options?: Options): Validator<OneOfValue<Options>, Options>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { failed } from '../lang/index.js';
|
|
2
|
+
import { getValidatorGenerator, } from './base.js';
|
|
3
|
+
export function getOneOfValidator(options = {}) {
|
|
4
|
+
return getValidatorGenerator(function validate(field, value) {
|
|
5
|
+
const errors = [];
|
|
6
|
+
for (const validator of options.validators) {
|
|
7
|
+
const result = validator(field, value);
|
|
8
|
+
if (result.success)
|
|
9
|
+
return result;
|
|
10
|
+
else
|
|
11
|
+
errors.push(result.message);
|
|
12
|
+
}
|
|
13
|
+
return failed(`${field} do not match any valid format:\n- ` + errors.join('\n- '));
|
|
14
|
+
})(options);
|
|
15
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type CommonOptions } from './base.js';
|
|
2
|
+
export interface StringOptions extends CommonOptions<string> {
|
|
3
|
+
/** 字符串最小长度。defaults='' 时默认为 0,否则默认为 1 */
|
|
4
|
+
min?: number;
|
|
5
|
+
/** 字符串最大长度。 */
|
|
6
|
+
max?: number;
|
|
7
|
+
/** 字符串需匹配此正则,也可传入关键词使用预置的正则。正则通常应以 ^ 和 $ 开头结尾。 */
|
|
8
|
+
pattern?: RegExp | 'uuid' | 'mobile';
|
|
9
|
+
/**
|
|
10
|
+
* 指定一个数组或 TypeScript enum,字段值必须在此 enum 之中。
|
|
11
|
+
* 若指定,前几个选项将不再生效。
|
|
12
|
+
*/
|
|
13
|
+
choices?: string[] | Record<string, string>;
|
|
14
|
+
/** 验证之前,是否先清除两侧空白字符 @default true */
|
|
15
|
+
trim?: boolean;
|
|
16
|
+
}
|
|
17
|
+
export type StringValueWithChoices<Options extends StringOptions> = Options extends {
|
|
18
|
+
choices: (infer T)[];
|
|
19
|
+
} ? T : Options extends {
|
|
20
|
+
choices: Record<string, infer T>;
|
|
21
|
+
} ? T : string;
|
|
22
|
+
export declare function getStringValidator<const Options extends StringOptions>(options?: Options): import("./base.js").Validator<StringValueWithChoices<Options>, Options>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { success, failed } from '../lang/index.js';
|
|
2
|
+
import { getValidatorGenerator } from './base.js';
|
|
3
|
+
export function getStringValidator(options = {}) {
|
|
4
|
+
return getValidatorGenerator(function validate(field, value) {
|
|
5
|
+
if (typeof value !== 'string')
|
|
6
|
+
return failed(`${field} must be a string`);
|
|
7
|
+
const trim = options.trim ?? true;
|
|
8
|
+
const formatted = trim ? value.trim() : value;
|
|
9
|
+
if ('choices' in options && options.choices) {
|
|
10
|
+
const validValues = Array.isArray(options.choices)
|
|
11
|
+
? options.choices
|
|
12
|
+
: Object.values(options.choices);
|
|
13
|
+
if (!validValues.includes(formatted))
|
|
14
|
+
return failed(`${field} can only be one of ${validValues.join(', ')}.`);
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
const { min = options.defaults === '' ? 0 : 1, max, pattern } = options;
|
|
18
|
+
if (typeof min === 'number' && formatted.length < min)
|
|
19
|
+
return failed(`${field}'s length must >= ${min}`);
|
|
20
|
+
if (typeof max === 'number' && formatted.length > max)
|
|
21
|
+
return failed(`${field}'s length must <= ${max}`);
|
|
22
|
+
if (pattern !== undefined) {
|
|
23
|
+
if (pattern instanceof RegExp && !pattern.exec(formatted))
|
|
24
|
+
return failed(`${field} does not match the pattern`);
|
|
25
|
+
if (pattern === 'mobile' && !/^1\d{10}$/.test(formatted))
|
|
26
|
+
return failed(`${field} is not a valid mobile number`);
|
|
27
|
+
if (pattern === 'uuid') {
|
|
28
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(formatted))
|
|
29
|
+
return failed(`${field} is not a valid uuid`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return success(formatted);
|
|
34
|
+
})(options);
|
|
35
|
+
}
|
package/README.md
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
# Common JavaScript Utils
|
|
2
|
-
|
|
3
|
-
## 依赖
|
|
4
|
-
|
|
5
|
-
- `init-dayjs` 依赖 `dayjs`
|
|
6
|
-
- `/logging` 依赖 `dayjs`,且会自动引用 `init-dayjs`
|
|
7
|
-
- `/env-node/logging` 依赖 `chalk`
|
|
8
|
-
- `/env-react/emotion` 依赖 `@emotion/*` 系列类库和 `react`
|
|
9
|
-
- `/env-service/prisma` 依赖 `@prisma/client`
|
|
10
|
-
- `/env-service/env-reader` 依赖 `dotenv`
|