@anjianshi/utils 2.5.0 → 2.7.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/README.md +10 -0
- package/eslint.config.cjs +33 -0
- package/package.json +26 -15
- package/publish-prepare.cjs +16 -0
- package/src/env-browser/device.ts +62 -0
- package/src/env-browser/global.ts +21 -0
- package/src/env-browser/load-script.ts +13 -0
- package/src/env-browser/logging.ts +58 -0
- package/src/env-browser/manage-vconsole.ts +54 -0
- package/src/env-node/crypto-random.ts +30 -0
- package/src/env-node/fs.ts +50 -0
- package/src/env-node/index.ts +6 -0
- package/src/env-node/logging/handlers.ts +190 -0
- package/src/env-node/logging/index.ts +16 -0
- package/src/env-node/safe-request.ts +66 -0
- package/src/env-react/emotion.tsx +42 -0
- package/src/env-service/controllers.ts +93 -0
- package/src/env-service/env-reader.ts +141 -0
- package/src/env-service/index.ts +6 -0
- package/src/env-service/prisma/adapt-logging.ts +39 -0
- package/src/env-service/prisma/extensions/exist.ts +21 -0
- package/src/env-service/prisma/extensions/find-and-count.ts +24 -0
- package/src/env-service/prisma/extensions/soft-delete.ts +162 -0
- package/src/env-service/prisma/extensions/with-transaction.ts +65 -0
- package/src/env-service/prisma/index.ts +6 -0
- package/src/env-service/prisma/transaction-contexted.ts +80 -0
- package/src/env-service/redis-cache.ts +142 -0
- package/src/env-service/tasks.ts +45 -0
- package/src/index.ts +3 -0
- package/src/init-dayjs.ts +8 -0
- package/src/lang/async.ts +47 -0
- package/src/lang/color.ts +119 -0
- package/src/lang/index.ts +7 -0
- package/src/lang/may-success.ts +57 -0
- package/src/lang/object.ts +39 -0
- package/src/lang/random.ts +25 -0
- package/src/lang/string.ts +95 -0
- package/src/lang/time.ts +19 -0
- package/{lang/types.d.ts → src/lang/types.ts} +43 -23
- package/src/logging/adapt.ts +49 -0
- package/src/logging/formatters.ts +23 -0
- package/src/logging/index.ts +106 -0
- package/src/md5.ts +318 -0
- package/src/url.ts +185 -0
- package/src/validators/array.ts +97 -0
- package/src/validators/base.ts +145 -0
- package/src/validators/boolean.ts +21 -0
- package/src/validators/datetime.ts +39 -0
- package/src/validators/factory.ts +244 -0
- package/src/validators/index.ts +9 -0
- package/src/validators/number.ts +54 -0
- package/src/validators/object.ts +101 -0
- package/src/validators/one-of.ts +33 -0
- package/src/validators/string.ts +72 -0
- package/env-browser/device.d.ts +0 -24
- package/env-browser/device.js +0 -50
- package/env-browser/global.d.ts +0 -10
- package/env-browser/global.js +0 -15
- package/env-browser/load-script.d.ts +0 -5
- package/env-browser/load-script.js +0 -13
- package/env-browser/logging.d.ts +0 -18
- package/env-browser/logging.js +0 -49
- package/env-browser/manage-vconsole.d.ts +0 -16
- package/env-browser/manage-vconsole.js +0 -38
- package/env-node/crypto-random.d.ts +0 -13
- package/env-node/crypto-random.js +0 -28
- package/env-node/fs.d.ts +0 -19
- package/env-node/fs.js +0 -48
- package/env-node/index.d.ts +0 -5
- package/env-node/index.js +0 -5
- package/env-node/logging/handlers.d.ts +0 -58
- package/env-node/logging/handlers.js +0 -154
- package/env-node/logging/index.d.ts +0 -11
- package/env-node/logging/index.js +0 -14
- package/env-react/emotion.d.ts +0 -20
- package/env-react/emotion.jsx +0 -34
- package/env-service/controllers.d.ts +0 -30
- package/env-service/controllers.js +0 -41
- package/env-service/env-reader.d.ts +0 -55
- package/env-service/env-reader.js +0 -79
- package/env-service/index.d.ts +0 -6
- package/env-service/index.js +0 -6
- package/env-service/prisma/adapt-logging.d.ts +0 -21
- package/env-service/prisma/adapt-logging.js +0 -30
- package/env-service/prisma/extensions/exist.d.ts +0 -10
- package/env-service/prisma/extensions/exist.js +0 -16
- package/env-service/prisma/extensions/find-and-count.d.ts +0 -7
- package/env-service/prisma/extensions/find-and-count.js +0 -19
- package/env-service/prisma/extensions/soft-delete.d.ts +0 -52
- package/env-service/prisma/extensions/soft-delete.js +0 -123
- package/env-service/prisma/extensions/with-transaction.d.ts +0 -9
- package/env-service/prisma/extensions/with-transaction.js +0 -54
- package/env-service/prisma/index.d.ts +0 -6
- package/env-service/prisma/index.js +0 -6
- package/env-service/prisma/transaction-contexted.d.ts +0 -11
- package/env-service/prisma/transaction-contexted.js +0 -52
- package/env-service/redis-cache.d.ts +0 -39
- package/env-service/redis-cache.js +0 -116
- package/env-service/tasks.d.ts +0 -12
- package/env-service/tasks.js +0 -37
- package/index.d.ts +0 -3
- package/index.js +0 -3
- package/init-dayjs.d.ts +0 -2
- package/init-dayjs.js +0 -7
- package/lang/async.d.ts +0 -19
- package/lang/async.js +0 -34
- package/lang/index.d.ts +0 -7
- package/lang/index.js +0 -7
- package/lang/may-success.d.ts +0 -40
- package/lang/may-success.js +0 -27
- package/lang/object.d.ts +0 -5
- package/lang/object.js +0 -31
- package/lang/random.d.ts +0 -13
- package/lang/random.js +0 -24
- package/lang/string.d.ts +0 -29
- package/lang/string.js +0 -92
- package/lang/time.d.ts +0 -10
- package/lang/time.js +0 -18
- package/lang/types.js +0 -28
- package/logging/adapt.d.ts +0 -10
- package/logging/adapt.js +0 -43
- package/logging/formatters.d.ts +0 -10
- package/logging/formatters.js +0 -22
- package/logging/index.d.ts +0 -45
- package/logging/index.js +0 -90
- package/md5.d.ts +0 -30
- package/md5.js +0 -308
- package/url.d.ts +0 -77
- package/url.js +0 -149
- package/validators/array.d.ts +0 -30
- package/validators/array.js +0 -47
- package/validators/base.d.ts +0 -82
- package/validators/base.js +0 -42
- package/validators/boolean.d.ts +0 -3
- package/validators/boolean.js +0 -22
- package/validators/factory.d.ts +0 -66
- package/validators/factory.js +0 -109
- package/validators/index.d.ts +0 -8
- package/validators/index.js +0 -8
- package/validators/number.d.ts +0 -19
- package/validators/number.js +0 -26
- package/validators/object.d.ts +0 -28
- package/validators/object.js +0 -49
- package/validators/oneOf.d.ts +0 -10
- package/validators/oneOf.js +0 -15
- package/validators/string.d.ts +0 -22
- package/validators/string.js +0 -35
package/src/url.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* URL 工具函数
|
|
3
|
+
* 部分灵感来自:https://www.npmjs.com/package/qs
|
|
4
|
+
*
|
|
5
|
+
* [名词定义]
|
|
6
|
+
* query: 指 a=1&b=2 格式的“查询字符串”或此类字符串的解析结果。
|
|
7
|
+
* search: URL 中的 search 部分,与 location.search 一致,空字符串或以 '?' 开头。
|
|
8
|
+
* hash: URL 中的 hash 部分,与 location.hash 一直,空字符串或以 '#' 开头。
|
|
9
|
+
*/
|
|
10
|
+
import isPlainObject from 'lodash/isPlainObject.js'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 从 URL 中解析出 query 对象
|
|
14
|
+
* 注意:不带 ? 号的纯 query 内容需手动加上 ? 再传入。
|
|
15
|
+
*
|
|
16
|
+
* [array]
|
|
17
|
+
* 是否把重复出现的 key 保存为数组(默认不开启)
|
|
18
|
+
* a=1&a=2 => { a: [1,2] }
|
|
19
|
+
*
|
|
20
|
+
* [loose]
|
|
21
|
+
* 是否开启“宽松模式”(默认不开启)
|
|
22
|
+
* 1. hash 里的内容也会被解析,以兼容拼接错误的 URL(把 query 拼到了 hash 后面)。
|
|
23
|
+
* 2. 出现多个 ? 符号时,会把 ? 也当做 & 分隔符(index.html?a=1&b=2?c=3)
|
|
24
|
+
*
|
|
25
|
+
* [decode]
|
|
26
|
+
* 是否对 query 值进行 decode(默认开启)
|
|
27
|
+
*/
|
|
28
|
+
function parseQuery(url: string, options?: { array?: false, loose?: boolean, decode?: boolean }): Record<string, string> // prettier-ignore
|
|
29
|
+
function parseQuery(url: string, options: { array: true, loose?: boolean, decode?: boolean }): Record<string, string | string[]> // prettier-ignore
|
|
30
|
+
function parseQuery(
|
|
31
|
+
url: string,
|
|
32
|
+
options?: { array?: boolean; loose?: boolean; decode?: boolean },
|
|
33
|
+
): Record<string, string | string[]> {
|
|
34
|
+
const { array = false, loose = false, decode = true } = options ?? {}
|
|
35
|
+
|
|
36
|
+
// 正常状态下,将仅剩 a=1&b=1(即不会再有 ? 和 #);loose 模式下,可能为 a=1&b=2#c=3?d=4
|
|
37
|
+
const queryString = (loose ? /(\?|#)(.+)/ : /(\?)(.+?)(#|$)/).exec(url)?.[2] ?? ''
|
|
38
|
+
if (!queryString) return {}
|
|
39
|
+
|
|
40
|
+
const query: Record<string, string | string[]> = {}
|
|
41
|
+
const reg = /([^#?&]*)=([^#?&]*)/g
|
|
42
|
+
let re = reg.exec(queryString)
|
|
43
|
+
while (re) {
|
|
44
|
+
const [name, rawValue] = [re[1]!, re[2]!] as [string, string]
|
|
45
|
+
const value = decode ? safeDecode(rawValue) : rawValue
|
|
46
|
+
if (array && query[name] !== undefined) {
|
|
47
|
+
const prev = query[name]
|
|
48
|
+
query[name] = Array.isArray(prev) ? [...prev, value] : [prev, value]
|
|
49
|
+
} else {
|
|
50
|
+
query[name] = value
|
|
51
|
+
}
|
|
52
|
+
re = reg.exec(queryString)
|
|
53
|
+
}
|
|
54
|
+
return query
|
|
55
|
+
}
|
|
56
|
+
export { parseQuery }
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 把对象合并成 query string。
|
|
60
|
+
* - 支持字符串、数值、布尔值、数组。
|
|
61
|
+
* - 布尔值会替换成 0 和 1。
|
|
62
|
+
* - 数组会多次赋值:{ a: [1,2,3] } => 'a=1&a=2&a=3',不支持嵌套数组
|
|
63
|
+
* - encode 为 true 时会对 value 执行 encodeURIComponent(默认为 true)
|
|
64
|
+
*/
|
|
65
|
+
export type StringifyVal = string | number | boolean
|
|
66
|
+
export type StringifyQuery = Record<string, StringifyVal | StringifyVal[] | undefined>
|
|
67
|
+
export function stringifyQuery(obj: StringifyQuery, encode = true) {
|
|
68
|
+
if (!isPlainObject(obj)) return ''
|
|
69
|
+
return (
|
|
70
|
+
Object.entries(obj)
|
|
71
|
+
// 过滤值为 undefined 的项目,使其完全不出现在最终的 query 中
|
|
72
|
+
.filter((entry): entry is [string, StringifyVal | StringifyVal[]] => entry[1] !== undefined)
|
|
73
|
+
.map(([name, value]) => stringifyQueryItem(name, value, encode))
|
|
74
|
+
.join('&')
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
function stringifyQueryItem(
|
|
78
|
+
name: string,
|
|
79
|
+
value: StringifyVal | StringifyVal[],
|
|
80
|
+
encode: boolean,
|
|
81
|
+
): string {
|
|
82
|
+
if (Array.isArray(value))
|
|
83
|
+
return value.map(subValue => stringifyQueryItem(name, subValue, encode)).join('&')
|
|
84
|
+
if (typeof value === 'boolean') value = value ? '1' : '0'
|
|
85
|
+
if (typeof value === 'number') value = value.toString()
|
|
86
|
+
if (encode) value = encodeURIComponent(value)
|
|
87
|
+
return `${name}=${value}`
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 拆分 URL 的各个部分
|
|
92
|
+
*
|
|
93
|
+
* bare 为 true,则 search 不带 '?',hash 不带 '#'
|
|
94
|
+
* 否则和 location.search / hash 一样
|
|
95
|
+
* (默认为 true)
|
|
96
|
+
*/
|
|
97
|
+
export function splitUrl(url: string, bare = true): { base: string; search: string; hash: string } {
|
|
98
|
+
let hashIndex = url.indexOf('#')
|
|
99
|
+
if (hashIndex === -1) hashIndex = url.length
|
|
100
|
+
const bareHash = url.slice(hashIndex + 1)
|
|
101
|
+
|
|
102
|
+
let searchIndex = url.slice(0, hashIndex).indexOf('?')
|
|
103
|
+
if (searchIndex === -1) searchIndex = hashIndex
|
|
104
|
+
const bareSearch = url.slice(searchIndex + 1, hashIndex)
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
base: url.slice(0, searchIndex),
|
|
108
|
+
search: bare ? bareSearch : bareSearch ? '?' + bareSearch : '',
|
|
109
|
+
hash: bare ? bareHash : bareHash ? '#' + bareHash : '',
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 把 query 和 hash 内容合并到 url 上
|
|
115
|
+
*
|
|
116
|
+
* query object 与现有 search 合并,替换同名项(值为数组的,用新数组代替老的,不会合并数组)
|
|
117
|
+
* hash string 带不带开头的 '#' 皆可。会代替 url 已有的 hash。
|
|
118
|
+
*/
|
|
119
|
+
export function combineUrl(origUrl: string, query: StringifyQuery = {}, hash = '') {
|
|
120
|
+
if (hash.startsWith('#')) hash = hash.slice(1)
|
|
121
|
+
|
|
122
|
+
// 拆分原 url 的 search、hash
|
|
123
|
+
const { base, search: origSearch, hash: origHash } = splitUrl(origUrl)
|
|
124
|
+
|
|
125
|
+
// 拼接新 URL
|
|
126
|
+
let newUrl = base
|
|
127
|
+
const newSearch = stringifyQuery({ ...parseQuery(origSearch), ...query })
|
|
128
|
+
const newHash = hash || origHash
|
|
129
|
+
if (newSearch) newUrl += `?${newSearch}`
|
|
130
|
+
if (newHash) newUrl += `#${newHash}`
|
|
131
|
+
return newUrl
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 移除路径中所有非必须的 "/"
|
|
136
|
+
* 清理后的字符串只有这几种可能的格式:''、'abc'、'abc/def'
|
|
137
|
+
* 例如 /abc/def 和 abc/def/ 都会变成 abc/def
|
|
138
|
+
*
|
|
139
|
+
* 注意:此操作不会统一大小写,因此不保证处理后两个字符串在代码层面全等(a === b)
|
|
140
|
+
*/
|
|
141
|
+
export function clearSlash(path: string) {
|
|
142
|
+
if (path.startsWith('/')) path = path.slice(1)
|
|
143
|
+
if (path.endsWith('/')) path = path.slice(0, -1)
|
|
144
|
+
path = path.replace(/\/+/g, '/')
|
|
145
|
+
return path
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 合并几段路径,保证合并处只有一个斜杠
|
|
150
|
+
*/
|
|
151
|
+
export function joinPath(...nodes: string[]) {
|
|
152
|
+
// - node 为 '' 时忽略 node
|
|
153
|
+
// - path 可能的格式:'' 'a' 'a/' ‘/a/'
|
|
154
|
+
// - path 为 '',则 node 开头 '/' 保持原样
|
|
155
|
+
// - 否则,根据 path 结尾有没有 '/',决定 node 开头带不带 '/'
|
|
156
|
+
// - node 开头、结尾若有多个 '/' 均替换成单个
|
|
157
|
+
return nodes.reduce((path, node) => {
|
|
158
|
+
if (!node) return path
|
|
159
|
+
type Matched = RegExpExecArray & { 1: string; 2: string; 3: string }
|
|
160
|
+
const [, origPrefix, content, origSuffix] = /^(\/*)(.*?)(\/*)$/.exec(node)! as Matched
|
|
161
|
+
const prefix = (path === '' ? !!origPrefix : !path.endsWith('/')) ? '/' : ''
|
|
162
|
+
const suffix = origSuffix ? '/' : ''
|
|
163
|
+
const result = `${path}${prefix}${content}${suffix}`
|
|
164
|
+
return result
|
|
165
|
+
}, '')
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* decodeURIComponent() 对于不规范编码的字符串可能会报错(例如字符串里出现了“%”)
|
|
170
|
+
* 用此函数代替可避免此问题
|
|
171
|
+
*/
|
|
172
|
+
export function safeDecode(content: string) {
|
|
173
|
+
try {
|
|
174
|
+
return decodeURIComponent(content)
|
|
175
|
+
} catch (e) {
|
|
176
|
+
return content
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 将 URL 中的 http:// 协议改成 https://
|
|
182
|
+
*/
|
|
183
|
+
export function ensureHttps(url: string | undefined) {
|
|
184
|
+
return url?.replace(/http:\/\//g, 'https://')
|
|
185
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { success, failed } from '../lang/index.js'
|
|
2
|
+
import {
|
|
3
|
+
getValidatorGenerator,
|
|
4
|
+
type CommonOptions,
|
|
5
|
+
type Validator,
|
|
6
|
+
type Validated,
|
|
7
|
+
type PrimitiveType,
|
|
8
|
+
} from './base.js'
|
|
9
|
+
|
|
10
|
+
/** 验证元素数量任意、元素类型相同的数组 */
|
|
11
|
+
export interface ArrayOptions extends CommonOptions {
|
|
12
|
+
/** 验证数组各元素 */
|
|
13
|
+
item: Validator<unknown, CommonOptions>
|
|
14
|
+
|
|
15
|
+
/** 数组最小长度 */
|
|
16
|
+
min?: number
|
|
17
|
+
|
|
18
|
+
/** 数组最大长度 */
|
|
19
|
+
max?: number
|
|
20
|
+
|
|
21
|
+
/** 是否对数组元素进行去重 @defaults false */
|
|
22
|
+
unique?: boolean
|
|
23
|
+
|
|
24
|
+
/** 如果传入的不是数组,是否要将其视为数组内元素,包裹成数组 */
|
|
25
|
+
toArray?: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type ArrayValues<Options extends ArrayOptions> = Validated<
|
|
29
|
+
Options extends { item: Validator<infer T, CommonOptions> } ? T : never,
|
|
30
|
+
Options extends { item: Validator<unknown, infer T> } ? T : never
|
|
31
|
+
>[]
|
|
32
|
+
|
|
33
|
+
export function getArrayValidator<Options extends ArrayOptions>(options: Options) {
|
|
34
|
+
return getValidatorGenerator<ArrayValues<Options>, Options>(
|
|
35
|
+
function validate(field, value, options) {
|
|
36
|
+
if (!Array.isArray(value)) {
|
|
37
|
+
if (options.toArray) value = [value as PrimitiveType]
|
|
38
|
+
else return failed(`${field} should be an array`)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let formatted = []
|
|
42
|
+
if (typeof options.min === 'number' && value.length < options.min)
|
|
43
|
+
return failed(`array ${field}'s length should >= ${options.min}`)
|
|
44
|
+
|
|
45
|
+
if (typeof options.max === 'number' && value.length > options.max)
|
|
46
|
+
return failed(`array ${field}'s length should <= ${options.max}`)
|
|
47
|
+
|
|
48
|
+
const itemValidator = options.item
|
|
49
|
+
for (let i = 0; i < value.length; i++) {
|
|
50
|
+
const itemResult = itemValidator(`${field}[${i}]`, value[i])
|
|
51
|
+
if (itemResult.success) formatted.push(itemResult.data)
|
|
52
|
+
else return itemResult
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (options.unique === true) formatted = [...new Set(formatted)]
|
|
56
|
+
|
|
57
|
+
return success(formatted as ArrayValues<Options>)
|
|
58
|
+
},
|
|
59
|
+
)(options)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ---------------------------------------------------
|
|
63
|
+
|
|
64
|
+
/** 验证元素数量固定、类型可以不同的数组 */
|
|
65
|
+
export interface TupleOptions extends CommonOptions {
|
|
66
|
+
/** 验证数组各元素(validator 与元素一一对应) */
|
|
67
|
+
tuple: Validator<unknown, CommonOptions>[]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type TupleValues<Options extends TupleOptions> = {
|
|
71
|
+
[Key in keyof Options['tuple']]: Options['tuple'][Key] extends Validator<
|
|
72
|
+
infer Value,
|
|
73
|
+
infer Options
|
|
74
|
+
>
|
|
75
|
+
? Validated<Value, Options>
|
|
76
|
+
: never
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function getTupleValidator<const Options extends TupleOptions>(options: Options) {
|
|
80
|
+
return getValidatorGenerator<TupleValues<Options>, Options>(
|
|
81
|
+
function validate(field, value, options) {
|
|
82
|
+
if (!Array.isArray(value)) return failed(`${field} should be an array`)
|
|
83
|
+
if (value.length > options.tuple.length)
|
|
84
|
+
return failed(`${field} should be a tuple with ${options.tuple.length} items`)
|
|
85
|
+
|
|
86
|
+
const formatted = []
|
|
87
|
+
// 这种情况不能遍历 value,因为它的长度可能小于 opt.tuple
|
|
88
|
+
for (let i = 0; i < options.tuple.length; i++) {
|
|
89
|
+
const itemValidator = options.tuple[i]!
|
|
90
|
+
const itemResult = itemValidator(`${field}[${i}]`, value[i])
|
|
91
|
+
if (itemResult.success) formatted.push(itemResult.data)
|
|
92
|
+
else return itemResult
|
|
93
|
+
}
|
|
94
|
+
return success(formatted as TupleValues<Options>)
|
|
95
|
+
},
|
|
96
|
+
)(options)
|
|
97
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { success, failed, type MaySuccess } from '../lang/index.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 支持传入进行验证的值类型
|
|
5
|
+
*/
|
|
6
|
+
export type AllowedInputValue = PrimitiveType | null | undefined
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* JavaScript 基础值类型
|
|
10
|
+
*/
|
|
11
|
+
export type PrimitiveType =
|
|
12
|
+
| string
|
|
13
|
+
| boolean
|
|
14
|
+
| number
|
|
15
|
+
| PrimitiveType[]
|
|
16
|
+
| [...PrimitiveType[]]
|
|
17
|
+
| { [key: string]: PrimitiveType }
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* validator 通用参数
|
|
21
|
+
*/
|
|
22
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
23
|
+
export interface CommonOptions<Value = any> {
|
|
24
|
+
/** 是否允许 null 值 @default false */
|
|
25
|
+
null?: boolean
|
|
26
|
+
|
|
27
|
+
/** 字段是否必须有值(不能是 undefined) @default true */
|
|
28
|
+
required?: boolean
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 默认值,字段无值(或值为 undefined)时生效,值为 null 不会生效。
|
|
32
|
+
* 指定后 required 选项将失去作用。
|
|
33
|
+
*/
|
|
34
|
+
defaults?: Value
|
|
35
|
+
|
|
36
|
+
custom?: (input: Value) => MaySuccess<Value>
|
|
37
|
+
|
|
38
|
+
// 用来保证传入定制过的 Options 时 TypeScript 不会报不匹配的错
|
|
39
|
+
// 例如不加这句时, `{ other: boolean } extends CommonOptions` 是会被 TypeScript 判定为不匹配的:
|
|
40
|
+
// error TS2559: Type '{ other: boolean }' has no properties in common with type 'CommonOptions<unknown>'
|
|
41
|
+
// 此解决办法来自:https://mariusschulz.com/blog/weak-type-detection-in-typescript
|
|
42
|
+
[key: string]: unknown
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 补全了的 Options
|
|
47
|
+
*/
|
|
48
|
+
type FullfiledOptions<Options extends Partial<CommonOptions>> = Omit<
|
|
49
|
+
Options,
|
|
50
|
+
keyof CommonOptions
|
|
51
|
+
> & {
|
|
52
|
+
null: Options['null'] extends true ? true : false
|
|
53
|
+
required: Options['required'] extends false ? false : true
|
|
54
|
+
defaults: Options extends { defaults: infer T } ? T : undefined
|
|
55
|
+
custom: Options extends { custom: infer T } ? T : undefined
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 验证完成后能得到的值类型
|
|
60
|
+
*/
|
|
61
|
+
export type Validated<Value, InputOptions extends CommonOptions> =
|
|
62
|
+
FullfiledOptions<InputOptions> extends { defaults: undefined }
|
|
63
|
+
? FullfiledOptions<InputOptions> extends { required: false; null: false }
|
|
64
|
+
? Value | undefined
|
|
65
|
+
: FullfiledOptions<InputOptions> extends { required: false; null: true }
|
|
66
|
+
? Value | undefined | null
|
|
67
|
+
: FullfiledOptions<InputOptions> extends { required: true; null: false }
|
|
68
|
+
? Value
|
|
69
|
+
: FullfiledOptions<InputOptions> extends { required: true; null: true }
|
|
70
|
+
? Value | null
|
|
71
|
+
: Value
|
|
72
|
+
: FullfiledOptions<InputOptions> extends {
|
|
73
|
+
defaults: infer T
|
|
74
|
+
null: false
|
|
75
|
+
}
|
|
76
|
+
? Value | T
|
|
77
|
+
: FullfiledOptions<InputOptions> extends { defaults: infer T; null: true }
|
|
78
|
+
? Value | T | null
|
|
79
|
+
: never
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 最终生成的 validator 函数类型
|
|
83
|
+
*/
|
|
84
|
+
export interface Validator<Value, InputOptions extends CommonOptions> {
|
|
85
|
+
(input: AllowedInputValue): MaySuccess<Validated<Value, InputOptions>>
|
|
86
|
+
(field: string, input: AllowedInputValue): MaySuccess<Validated<Value, InputOptions>>
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// -----------------------------------
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 返回支持指定格式的 options、并按照传入的逻辑进行验证的 validator 的生成器。
|
|
93
|
+
* 对 CommonOptions 相关内容的验证以自动包含在里面,只需要传入额外的验证逻辑即可。
|
|
94
|
+
*/
|
|
95
|
+
export function getValidatorGenerator<Value, Options extends CommonOptions>(
|
|
96
|
+
validate: (
|
|
97
|
+
field: string,
|
|
98
|
+
input: PrimitiveType | Validated<Value, Options>,
|
|
99
|
+
options: Options,
|
|
100
|
+
) => MaySuccess<Value>,
|
|
101
|
+
) {
|
|
102
|
+
return function validatorGenerator<const InputOptions extends Options>(
|
|
103
|
+
inputOptions: InputOptions,
|
|
104
|
+
): Validator<Value, InputOptions> {
|
|
105
|
+
type Return = MaySuccess<Validated<Value, InputOptions>>
|
|
106
|
+
function validator(input: AllowedInputValue): Return
|
|
107
|
+
function validator(field: string, input: AllowedInputValue): Return
|
|
108
|
+
function validator(field: string | AllowedInputValue, input?: AllowedInputValue) {
|
|
109
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
110
|
+
const { null: allowNull = false, required = true, defaults, custom } = inputOptions
|
|
111
|
+
|
|
112
|
+
if (typeof field !== 'string') {
|
|
113
|
+
input = field
|
|
114
|
+
field = 'value'
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
let value: AllowedInputValue | Validated<Value, Options> = input
|
|
118
|
+
if (typeof value === 'undefined') {
|
|
119
|
+
if (typeof defaults !== 'undefined') {
|
|
120
|
+
value = defaults as Validated<Value, Options>
|
|
121
|
+
} else if (required) {
|
|
122
|
+
return failed(`${field} is required`)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (value === null && !allowNull) return failed(`${field} cannot be null`)
|
|
126
|
+
if (value === null || value === undefined) return success(value)
|
|
127
|
+
|
|
128
|
+
const validated = validate(field, value, inputOptions)
|
|
129
|
+
return validated.success && custom ? custom(validated.data) : validated
|
|
130
|
+
}
|
|
131
|
+
return validator
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// -----------------------------------
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 返回只进行基本检查,不带定制的验证逻辑的 validator。
|
|
139
|
+
* 同时也是定制 validator 最小化实现的例子。
|
|
140
|
+
*/
|
|
141
|
+
export const getAnyValidator = getValidatorGenerator<unknown, CommonOptions>(
|
|
142
|
+
function validate(field, input) {
|
|
143
|
+
return success(input)
|
|
144
|
+
},
|
|
145
|
+
)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { success, failed } from '../lang/index.js'
|
|
2
|
+
import { getValidatorGenerator, type CommonOptions } from './base.js'
|
|
3
|
+
|
|
4
|
+
export type BooleanOptions = CommonOptions<boolean>
|
|
5
|
+
|
|
6
|
+
export const getBooleanValidator = getValidatorGenerator<boolean, BooleanOptions>(
|
|
7
|
+
function validate(field, input) {
|
|
8
|
+
let value: boolean | null = null
|
|
9
|
+
if (typeof input === 'boolean') {
|
|
10
|
+
value = input
|
|
11
|
+
} else if (typeof input === 'string') {
|
|
12
|
+
const str = input.trim().toLowerCase()
|
|
13
|
+
if (['1', 'true', 'on', 'yes'].includes(str)) value = true
|
|
14
|
+
else if (['0', 'false', 'off', 'no'].includes(str)) value = false
|
|
15
|
+
} else if (typeof input === 'number') {
|
|
16
|
+
if (input === 1) value = true
|
|
17
|
+
else if (input === 0) value = false
|
|
18
|
+
}
|
|
19
|
+
return value === null ? failed(`${field} must be true or false`) : success(value)
|
|
20
|
+
},
|
|
21
|
+
)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 验证日期时间类型的值,依赖 dayjs
|
|
3
|
+
*/
|
|
4
|
+
import dayjs, { Dayjs } from 'dayjs'
|
|
5
|
+
import { success, failed } from '../lang/index.js'
|
|
6
|
+
import { getValidatorGenerator, type CommonOptions } from './base.js'
|
|
7
|
+
|
|
8
|
+
export interface DatetimeOptions extends CommonOptions<number> {
|
|
9
|
+
raw?: boolean // 为 true 则返回原生 Date 对象;否则返回 Dayjs 对象(默认)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type DatetimeValue<Options extends DatetimeOptions> = Options extends {
|
|
13
|
+
raw: true
|
|
14
|
+
}
|
|
15
|
+
? Date
|
|
16
|
+
: Dayjs
|
|
17
|
+
|
|
18
|
+
export function getDatetimeValidator<const Options extends DatetimeOptions>(
|
|
19
|
+
options: Options = {} as Options
|
|
20
|
+
) {
|
|
21
|
+
return getValidatorGenerator<DatetimeValue<Options>, Options>(function validate(field, value) {
|
|
22
|
+
let dayjsValue: Dayjs
|
|
23
|
+
|
|
24
|
+
if (typeof value === 'number') {
|
|
25
|
+
dayjsValue = dayjs.unix(value)
|
|
26
|
+
if (!dayjsValue.isValid()) return failed(`${field} must be a valid unix timestamp`)
|
|
27
|
+
} else if (typeof value === 'string') {
|
|
28
|
+
dayjsValue = dayjs(value)
|
|
29
|
+
if (!dayjsValue.isValid()) return failed(`${field} must be a valid datetime string`)
|
|
30
|
+
} else if (value instanceof Date || value instanceof Dayjs) {
|
|
31
|
+
dayjsValue = dayjs(value)
|
|
32
|
+
if (!dayjsValue.isValid()) return failed(`${field} must be a valid Date or Dayjs object`)
|
|
33
|
+
} else {
|
|
34
|
+
return failed(`${field} must be a datetime string or unix timestamp`)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return success((options.raw ? dayjsValue.toDate() : dayjsValue) as DatetimeValue<Options>)
|
|
38
|
+
})(options)
|
|
39
|
+
}
|