@anjianshi/utils 3.0.0 → 3.0.1
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 +5 -0
- package/env-node/index.js +5 -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/{src/env-react/emotion-register-globals.ts → env-react/emotion-register-globals.d.ts} +2 -5
- package/env-react/emotion-register-globals.js +5 -0
- package/env-react/emotion.d.ts +20 -0
- package/env-react/emotion.jsx +34 -0
- package/env-react/hooks.d.ts +23 -0
- package/env-react/hooks.js +47 -0
- package/env-react/index.d.ts +1 -0
- package/env-react/index.js +1 -0
- package/env-react/react-register-globals.d.ts +21 -0
- package/env-react/react-register-globals.js +19 -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 +4 -0
- package/index.js +4 -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 +8 -0
- package/lang/index.js +8 -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/result.d.ts +47 -0
- package/lang/result.js +45 -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 +10 -19
- package/safe-request.d.ts +53 -0
- package/safe-request.js +140 -0
- 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 -5
- package/src/env-node/logging/handlers.ts +0 -190
- package/src/env-node/logging/index.ts +0 -16
- package/src/env-react/emotion.tsx +0 -42
- package/src/env-react/hooks.ts +0 -59
- package/src/env-react/index.ts +0 -1
- package/src/env-react/react-register-globals.ts +0 -53
- 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 -4
- 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 -8
- package/src/lang/object.ts +0 -39
- package/src/lang/random.ts +0 -25
- package/src/lang/result.ts +0 -78
- 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/safe-request.ts +0 -193
- 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
|
@@ -1,141 +0,0 @@
|
|
|
1
|
-
import * as dotenv from 'dotenv'
|
|
2
|
-
import { safeParseJSON } from '../lang/string.js'
|
|
3
|
-
|
|
4
|
-
type EnvValue = string | number | boolean | unknown[] | Record<string, unknown>
|
|
5
|
-
|
|
6
|
-
type TypeDef = 'string' | 'number' | 'boolean' | unknown[] | Record<string, unknown>
|
|
7
|
-
type TypeFrom<D extends TypeDef> = D extends 'string'
|
|
8
|
-
? string
|
|
9
|
-
: D extends 'number'
|
|
10
|
-
? number
|
|
11
|
-
: D extends 'boolean'
|
|
12
|
-
? boolean
|
|
13
|
-
: D
|
|
14
|
-
type ResultFrom<Defs extends Record<string, TypeDef>> = {
|
|
15
|
-
[K in keyof Defs]: TypeFrom<Defs[K]>
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* 读取 .env 文件,并获取格式化后的数据
|
|
20
|
-
* 注意:依赖 dotenv 包
|
|
21
|
-
*/
|
|
22
|
-
export class EnvReader {
|
|
23
|
-
protected loadedEnvs: Record<string, string> = {}
|
|
24
|
-
|
|
25
|
-
constructor(options: dotenv.DotenvConfigOptions = {}) {
|
|
26
|
-
dotenv.config({
|
|
27
|
-
...options,
|
|
28
|
-
|
|
29
|
-
// 把从 .env 文件读到的内容写入此变量,而不是 process.env,以避免污染 process.env。
|
|
30
|
-
processEnv: this.loadedEnvs,
|
|
31
|
-
})
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
protected toNumber(raw: string) {
|
|
35
|
-
const num = parseInt(raw, 10)
|
|
36
|
-
return isFinite(num) ? num : undefined
|
|
37
|
-
}
|
|
38
|
-
protected toBoolean(raw: string) {
|
|
39
|
-
const formatted = raw.toLowerCase().trim()
|
|
40
|
-
if (['1', 'true', 'on'].includes(formatted)) return true
|
|
41
|
-
if (['0', 'false', 'off'].includes(formatted)) return false
|
|
42
|
-
return undefined
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
getRaw(key: string) {
|
|
46
|
-
return this.loadedEnvs[key] ?? process.env[key]
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* 获取指定 env 的值,并转换成与 defaults 匹配的类型。
|
|
51
|
-
* 若值不存在,返回 defaults。
|
|
52
|
-
*/
|
|
53
|
-
get(key: string, defaults: string): string
|
|
54
|
-
get(key: string, defaults: number): number
|
|
55
|
-
get(key: string, defaults: boolean): boolean
|
|
56
|
-
get<T extends unknown[] | Record<string, unknown>>(key: string, defaults: T): T
|
|
57
|
-
get(key: string, defaults: EnvValue) {
|
|
58
|
-
const raw = this.getRaw(key)
|
|
59
|
-
if (raw === undefined) return defaults
|
|
60
|
-
|
|
61
|
-
if (typeof defaults === 'number') return this.toNumber(raw) ?? defaults
|
|
62
|
-
else if (typeof defaults === 'boolean') return this.toBoolean(raw) ?? defaults
|
|
63
|
-
else if (Array.isArray(defaults) || typeof defaults === 'object') {
|
|
64
|
-
return safeParseJSON(raw) ?? defaults
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
return raw
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* 获取指定 env 的值,并转换成指定类型,无需提供默认值。
|
|
72
|
-
* 值不存在或转换失败时,返回 undefined。
|
|
73
|
-
*/
|
|
74
|
-
getByType(key: string, type?: 'string'): string | undefined
|
|
75
|
-
getByType(key: string, type: 'number'): number | undefined
|
|
76
|
-
getByType(key: string, type: 'boolean'): boolean | undefined
|
|
77
|
-
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
|
|
78
|
-
getByType<T extends unknown[] | Record<string, unknown>>(key: string, type: 'json'): T | undefined
|
|
79
|
-
getByType(key: string, type: 'string' | 'number' | 'boolean' | 'json' = 'string') {
|
|
80
|
-
const raw = this.getRaw(key)
|
|
81
|
-
if (raw === undefined) return raw
|
|
82
|
-
if (type === 'number') return this.toNumber(raw)
|
|
83
|
-
if (type === 'boolean') return this.toBoolean(raw)
|
|
84
|
-
if (type === 'json') return safeParseJSON(raw)
|
|
85
|
-
return raw
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* 同 envReader.get(),只不过是通过对象指定各 env 的默认值来批量获取
|
|
90
|
-
* envReader.batchGet({ port: 8000, debug: false, mobiles: ['123', '456'] }
|
|
91
|
-
*/
|
|
92
|
-
batchGet<Defs extends Record<string, EnvValue>>(definitions: Defs) {
|
|
93
|
-
const result = {} as Record<string, unknown>
|
|
94
|
-
for (const [key, defaults] of Object.entries(definitions)) {
|
|
95
|
-
result[key] = this.get(key, defaults as string)
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// 保证返回的值类型是“通用化”的,例如不是 `false` 而是 `boolean`
|
|
99
|
-
return result as {
|
|
100
|
-
[K in keyof Defs]: Defs[K] extends string
|
|
101
|
-
? string
|
|
102
|
-
: Defs[K] extends number
|
|
103
|
-
? number
|
|
104
|
-
: Defs[K] extends boolean
|
|
105
|
-
? boolean
|
|
106
|
-
: Defs[K]
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* 同 envReader.getByType(),只不过是通过对象指定各 env 的类型来批量获取。
|
|
112
|
-
*
|
|
113
|
-
* - required=false(默认)时,不存在或值为 undefined 的 env 不会出现在返回对象里,以保证 { ...defaults, ...envReader.batchGetByType(...) } 的用法能正常保留默认值。
|
|
114
|
-
* - required=true 时要求所有 env 都必须有值,否则会抛出异常
|
|
115
|
-
*
|
|
116
|
-
* envReader.batchGetByType({
|
|
117
|
-
* port: 'number',
|
|
118
|
-
* debug: 'boolean',
|
|
119
|
-
* mobiles: [] as string[], // 用此格式定义内容是数组的 JSON 值
|
|
120
|
-
* obj: {} as { a: number, b: string } // 用此格式定义内容是对象的 JSON 值
|
|
121
|
-
* })
|
|
122
|
-
*/
|
|
123
|
-
batchGetByType<Defs extends Record<string, TypeDef>>(
|
|
124
|
-
definitions: Defs,
|
|
125
|
-
required?: false,
|
|
126
|
-
): Partial<ResultFrom<Defs>>
|
|
127
|
-
batchGetByType<Defs extends Record<string, TypeDef>>(
|
|
128
|
-
definitions: Defs,
|
|
129
|
-
required: true,
|
|
130
|
-
): ResultFrom<Defs>
|
|
131
|
-
batchGetByType<Defs extends Record<string, TypeDef>>(definitions: Defs, required = false) {
|
|
132
|
-
const result = {} as Record<string, unknown>
|
|
133
|
-
for (const [key, def] of Object.entries(definitions)) {
|
|
134
|
-
const value =
|
|
135
|
-
typeof def === 'string' ? this.getByType(key, def as 'string') : this.getByType(key, 'json')
|
|
136
|
-
if (value !== undefined) result[key] = value
|
|
137
|
-
else if (required) throw new Error(`env ${key} needs a value`)
|
|
138
|
-
}
|
|
139
|
-
return result
|
|
140
|
-
}
|
|
141
|
-
}
|
package/src/env-service/index.ts
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 对接 Prisma 的日志记录
|
|
3
|
-
*
|
|
4
|
-
* 注意:Prisma 的 debugging 日志是直接输出到 console 的,没有提供处理渠道,所以无法记录进日志文件。
|
|
5
|
-
* 理论上可以重写 console.log/debug... 等方法来实现捕获,但这牵扯面太广,暂不这样做。
|
|
6
|
-
*/
|
|
7
|
-
import nodeUtil from 'node:util'
|
|
8
|
-
import type { getPrismaClient, PrismaClientOptions } from '@prisma/client/runtime/library.js'
|
|
9
|
-
import chalk from 'chalk'
|
|
10
|
-
import { type Logger } from '../../logging/index.js'
|
|
11
|
-
|
|
12
|
-
type PrismalClient = ReturnType<typeof getPrismaClient> extends new () => infer T ? T : never
|
|
13
|
-
|
|
14
|
-
export function getPrismaLoggingOptions(debug: boolean) {
|
|
15
|
-
return {
|
|
16
|
-
errorFormat: 'pretty',
|
|
17
|
-
log: [
|
|
18
|
-
...(debug ? [{ emit: 'event', level: 'query' } as const] : []),
|
|
19
|
-
{ emit: 'event', level: 'info' },
|
|
20
|
-
{ emit: 'event', level: 'warn' },
|
|
21
|
-
{ emit: 'event', level: 'error' },
|
|
22
|
-
],
|
|
23
|
-
} satisfies PrismaClientOptions
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
|
|
27
|
-
export function adaptPrismaLogging<T extends Pick<PrismalClient, '$on'>>(
|
|
28
|
-
prisma: T,
|
|
29
|
-
baseLogger: Logger,
|
|
30
|
-
) {
|
|
31
|
-
// 记录 Prisma 相关日志
|
|
32
|
-
const queryLogger = baseLogger.getChild('query')
|
|
33
|
-
prisma.$on('query', e => {
|
|
34
|
-
queryLogger.debug(e.query, chalk.green(nodeUtil.format(e.params) + ` +${e.duration}ms`))
|
|
35
|
-
})
|
|
36
|
-
prisma.$on('info', e => baseLogger.info(e.message))
|
|
37
|
-
prisma.$on('warn', e => baseLogger.warn(e.message))
|
|
38
|
-
prisma.$on('error', e => baseLogger.error(e.message))
|
|
39
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { Prisma } from '@prisma/client/extension'
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 快速检查指定条件的数据是否存在
|
|
5
|
-
* const exists = await prisma.xxx.exists({ id: '1' })
|
|
6
|
-
*/
|
|
7
|
-
export const exists = Prisma.defineExtension({
|
|
8
|
-
name: 'exists',
|
|
9
|
-
model: {
|
|
10
|
-
$allModels: {
|
|
11
|
-
async exists<T>(
|
|
12
|
-
this: T,
|
|
13
|
-
where: Prisma.Args<T, 'count'>['where'],
|
|
14
|
-
withDeleted = false,
|
|
15
|
-
): Promise<boolean> {
|
|
16
|
-
const context = Prisma.getExtensionContext(this)
|
|
17
|
-
return !!(await (context as any).count({ where, withDeleted }))
|
|
18
|
-
},
|
|
19
|
-
},
|
|
20
|
-
},
|
|
21
|
-
})
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { Prisma } from '@prisma/client/extension'
|
|
2
|
-
import { type SoftDeleteQueryArgs } from './soft-delete.js'
|
|
3
|
-
|
|
4
|
-
export const findAndCount = Prisma.defineExtension({
|
|
5
|
-
name: 'findAndCount',
|
|
6
|
-
model: {
|
|
7
|
-
$allModels: {
|
|
8
|
-
findAndCount<T, A>(
|
|
9
|
-
this: T,
|
|
10
|
-
rawArgs: Prisma.Exact<A, Prisma.Args<T, 'findMany'> & SoftDeleteQueryArgs>,
|
|
11
|
-
) {
|
|
12
|
-
const context = Prisma.getExtensionContext(this)
|
|
13
|
-
const args = rawArgs as Prisma.Args<T, 'findMany'> & SoftDeleteQueryArgs
|
|
14
|
-
return Promise.all([
|
|
15
|
-
(context as any).findMany(args) as Promise<Prisma.Result<T, A, 'findMany'>>,
|
|
16
|
-
(context as any).count({
|
|
17
|
-
where: args.where,
|
|
18
|
-
withDeleted: args.withDeleted,
|
|
19
|
-
}) as Promise<Prisma.Result<T, A, 'count'>>,
|
|
20
|
-
])
|
|
21
|
-
},
|
|
22
|
-
},
|
|
23
|
-
},
|
|
24
|
-
})
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 扩展 Prisma 实现软删除
|
|
3
|
-
*
|
|
4
|
-
* 1. 有 deleteTime 字段的 model 支持软删除。
|
|
5
|
-
* 2. 执行 delete() 和 deleteMany() 时默认是进行软删除;可指定 soft 为 false 来彻底删除;执行软删除时可指定要额外更新的 data。
|
|
6
|
-
* 2. 查询时会忽略被软删除的记录;可指定 withDeleted 为 true 来包含它们。
|
|
7
|
-
* 4. 可通过 restore() 和 restoreMany() 恢复软删除的记录。
|
|
8
|
-
*
|
|
9
|
-
* 扩展实现方式参考:
|
|
10
|
-
* https://www.prisma.io/docs/orm/prisma-client/client-extensions/type-utilities#add-a-custom-property-to-a-method
|
|
11
|
-
* https://www.npmjs.com/package/@prisma/extension-accelerate?activeTab=code => @prisma/extension-accelerate/dist/esm/extension.js
|
|
12
|
-
*
|
|
13
|
-
* 此扩展修改了 Prisma 的原生方法。
|
|
14
|
-
* 为保证其他扩展也应用到修改过的这些方法,此扩展应尽可能放在最前面。
|
|
15
|
-
*/
|
|
16
|
-
import { Prisma } from '@prisma/client/extension'
|
|
17
|
-
import type { Operation } from '@prisma/client/runtime/library.js'
|
|
18
|
-
import { type OptionalFields } from '../../../index.js'
|
|
19
|
-
|
|
20
|
-
type ExampleModel = any
|
|
21
|
-
|
|
22
|
-
type DeleteArgs<T> = Prisma.Args<T, 'delete'> & {
|
|
23
|
-
soft?: boolean
|
|
24
|
-
data?: Prisma.Args<T, 'update'>['data'] // 软删除时支持额外更新其他字段
|
|
25
|
-
}
|
|
26
|
-
type DeleteReturn<T, A> = Promise<Prisma.Result<T, A, 'delete'>>
|
|
27
|
-
|
|
28
|
-
type DeleteManyArgs<T> = Prisma.Args<T, 'deleteMany'> & {
|
|
29
|
-
soft?: boolean
|
|
30
|
-
data?: Prisma.Args<T, 'updateMany'>['data']
|
|
31
|
-
}
|
|
32
|
-
type DeleteManyReturn<T, A> = Promise<Prisma.Result<T, A, 'deleteMany'>>
|
|
33
|
-
|
|
34
|
-
type RestoreArgs<T> = OptionalFields<Prisma.Args<T, 'update'>, 'data'>
|
|
35
|
-
type RestoreManyArgs<T> = OptionalFields<Prisma.Args<T, 'updateMany'>, 'data'>
|
|
36
|
-
|
|
37
|
-
interface QueryExtraArgs {
|
|
38
|
-
withDeleted?: boolean
|
|
39
|
-
}
|
|
40
|
-
export type { QueryExtraArgs as SoftDeleteQueryArgs }
|
|
41
|
-
type QueryInputArgs<T, A, K extends Operation> = Prisma.Exact<A, Prisma.Args<T, K> & QueryExtraArgs>
|
|
42
|
-
|
|
43
|
-
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
|
|
44
|
-
function getModel<T>(that: T) {
|
|
45
|
-
const context = Prisma.getExtensionContext(that as ExampleModel)
|
|
46
|
-
|
|
47
|
-
// 1. 此扩展修改了 Prisma 原生的方法,所以要通过 context.$parent[context.$name] 获取上一层的 model,不然会自己调用自己导致死循环。
|
|
48
|
-
// 2. 如果此扩展后面还应用了其他扩展,那么仅仅一层 $parent 取得的 model 还是这个扩展修改过的版本而不是原生的。
|
|
49
|
-
// 此时需要递归向上,直到取得未经此扩展修改过的 model。不然此扩展的业务逻辑会被重复执行,
|
|
50
|
-
// 而因为第一次执行时已经把定制参数消解掉了,第二次执行时会误以为没有传入定制参数,最终导致定制参数失效。
|
|
51
|
-
let model = context
|
|
52
|
-
do {
|
|
53
|
-
model = (model as unknown as { $parent: Record<string, ExampleModel> }).$parent[context.$name!]!
|
|
54
|
-
} while ('withSoftDeleteExtension' in model)
|
|
55
|
-
|
|
56
|
-
const supportSoftDelete = 'deleteTime' in model.fields
|
|
57
|
-
return { model, supportSoftDelete }
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function query<T, A, K extends Operation>(
|
|
61
|
-
that: T,
|
|
62
|
-
inputArgs: Prisma.Exact<A, Prisma.Args<T, K>>,
|
|
63
|
-
method: K,
|
|
64
|
-
) {
|
|
65
|
-
const { model, supportSoftDelete } = getModel(that)
|
|
66
|
-
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
|
|
67
|
-
const { withDeleted = false, ...args } = inputArgs as Prisma.Args<ExampleModel, 'findFirst'> &
|
|
68
|
-
QueryExtraArgs
|
|
69
|
-
|
|
70
|
-
return model[method]({
|
|
71
|
-
...args,
|
|
72
|
-
where: !supportSoftDelete || withDeleted ? args.where : { ...args.where, deleteTime: null },
|
|
73
|
-
}) as Promise<Prisma.Result<T, A, K>>
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export const softDelete = Prisma.defineExtension({
|
|
77
|
-
name: 'softDeleted',
|
|
78
|
-
model: {
|
|
79
|
-
$allModels: {
|
|
80
|
-
withSoftDeleteExtension: true,
|
|
81
|
-
|
|
82
|
-
// -----------------------------
|
|
83
|
-
// 操作
|
|
84
|
-
// -----------------------------
|
|
85
|
-
|
|
86
|
-
delete<T, A>(this: T, rawArgs: Prisma.Exact<A, DeleteArgs<T>>) {
|
|
87
|
-
const { model, supportSoftDelete } = getModel(this)
|
|
88
|
-
const { soft = true, data, ...args } = rawArgs as DeleteArgs<ExampleModel>
|
|
89
|
-
if (supportSoftDelete && soft) {
|
|
90
|
-
return model.update({
|
|
91
|
-
...args, // .delete() 的参数 .update() 也都支持
|
|
92
|
-
data: { ...(data ?? {}), deleteTime: new Date() },
|
|
93
|
-
}) as unknown as DeleteReturn<T, A> // .update() 的返回值和 .delete() 一样
|
|
94
|
-
} else {
|
|
95
|
-
return model.delete(args) as unknown as DeleteReturn<T, A>
|
|
96
|
-
}
|
|
97
|
-
},
|
|
98
|
-
|
|
99
|
-
deleteMany<T, A>(this: T, rawArgs: Prisma.Exact<A, DeleteManyArgs<T>>) {
|
|
100
|
-
const { model, supportSoftDelete } = getModel(this)
|
|
101
|
-
const { soft = true, data, ...args } = rawArgs as DeleteManyArgs<ExampleModel>
|
|
102
|
-
if (supportSoftDelete && soft) {
|
|
103
|
-
return model.updateMany({
|
|
104
|
-
...args, // .deleteMany() 的参数 .updateMany() 也都支持
|
|
105
|
-
data: { ...(data ?? {}), deleteTime: new Date() },
|
|
106
|
-
}) as DeleteManyReturn<T, A> // .updateMany() 的返回值和 .deleteMany() 一样
|
|
107
|
-
} else {
|
|
108
|
-
return model.deleteMany(args) as DeleteManyReturn<T, A>
|
|
109
|
-
}
|
|
110
|
-
},
|
|
111
|
-
|
|
112
|
-
restore<T, A>(this: T, rawArgs: Prisma.Exact<A, RestoreArgs<T>>) {
|
|
113
|
-
const { data, ...args } = rawArgs as RestoreArgs<ExampleModel>
|
|
114
|
-
const { model, supportSoftDelete } = getModel(this)
|
|
115
|
-
if (!supportSoftDelete) throw new Error('当前模型不支持软删除,不能执行恢复')
|
|
116
|
-
return model.update({
|
|
117
|
-
...(args as Prisma.Args<ExampleModel, 'update'>),
|
|
118
|
-
data: { ...(data ?? {}), deleteTime: null },
|
|
119
|
-
}) as unknown as Promise<Prisma.Result<T, A, 'update'>>
|
|
120
|
-
},
|
|
121
|
-
|
|
122
|
-
restoreMany<T, A>(this: T, rawArgs: Prisma.Exact<A, RestoreManyArgs<T>>) {
|
|
123
|
-
const { data, ...args } = rawArgs as RestoreArgs<ExampleModel>
|
|
124
|
-
const { model, supportSoftDelete } = getModel(this)
|
|
125
|
-
if (!supportSoftDelete) throw new Error('当前模型不支持软删除,不能执行恢复')
|
|
126
|
-
return model.updateMany({
|
|
127
|
-
...(args as Prisma.Args<ExampleModel, 'updateMany'>),
|
|
128
|
-
data: { ...(data ?? {}), deleteTime: new Date() },
|
|
129
|
-
}) as Promise<Prisma.Result<T, A, 'updateMany'>>
|
|
130
|
-
},
|
|
131
|
-
|
|
132
|
-
// -----------------------------
|
|
133
|
-
// 查询
|
|
134
|
-
// -----------------------------
|
|
135
|
-
|
|
136
|
-
aggregate<T, A>(this: T, inputArgs: QueryInputArgs<T, A, 'aggregate'>) {
|
|
137
|
-
return query(this, inputArgs, 'aggregate')
|
|
138
|
-
},
|
|
139
|
-
count<T, A>(this: T, inputArgs: QueryInputArgs<T, A, 'count'>) {
|
|
140
|
-
return query(this, inputArgs, 'count')
|
|
141
|
-
},
|
|
142
|
-
findFirst<T, A>(this: T, inputArgs: QueryInputArgs<T, A, 'findFirst'>) {
|
|
143
|
-
return query(this, inputArgs, 'findFirst')
|
|
144
|
-
},
|
|
145
|
-
findFirstOrThrow<T, A>(this: T, inputArgs: QueryInputArgs<T, A, 'findFirstOrThrow'>) {
|
|
146
|
-
return query(this, inputArgs, 'findFirstOrThrow')
|
|
147
|
-
},
|
|
148
|
-
findMany<T, A>(this: T, inputArgs: QueryInputArgs<T, A, 'findMany'>) {
|
|
149
|
-
return query(this, inputArgs, 'findMany')
|
|
150
|
-
},
|
|
151
|
-
findUnique<T, A>(this: T, inputArgs: QueryInputArgs<T, A, 'findUnique'>) {
|
|
152
|
-
return query(this, inputArgs, 'findUnique')
|
|
153
|
-
},
|
|
154
|
-
findUniqueOrThrow<T, A>(this: T, inputArgs: QueryInputArgs<T, A, 'findUniqueOrThrow'>) {
|
|
155
|
-
return query(this, inputArgs, 'findUniqueOrThrow')
|
|
156
|
-
},
|
|
157
|
-
groupBy<T, A>(this: T, inputArgs: QueryInputArgs<T, A, 'groupBy'>) {
|
|
158
|
-
return query(this, inputArgs, 'groupBy')
|
|
159
|
-
},
|
|
160
|
-
},
|
|
161
|
-
},
|
|
162
|
-
})
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 在事务中执行回调。与 $transaction 有几点不同:
|
|
3
|
-
* 1. 回调必须返回 Result 值
|
|
4
|
-
* 2. 回调返回 Failed 值或抛出异常都会触发回滚。
|
|
5
|
-
* 如果是返回 Failed,会作为此方法的返回值;如果是抛出异常,则异常会继续向上传递,直到被捕获或触发请求失败。
|
|
6
|
-
* 3. 如果已经处于事务中,会沿用上层事务,且回调返回 Failed 或抛出异常会触发上层事务的回滚。
|
|
7
|
-
*
|
|
8
|
-
* const result: Result = await db.$withTransaction(
|
|
9
|
-
* async (dbInTransaction) => {
|
|
10
|
-
* // do something
|
|
11
|
-
* return success()
|
|
12
|
-
* }
|
|
13
|
-
* )
|
|
14
|
-
*/
|
|
15
|
-
import { Prisma } from '@prisma/client/extension.js'
|
|
16
|
-
import { type ITXClientDenyList } from '@prisma/client/runtime/library.js'
|
|
17
|
-
import type { Result, Failed } from '../../../index.js'
|
|
18
|
-
|
|
19
|
-
export const withTransaction = Prisma.defineExtension({
|
|
20
|
-
name: 'withTransaction',
|
|
21
|
-
client: {
|
|
22
|
-
$withTransaction,
|
|
23
|
-
},
|
|
24
|
-
})
|
|
25
|
-
|
|
26
|
-
// ----------------------------------
|
|
27
|
-
|
|
28
|
-
export type GetPrismaClientInTransaction<PrismaClient> = Omit<PrismaClient, ITXClientDenyList>
|
|
29
|
-
export type WithTransactionMethod = typeof $withTransaction
|
|
30
|
-
|
|
31
|
-
type OpenTransaction<R = unknown> = (cb: (dbInTransaction: unknown) => Promise<R>) => Promise<R>
|
|
32
|
-
|
|
33
|
-
class FailedInTransaction<T = void> extends Error {
|
|
34
|
-
constructor(readonly failed: Failed<T>) {
|
|
35
|
-
super(failed.message)
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// 注意:此函数的返回值为 `R | Failed<any>`,例如实际可能为 `Result<xxx, xxx> | Failed<any>`,这是有意为之的,`Failed<any>` 并不多余。
|
|
40
|
-
// 因为有时 callback() 只会返回 success 结果,此时 R=Success<xxx>,但是 $withTransaction 整体的返回值仍有可能有 Failed<any>,所以不能用 R 作为整体返回值。
|
|
41
|
-
async function $withTransaction<That extends object, R extends Result<unknown, unknown>>(
|
|
42
|
-
this: That,
|
|
43
|
-
callback: (dbInTransaction: GetPrismaClientInTransaction<That>) => Promise<R>,
|
|
44
|
-
) {
|
|
45
|
-
const executeCallback = async (dbInTransaction: unknown) => {
|
|
46
|
-
const result = await callback(dbInTransaction as GetPrismaClientInTransaction<That>)
|
|
47
|
-
if (result.success) return result
|
|
48
|
-
else throw new FailedInTransaction(result)
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
if ('$transaction' in this && this.$transaction) {
|
|
52
|
-
// 如果当前不在事务中,开启新事务并执行回调
|
|
53
|
-
try {
|
|
54
|
-
return await (this.$transaction as OpenTransaction<R>)(async dbInTransaction =>
|
|
55
|
-
executeCallback(dbInTransaction),
|
|
56
|
-
)
|
|
57
|
-
} catch (e) {
|
|
58
|
-
if (e instanceof FailedInTransaction) return e.failed
|
|
59
|
-
throw e
|
|
60
|
-
}
|
|
61
|
-
} else {
|
|
62
|
-
// 已经在事务中,直接执行回调(如果有异常,上层开启事务的代码会捕获)
|
|
63
|
-
return executeCallback(this)
|
|
64
|
-
}
|
|
65
|
-
}
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import { type Result } from '../../index.js'
|
|
2
|
-
import type {
|
|
3
|
-
GetPrismaClientInTransaction,
|
|
4
|
-
WithTransactionMethod,
|
|
5
|
-
} from './extensions/with-transaction.js'
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* 返回一个可以在事务内和事务外通用的 PrismaClient 代理对象。
|
|
9
|
-
* 当前在事务内时,调用它是调用事务内的 client;当前不在事务内时,调用它是调用全局 client。
|
|
10
|
-
* 这样当一个事务涉及多个函数调用时,就不用把事务内 client 传递来传递去了。
|
|
11
|
-
* 注意:应给每个线性流程(例如一个请求)单独生成一个此对象,不能作为全局对象使用,不然可能出现事务冲突。
|
|
12
|
-
*/
|
|
13
|
-
export function getTransactionContextedPrismaClient<
|
|
14
|
-
AppPrismaClient extends {
|
|
15
|
-
$transaction: (...args: any[]) => Promise<unknown>
|
|
16
|
-
$withTransaction: WithTransactionMethod
|
|
17
|
-
},
|
|
18
|
-
>(prisma: AppPrismaClient): AppPrismaClient {
|
|
19
|
-
type PrismaClientInTransaction = GetPrismaClientInTransaction<AppPrismaClient>
|
|
20
|
-
|
|
21
|
-
/** 虽然这里还是会把事务中的 client 传给 callback,但实际并不需要了,始终使用 contexted client 即可 */
|
|
22
|
-
type TransactionCallback<R = unknown> = (client: PrismaClientInTransaction) => Promise<R>
|
|
23
|
-
|
|
24
|
-
let client: AppPrismaClient | PrismaClientInTransaction = prisma
|
|
25
|
-
|
|
26
|
-
async function callCallbackInTransaction<R = unknown>(
|
|
27
|
-
callback: TransactionCallback<R>,
|
|
28
|
-
clientInTransaction: PrismaClientInTransaction,
|
|
29
|
-
) {
|
|
30
|
-
const prevClient = client
|
|
31
|
-
const currentClient = clientInTransaction
|
|
32
|
-
client = currentClient
|
|
33
|
-
function restoreClient() {
|
|
34
|
-
if (client !== currentClient)
|
|
35
|
-
throw new Error('事务冲突,必须等一个事务结束后再开启另一个事务')
|
|
36
|
-
client = prevClient
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
try {
|
|
40
|
-
const res = await callback(client)
|
|
41
|
-
restoreClient()
|
|
42
|
-
return res
|
|
43
|
-
} catch (e) {
|
|
44
|
-
restoreClient()
|
|
45
|
-
throw e
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
async function $transaction(arg: unknown, ...restArgs: unknown[]) {
|
|
50
|
-
interface GeneralClient {
|
|
51
|
-
$transaction: (...args: unknown[]) => Promise<unknown>
|
|
52
|
-
}
|
|
53
|
-
if (typeof arg === 'function') {
|
|
54
|
-
const wrappedCallback = callCallbackInTransaction.bind(null, arg as TransactionCallback)
|
|
55
|
-
return (client as GeneralClient).$transaction(wrappedCallback, ...restArgs)
|
|
56
|
-
} else {
|
|
57
|
-
return (client as GeneralClient).$transaction(arg, ...restArgs)
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
async function $withTransaction(callback: TransactionCallback<Result>) {
|
|
62
|
-
return client.$withTransaction(async clientInTransaction =>
|
|
63
|
-
callCallbackInTransaction(callback, clientInTransaction as PrismaClientInTransaction),
|
|
64
|
-
)
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
return new Proxy(
|
|
68
|
-
{},
|
|
69
|
-
{
|
|
70
|
-
has(_, prop) {
|
|
71
|
-
return prop in client
|
|
72
|
-
},
|
|
73
|
-
get(_, prop) {
|
|
74
|
-
if (prop === '$transaction') return $transaction
|
|
75
|
-
if (prop === '$withTransaction') return $withTransaction
|
|
76
|
-
return (client as Record<string | symbol, unknown>)[prop]
|
|
77
|
-
},
|
|
78
|
-
},
|
|
79
|
-
) as AppPrismaClient
|
|
80
|
-
}
|