@aomex/mongoose 3.23.3 → 3.24.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/CHANGELOG.md +13 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +75 -31
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,19 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
# [3.24.0](https://github.com/aomex/aomex/compare/v3.23.3...v3.24.0) (2025-04-20)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Features
|
|
10
|
+
|
|
11
|
+
* **mongoose:** decimal123和objectid验证器的默认值支持传入字符串 ([e954d56](https://github.com/aomex/aomex/commit/e954d5653af0854aa8e1f84fbf57da4a3b77e572))
|
|
12
|
+
* **mongoose:** 创建迁移文件时,支持使用对话输入文件名 ([9261a31](https://github.com/aomex/aomex/commit/9261a314539532f01d96049be9b31c4856ba36ec))
|
|
13
|
+
* **mongoose:** 回滚指令增加--all参数回滚全部 ([2136394](https://github.com/aomex/aomex/commit/213639407dc232f60fd53251e0a1d040011b87a1))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
6
19
|
## [3.23.3](https://github.com/aomex/aomex/compare/v3.23.2...v3.23.3) (2025-04-18)
|
|
7
20
|
|
|
8
21
|
**Note:** Version bump only for package @aomex/mongoose
|
package/dist/index.d.ts
CHANGED
|
@@ -7,8 +7,9 @@ declare class MongoDecimal128Validator<T = mongo.Decimal128> extends Validator<T
|
|
|
7
7
|
protected config: Validator.Options<T>;
|
|
8
8
|
docs: (docs: Validator.PartialOpenAPISchema, mode?: Validator.DocumentMergeMode) => this;
|
|
9
9
|
optional: () => MongoDecimal128Validator<T | Validator.TOptional>;
|
|
10
|
-
|
|
10
|
+
nullable: () => MongoDecimal128Validator<T | null>;
|
|
11
11
|
transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
|
|
12
|
+
default(value: number | string | mongo.Decimal128): MongoDecimal128Validator<T | Validator.TDefault>;
|
|
12
13
|
protected validateValue(value: any, _key: string, label: string): ValidateResult.Any<mongo.Decimal128>;
|
|
13
14
|
protected copy: () => MongoDecimal128Validator<T>;
|
|
14
15
|
protected toDocument(): OpenAPI.SchemaObject;
|
|
@@ -23,8 +24,9 @@ declare class MongoObjectIdValidator<T = mongo.ObjectId> extends Validator<T> {
|
|
|
23
24
|
protected config: Validator.Options<T>;
|
|
24
25
|
docs: (docs: Validator.PartialOpenAPISchema, mode?: Validator.DocumentMergeMode) => this;
|
|
25
26
|
optional: () => MongoObjectIdValidator<T | Validator.TOptional>;
|
|
26
|
-
|
|
27
|
+
nullable: () => MongoObjectIdValidator<T | null>;
|
|
27
28
|
transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
|
|
29
|
+
default(value: string | mongo.ObjectId): MongoObjectIdValidator<T | Validator.TDefault>;
|
|
28
30
|
protected validateValue(value: any, _key: string, label: string): ValidateResult.Any<mongo.ObjectId>;
|
|
29
31
|
protected copy: () => MongoObjectIdValidator<T>;
|
|
30
32
|
protected toDocument(): OpenAPI.SchemaObject;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// src/
|
|
1
|
+
// src/validators/mongo-decimal128.validator.ts
|
|
2
2
|
import {
|
|
3
3
|
Validator,
|
|
4
4
|
ValidateResult,
|
|
@@ -26,7 +26,8 @@ var zh = I18n.define({
|
|
|
26
26
|
create: "\u521B\u5EFA\u8FC1\u79FB\u6587\u4EF6",
|
|
27
27
|
up: "\u6267\u884C\u8FC1\u79FB\u903B\u8F91",
|
|
28
28
|
down: "\u56DE\u6EDA\u8FC1\u79FB\u903B\u8F91",
|
|
29
|
-
file_not_found: "\u8FC1\u79FB\u6587\u4EF6 '{{file}}' \u4E0D\u5B58\u5728"
|
|
29
|
+
file_not_found: "\u8FC1\u79FB\u6587\u4EF6 '{{file}}' \u4E0D\u5B58\u5728",
|
|
30
|
+
input_file_name: "\u8FC1\u79FB\u6587\u4EF6\u540D\u662F\u4EC0\u4E48\uFF1F"
|
|
30
31
|
}
|
|
31
32
|
});
|
|
32
33
|
|
|
@@ -48,7 +49,8 @@ var en = I18n2.satisfies(zh).define({
|
|
|
48
49
|
create: "Generate migration file",
|
|
49
50
|
up: "Execute migration logic",
|
|
50
51
|
down: "Rollback migration logic",
|
|
51
|
-
file_not_found: "Migration file '{{file}}' not found"
|
|
52
|
+
file_not_found: "Migration file '{{file}}' not found",
|
|
53
|
+
input_file_name: "What is migration file name?"
|
|
52
54
|
}
|
|
53
55
|
});
|
|
54
56
|
|
|
@@ -64,9 +66,15 @@ var i18n = new I18n3({
|
|
|
64
66
|
defaultLanguage: "zh_CN"
|
|
65
67
|
});
|
|
66
68
|
|
|
67
|
-
// src/
|
|
69
|
+
// src/validators/mongo-decimal128.validator.ts
|
|
68
70
|
import { mongo } from "mongoose";
|
|
69
71
|
var MongoDecimal128Validator = class extends Validator {
|
|
72
|
+
default(value) {
|
|
73
|
+
const validator = super.default(
|
|
74
|
+
typeof value === "string" || typeof value === "number" ? mongo.Decimal128.fromString(value.toString()) : value
|
|
75
|
+
);
|
|
76
|
+
return validator;
|
|
77
|
+
}
|
|
70
78
|
validateValue(value, _key, label) {
|
|
71
79
|
if (value instanceof mongo.Decimal128) {
|
|
72
80
|
return ValidateResult.accept(value);
|
|
@@ -80,14 +88,18 @@ var MongoDecimal128Validator = class extends Validator {
|
|
|
80
88
|
}
|
|
81
89
|
}
|
|
82
90
|
toDocument() {
|
|
91
|
+
const defaultValue = this.getDefaultValue(
|
|
92
|
+
this.config.defaultValue
|
|
93
|
+
);
|
|
83
94
|
return {
|
|
84
|
-
type: "string"
|
|
95
|
+
type: "string",
|
|
96
|
+
default: defaultValue && defaultValue.toString()
|
|
85
97
|
};
|
|
86
98
|
}
|
|
87
99
|
};
|
|
88
100
|
Rule.register("mongoDecimal128", MongoDecimal128Validator);
|
|
89
101
|
|
|
90
|
-
// src/
|
|
102
|
+
// src/validators/mongo-object-id.validator.ts
|
|
91
103
|
import {
|
|
92
104
|
Validator as Validator2,
|
|
93
105
|
ValidateResult as ValidateResult2,
|
|
@@ -95,6 +107,12 @@ import {
|
|
|
95
107
|
} from "@aomex/common";
|
|
96
108
|
import { mongo as mongo2 } from "mongoose";
|
|
97
109
|
var MongoObjectIdValidator = class extends Validator2 {
|
|
110
|
+
default(value) {
|
|
111
|
+
const validator = super.default(
|
|
112
|
+
typeof value === "string" ? mongo2.ObjectId.createFromHexString(value.toString()) : value
|
|
113
|
+
);
|
|
114
|
+
return validator;
|
|
115
|
+
}
|
|
98
116
|
validateValue(value, _key, label) {
|
|
99
117
|
if (value instanceof mongo2.ObjectId) {
|
|
100
118
|
return ValidateResult2.accept(value);
|
|
@@ -108,8 +126,12 @@ var MongoObjectIdValidator = class extends Validator2 {
|
|
|
108
126
|
}
|
|
109
127
|
}
|
|
110
128
|
toDocument() {
|
|
129
|
+
const defaultValue = this.getDefaultValue(
|
|
130
|
+
this.config.defaultValue
|
|
131
|
+
);
|
|
111
132
|
return {
|
|
112
|
-
type: "string"
|
|
133
|
+
type: "string",
|
|
134
|
+
default: defaultValue && defaultValue.toHexString()
|
|
113
135
|
};
|
|
114
136
|
}
|
|
115
137
|
};
|
|
@@ -210,15 +232,27 @@ import { middleware, rule, validate } from "@aomex/common";
|
|
|
210
232
|
import snakeCase from "lodash.snakecase";
|
|
211
233
|
import path from "node:path";
|
|
212
234
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
235
|
+
import { createInterface } from "node:readline/promises";
|
|
213
236
|
var commandName = "mongoose:migration:create";
|
|
214
237
|
var migrationCreateFile = (migrationsPath) => {
|
|
215
238
|
return middleware.console({
|
|
216
239
|
fn: async (ctx, next) => {
|
|
217
240
|
if (ctx.input.command !== commandName) return next();
|
|
218
241
|
ctx.commandMatched = true;
|
|
219
|
-
|
|
242
|
+
let { name } = await validate(ctx.input.parseArgv(), {
|
|
220
243
|
name: rule.string().optional().trim().transform(snakeCase)
|
|
221
244
|
});
|
|
245
|
+
if (!name) {
|
|
246
|
+
const readline = createInterface({
|
|
247
|
+
input: process.stdin,
|
|
248
|
+
output: process.stdout
|
|
249
|
+
});
|
|
250
|
+
while (!name) {
|
|
251
|
+
name = await readline.question(i18n.t("migration.input_file_name"));
|
|
252
|
+
name = snakeCase(name.trim());
|
|
253
|
+
}
|
|
254
|
+
readline.close();
|
|
255
|
+
}
|
|
222
256
|
const filename = `${(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[-TZ.:]/gi, "")}_${name}.ts`;
|
|
223
257
|
const fullPath = path.join(migrationsPath, filename);
|
|
224
258
|
await mkdir(path.dirname(fullPath), { recursive: true });
|
|
@@ -353,7 +387,7 @@ var migrationUp = (opts) => {
|
|
|
353
387
|
};
|
|
354
388
|
|
|
355
389
|
// src/middleware/migration-down.md.ts
|
|
356
|
-
import { middleware as middleware3 } from "@aomex/common";
|
|
390
|
+
import { middleware as middleware3, rule as rule3, validate as validate2 } from "@aomex/common";
|
|
357
391
|
import mongoose4, { createConnection as createConnection2 } from "mongoose";
|
|
358
392
|
import { terminal as terminal2 } from "@aomex/console";
|
|
359
393
|
import { pathToFiles as pathToFiles3 } from "@aomex/internal-file-import";
|
|
@@ -365,35 +399,42 @@ var migrationDown = (opts) => {
|
|
|
365
399
|
fn: async (ctx, next) => {
|
|
366
400
|
if (ctx.input.command !== commandName3) return next();
|
|
367
401
|
ctx.commandMatched = true;
|
|
402
|
+
const { all } = await validate2(ctx.input.parseArgv(), {
|
|
403
|
+
all: rule3.boolean().default(false)
|
|
404
|
+
});
|
|
368
405
|
const connection = opts.connection instanceof mongoose4.Connection ? opts.connection : await createConnection2(
|
|
369
406
|
opts.connection.uri,
|
|
370
407
|
opts.connection.options
|
|
371
408
|
).asPromise();
|
|
372
409
|
const db = connection.db;
|
|
373
410
|
await syncCollectionIndex(opts.modelsPath);
|
|
374
|
-
const
|
|
375
|
-
|
|
376
|
-
|
|
411
|
+
const rows = await MigrationModel.find().sort({ filename: "desc" }).lean();
|
|
412
|
+
if (!rows.length) return;
|
|
413
|
+
const migratedFiles = rows.map((item) => item.filename);
|
|
377
414
|
await mkdir4(opts.migrationsPath, { recursive: true });
|
|
378
415
|
const allFiles = await pathToFiles3(opts.migrationsPath);
|
|
379
|
-
const
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
416
|
+
const executeCount = all ? migratedFiles.length : 1;
|
|
417
|
+
for (let i = 0; i < executeCount; ++i) {
|
|
418
|
+
const filename = migratedFiles[i];
|
|
419
|
+
const fullPath = allFiles.find(
|
|
420
|
+
(item) => item.endsWith(filename + path3.extname(item))
|
|
421
|
+
);
|
|
422
|
+
if (!fullPath) {
|
|
423
|
+
throw new Error(i18n.t("migration.file_not_found", { file: filename }));
|
|
424
|
+
}
|
|
425
|
+
const instance = await import(fullPath);
|
|
426
|
+
const migrate2 = instance.default;
|
|
427
|
+
if (migrate2 instanceof Migrate) {
|
|
428
|
+
try {
|
|
429
|
+
await connection.transaction(async (session) => {
|
|
430
|
+
await MigrationModel.deleteOne({ filename }, { session });
|
|
431
|
+
await migrate2.down(db, session);
|
|
432
|
+
});
|
|
433
|
+
terminal2.printSuccess(`[down] ${filename}`);
|
|
434
|
+
} catch (e) {
|
|
435
|
+
terminal2.printError(`[down] ${filename}`);
|
|
436
|
+
throw e;
|
|
437
|
+
}
|
|
397
438
|
}
|
|
398
439
|
}
|
|
399
440
|
if (!(opts.connection instanceof mongoose4.Connection)) {
|
|
@@ -402,7 +443,10 @@ var migrationDown = (opts) => {
|
|
|
402
443
|
},
|
|
403
444
|
help: {
|
|
404
445
|
onDocument(doc) {
|
|
405
|
-
doc[commandName3] = {
|
|
446
|
+
doc[commandName3] = {
|
|
447
|
+
summary: i18n.t("migration.down"),
|
|
448
|
+
parameters: [{ type: "boolean", name: "all", defaultValue: false }]
|
|
449
|
+
};
|
|
406
450
|
}
|
|
407
451
|
}
|
|
408
452
|
});
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/overrides/mongo-decimal128.validator.ts","../src/i18n/index.ts","../src/i18n/locales/zh-cn.ts","../src/i18n/locales/en-us.ts","../src/i18n/locales/index.ts","../src/overrides/mongo-object-id.validator.ts","../src/define-mongoose-model.ts","../src/libs/validator-to-schema.ts","../src/middleware/mongoose-migration.md.ts","../src/middleware/migration-create-file.md.ts","../src/middleware/migration-up.md.ts","../src/libs/sync-collection-index.ts","../src/models/migration.model.ts","../src/libs/migrate.ts","../src/middleware/migration-down.md.ts","../src/libs/format-mongo-result.ts"],"sourcesContent":["import {\n Validator,\n type TransformedValidator,\n ValidateResult,\n OpenAPI,\n Rule,\n} from '@aomex/common';\nimport { i18n } from '../i18n';\nimport { mongo } from 'mongoose';\n\nexport class MongoDecimal128Validator<T = mongo.Decimal128> extends Validator<T> {\n protected declare config: Validator.Options<T>;\n\n public declare docs: (\n docs: Validator.PartialOpenAPISchema,\n mode?: Validator.DocumentMergeMode,\n ) => this;\n public declare optional: () => MongoDecimal128Validator<T | Validator.TOptional>;\n public declare default: (\n decimal128: mongo.Decimal128,\n ) => MongoDecimal128Validator<T | Validator.TDefault>;\n public declare transform: <T1>(\n fn: Validator.TransformFn<T, T1>,\n ) => TransformedValidator<T1>;\n\n protected validateValue(\n value: any,\n _key: string,\n label: string,\n ): ValidateResult.Any<mongo.Decimal128> {\n if (value instanceof mongo.Decimal128) {\n return ValidateResult.accept(value);\n }\n\n try {\n return ValidateResult.accept(mongo.Decimal128.fromString(value));\n } catch {\n return ValidateResult.deny(\n i18n.t('validator.decimal128.must_be_decimal128', { label }),\n );\n }\n }\n\n protected declare copy: () => MongoDecimal128Validator<T>;\n\n protected override toDocument(): OpenAPI.SchemaObject {\n return {\n type: 'string',\n };\n }\n}\n\ndeclare module '@aomex/common' {\n export interface Rule {\n mongoDecimal128(): MongoDecimal128Validator;\n }\n}\n\nRule.register('mongoDecimal128', MongoDecimal128Validator);\n","import { I18n } from '@aomex/common';\nimport { locales } from './locales';\n\nexport const i18n = new I18n({\n resources: locales,\n defaultLanguage: 'zh_CN',\n});\n","import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n validator: {\n decimal128: {\n must_be_decimal128: '{{label}}:必须是 Decimal128 类型',\n },\n objectId: {\n must_be_objectId: '{{label}}:必须是 ObjectId 类型',\n },\n },\n mongoose: {\n unsupported_validator: '暂不支持 {{validator}} 验证器',\n },\n migration: {\n create: '创建迁移文件',\n up: '执行迁移逻辑',\n down: '回滚迁移逻辑',\n file_not_found: \"迁移文件 '{{file}}' 不存在\",\n },\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n validator: {\n decimal128: {\n must_be_decimal128: '{{label}}: must be Decimal128',\n },\n objectId: {\n must_be_objectId: '{{label}}: must be ObjectId',\n },\n },\n mongoose: {\n unsupported_validator: '{{validator} is not supported yet',\n },\n migration: {\n create: 'Generate migration file',\n up: 'Execute migration logic',\n down: 'Rollback migration logic',\n file_not_found: \"Migration file '{{file}}' not found\",\n },\n});\n","import { zh } from './zh-cn';\nimport { en } from './en-us';\n\nexport const locales = {\n zh_CN: zh,\n en_US: en,\n};\n","import {\n Validator,\n type TransformedValidator,\n ValidateResult,\n OpenAPI,\n Rule,\n} from '@aomex/common';\nimport { i18n } from '../i18n';\nimport { mongo } from 'mongoose';\n\nexport class MongoObjectIdValidator<T = mongo.ObjectId> extends Validator<T> {\n protected declare config: Validator.Options<T>;\n\n public declare docs: (\n docs: Validator.PartialOpenAPISchema,\n mode?: Validator.DocumentMergeMode,\n ) => this;\n public declare optional: () => MongoObjectIdValidator<T | Validator.TOptional>;\n public declare default: (\n objectId: mongo.ObjectId,\n ) => MongoObjectIdValidator<T | Validator.TDefault>;\n public declare transform: <T1>(\n fn: Validator.TransformFn<T, T1>,\n ) => TransformedValidator<T1>;\n\n protected validateValue(\n value: any,\n _key: string,\n label: string,\n ): ValidateResult.Any<mongo.ObjectId> {\n if (value instanceof mongo.ObjectId) {\n return ValidateResult.accept(value);\n }\n\n try {\n return ValidateResult.accept(mongo.ObjectId.createFromHexString(String(value)));\n } catch {\n return ValidateResult.deny(\n i18n.t('validator.objectId.must_be_objectId', { label }),\n );\n }\n }\n\n protected declare copy: () => MongoObjectIdValidator<T>;\n\n protected override toDocument(): OpenAPI.SchemaObject {\n return {\n type: 'string',\n };\n }\n}\n\ndeclare module '@aomex/common' {\n export interface Rule {\n mongoObjectId(): MongoObjectIdValidator;\n }\n}\n\nRule.register('mongoObjectId', MongoObjectIdValidator);\n","import type {\n AnyValidator,\n ArrayValidator,\n BooleanValidator,\n DateValidator,\n NumberValidator,\n ObjectValidator,\n StringValidator,\n Validator,\n} from '@aomex/common';\nimport type { NonReadonly } from '@aomex/internal-tools';\nimport {\n Model,\n type IndexDirection,\n type IndexOptions,\n type SchemaOptions,\n type SchemaDefinition,\n Schema,\n model,\n type HydratedDocument,\n} from 'mongoose';\nimport type { TimestampSetting, VersionKeySetting } from './type-d';\nimport { validatorToSchema } from './libs/validator-to-schema';\nimport type { MongoDecimal128Validator } from './overrides/mongo-decimal128.validator';\nimport type { MongoObjectIdValidator } from './overrides/mongo-object-id.validator';\n\nexport const defineMongooseModel = <\n const Schema extends {\n [field: string]:\n | StringValidator<any>\n | NumberValidator<any>\n | BooleanValidator<any>\n | ObjectValidator<any>\n | ArrayValidator<any>\n | DateValidator<any>\n | AnyValidator<any>\n | MongoDecimal128Validator<any>\n | MongoObjectIdValidator<any>;\n },\n Ver extends SchemaOptions['versionKey'],\n const Time extends SchemaOptions['timestamps'],\n Output = NonReadonly<Validator.Infer<Schema>> &\n TimestampSetting<Time> &\n VersionKeySetting<Ver>,\n>(\n collectionName: string,\n opts: {\n readonly schemas: Schema;\n readonly indexes?: ({\n fields: { [K in keyof Schema]?: IndexDirection };\n } & IndexOptions)[];\n readonly timestamps?: Time;\n readonly versionKey?: Ver;\n } & Omit<SchemaOptions, 'timestamps' | 'versionKey'>,\n): Model<Output, {}, {}, {}, HydratedDocument<Output>, Schema> => {\n const { schemas, indexes, ...schemaOptions } = opts;\n\n const definition: SchemaDefinition = {};\n Object.entries(schemas).forEach(([key, schema]) => {\n definition[key] = validatorToSchema(schema);\n });\n const schema = new Schema(definition, {\n collection: collectionName,\n ...schemaOptions,\n });\n\n indexes?.forEach(({ fields, ...indexRest }) => {\n schema.index(\n // @ts-expect-error\n fields,\n indexRest,\n );\n });\n\n const customModel = model(collectionName, schema);\n return customModel as Model<any>;\n};\n","import {\n AnyValidator,\n ArrayValidator,\n BooleanValidator,\n DateValidator,\n NumberValidator,\n ObjectValidator,\n StringValidator,\n Validator,\n} from '@aomex/common';\nimport { Schema, SchemaTypes, type SchemaDefinition } from 'mongoose';\nimport { MongoDecimal128Validator } from '../overrides/mongo-decimal128.validator';\nimport { i18n } from '../i18n';\nimport { MongoObjectIdValidator } from '../overrides/mongo-object-id.validator';\n\nexport const validatorToSchema = (validator: Validator) => {\n const defaultValue = validator['config']['nullable']\n ? null\n : validator['config']['defaultValue'];\n const schema: SchemaDefinition[string] = {\n required: defaultValue === undefined && validator['config']['required'],\n default: defaultValue,\n };\n\n if (validator instanceof StringValidator) {\n schema.type = SchemaTypes.String;\n } else if (validator instanceof NumberValidator) {\n schema.type = SchemaTypes.Number;\n } else if (validator instanceof BooleanValidator) {\n schema.type = SchemaTypes.Boolean;\n } else if (validator instanceof MongoDecimal128Validator) {\n schema.type = SchemaTypes.Decimal128;\n } else if (validator instanceof ArrayValidator) {\n const items = validator['config']['itemValidator'];\n if (items) {\n schema.type = [validatorToSchema(items)];\n } else {\n schema.type = SchemaTypes.Array;\n }\n } else if (validator instanceof ObjectValidator) {\n schema.type = SchemaTypes.Map;\n const properties = validator['config']['properties'];\n if (properties) {\n schema.type = new Schema(\n Object.fromEntries(\n Object.entries(properties).map(\n ([key, value]) => <const>[key, validatorToSchema(value)],\n ),\n ),\n { _id: false, timestamps: false, versionKey: false },\n );\n }\n } else if (validator instanceof DateValidator) {\n schema.type = SchemaTypes.Date;\n } else if (validator instanceof MongoObjectIdValidator) {\n schema.type = SchemaTypes.ObjectId;\n } else if (validator instanceof AnyValidator) {\n schema.type = SchemaTypes.Mixed;\n } else {\n throw new Error(\n i18n.t('mongoose.unsupported_validator', { validator: validator.constructor.name }),\n );\n }\n\n return schema;\n};\n","import { compose, middleware } from '@aomex/common';\nimport type { ConsoleMiddleware } from '@aomex/console';\nimport { migrationCreateFile } from './migration-create-file.md';\nimport { migrationUp } from './migration-up.md';\nimport { migrationDown } from './migration-down.md';\nimport type { Connection, ConnectOptions } from 'mongoose';\n\nexport interface MigrationOptions {\n /**\n * 模型存放位置,用于执行`mongoose.syncIndexes()`同步索引。默认值:`src/models`\n */\n modelsPath?: string;\n /**\n * 迁移文件存放位置。默认值:`src/migrations`\n */\n migrationsPath?: string;\n /**\n * 连接参数。如果已经连接并且拥有读写权限,则可以传入`mongoose.connection`\n */\n connection:\n | Connection\n | {\n uri: string;\n options?: ConnectOptions;\n };\n}\n\nexport const mongooseMigration = (opts: MigrationOptions): ConsoleMiddleware => {\n const {\n migrationsPath = 'src/migrations',\n modelsPath = 'src/models',\n connection,\n } = opts;\n const middlewareList = [\n migrationCreateFile(migrationsPath),\n migrationUp({ migrationsPath, connection, modelsPath }),\n migrationDown({ migrationsPath, connection, modelsPath }),\n ];\n\n return middleware.console({\n fn: compose(middlewareList),\n help: {\n async onDocument(_, { children }) {\n await children(middlewareList);\n },\n async postDocument(_, { children }) {\n await children(middlewareList);\n },\n },\n });\n};\n","import { middleware, rule, validate } from '@aomex/common';\nimport type { ConsoleMiddleware } from '@aomex/console';\nimport snakeCase from 'lodash.snakecase';\nimport { i18n } from '../i18n';\nimport path from 'node:path';\nimport { mkdir, writeFile } from 'node:fs/promises';\n\nconst commandName = 'mongoose:migration:create';\n\nexport const migrationCreateFile = (migrationsPath: string): ConsoleMiddleware => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n ctx.commandMatched = true;\n\n const { name } = await validate(ctx.input.parseArgv(), {\n name: rule.string().optional().trim().transform(snakeCase),\n });\n const filename = `${new Date().toISOString().replaceAll(/[-TZ.:]/gi, '')}_${name}.ts`;\n const fullPath = path.join(migrationsPath, filename);\n await mkdir(path.dirname(fullPath), { recursive: true });\n await writeFile(\n fullPath,\n `import { migrate } from '@aomex/mongoose';\n\nexport default migrate({\n up: async (db, session) => {\n // up transaction\n },\n down: async (db, session) => {\n // down transaction\n },\n});\n`,\n );\n },\n help: {\n onDocument(doc) {\n doc[commandName] = {\n summary: i18n.t('migration.create'),\n parameters: [{ type: 'string', name: 'name' }],\n };\n },\n },\n });\n};\n","import { middleware } from '@aomex/common';\nimport type { MigrationOptions } from './mongoose-migration.md';\nimport { i18n } from '../i18n';\nimport { syncCollectionIndex } from '../libs/sync-collection-index';\nimport { MigrationModel } from '../models/migration.model';\nimport { pathToFiles } from '@aomex/internal-file-import';\nimport path from 'node:path';\nimport { Migrate } from '../libs/migrate';\nimport mongoose, { createConnection } from 'mongoose';\nimport { terminal } from '@aomex/console';\nimport { mkdir } from 'node:fs/promises';\n\nconst commandName = 'mongoose:migration:up';\n\nexport const migrationUp = (opts: Required<MigrationOptions>) => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n ctx.commandMatched = true;\n\n const connection =\n opts.connection instanceof mongoose.Connection\n ? opts.connection\n : await createConnection(\n opts.connection.uri,\n opts.connection.options,\n ).asPromise();\n const db = connection.db!;\n\n await syncCollectionIndex(opts.modelsPath);\n\n const migratedRows = await MigrationModel.find().sort({ filename: 'asc' }).lean();\n const migratedFiles = migratedRows.map((item) => item.filename);\n await mkdir(opts.migrationsPath, { recursive: true });\n const allFiles = await pathToFiles(opts.migrationsPath);\n const waitingMigrateFiles = allFiles\n .filter(\n (item) => !migratedFiles.includes(path.basename(item, path.extname(item))),\n )\n .sort();\n\n for (const filePath of waitingMigrateFiles) {\n const instance = await import(filePath);\n const migrate = instance.default;\n if (migrate instanceof Migrate) {\n const filename = path.basename(filePath, path.extname(filePath));\n try {\n await connection.transaction(async (session) => {\n await MigrationModel.create([{ filename }], { session });\n await migrate.up(db, session);\n await MigrationModel.updateOne(\n { filename },\n { finished_at: new Date() },\n { session },\n );\n });\n terminal.printSuccess(`[up] ${filename}`);\n } catch (e) {\n terminal.printError(`[up] ${filename}`);\n throw e;\n }\n }\n }\n\n if (!(opts.connection instanceof mongoose.Connection)) {\n await connection.close();\n }\n },\n help: {\n onDocument(doc) {\n doc[commandName] = { summary: i18n.t('migration.up') };\n },\n },\n });\n};\n","import { getFileValues, pathToFiles } from '@aomex/internal-file-import';\nimport mongoose from 'mongoose';\nimport { mkdir } from 'node:fs/promises';\n\nexport const syncCollectionIndex = async (modelsPath: string) => {\n await mkdir(modelsPath, { recursive: true });\n const files = await pathToFiles(modelsPath);\n await getFileValues(files);\n await mongoose.syncIndexes();\n};\n","import { rule } from '@aomex/common';\nimport { defineMongooseModel } from '../define-mongoose-model';\n\nexport const MigrationModel = defineMongooseModel('__aomex_migration__', {\n schemas: {\n filename: rule.string(),\n finished_at: rule.date().nullable(),\n },\n versionKey: false,\n timestamps: { createdAt: 'created_at', updatedAt: false },\n indexes: [\n {\n fields: { filename: 'asc' },\n unique: true,\n },\n ],\n});\n","import mongoose from 'mongoose';\n\ninterface Operation {\n (db: mongoose.mongo.Db, session: mongoose.mongo.ClientSession): Promise<any>;\n}\n\n/**\n * 迁移数据,因为开启了事务,所以任何操作都需要带上session,这样能保证出错时顺利回滚数据。\n *\n * 注意:集合和索引会根据models自动同步,无须写迁移逻辑。\n */\nexport const migrate = (opts: { up: Operation; down: Operation }) => {\n return new Migrate(opts.up, opts.down);\n};\n\nexport class Migrate {\n constructor(\n public readonly up: Operation,\n public readonly down: Operation,\n ) {}\n}\n","import { middleware } from '@aomex/common';\nimport type { MigrationOptions } from './mongoose-migration.md';\nimport { i18n } from '../i18n';\nimport { syncCollectionIndex } from '../libs/sync-collection-index';\nimport { MigrationModel } from '../models/migration.model';\nimport { Migrate } from '../libs/migrate';\nimport mongoose, { createConnection } from 'mongoose';\nimport { terminal } from '@aomex/console';\nimport { pathToFiles } from '@aomex/internal-file-import';\nimport { mkdir } from 'node:fs/promises';\nimport path from 'node:path';\n\nconst commandName = 'mongoose:migration:down';\n\nexport const migrationDown = (opts: Required<MigrationOptions>) => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n ctx.commandMatched = true;\n\n const connection =\n opts.connection instanceof mongoose.Connection\n ? opts.connection\n : await createConnection(\n opts.connection.uri,\n opts.connection.options,\n ).asPromise();\n const db = connection.db!;\n\n await syncCollectionIndex(opts.modelsPath);\n\n const lastMigratedRow = await MigrationModel.findOne()\n .sort({ filename: 'desc' })\n .lean();\n const filename = lastMigratedRow?.filename;\n if (!filename) return;\n await mkdir(opts.migrationsPath, { recursive: true });\n const allFiles = await pathToFiles(opts.migrationsPath);\n const fullPath = allFiles.find((item) =>\n item.endsWith(filename + path.extname(item)),\n );\n\n if (!fullPath) {\n throw new Error(i18n.t('migration.file_not_found', { file: filename }));\n }\n\n const instance = await import(fullPath);\n const migrate = instance.default;\n if (migrate instanceof Migrate) {\n try {\n await connection.transaction(async (session) => {\n await MigrationModel.deleteOne({ _id: lastMigratedRow._id }, { session });\n await migrate.down(db, session);\n });\n terminal.printSuccess(`[down] ${filename}`);\n } catch (e) {\n terminal.printError(`[down] ${filename}`);\n throw e;\n }\n }\n\n if (!(opts.connection instanceof mongoose.Connection)) {\n await connection.close();\n }\n },\n help: {\n onDocument(doc) {\n doc[commandName] = { summary: i18n.t('migration.down') };\n },\n },\n });\n};\n","import {\n Document,\n mongo,\n type Default__v,\n type FlattenMaps,\n type Require_id,\n} from 'mongoose';\n\nexport type MongoResult<T, Remove extends boolean> = {\n [K in keyof T as K extends '__v'\n ? never\n : Remove extends true\n ? K extends (typeof excludedFields)[number]\n ? never\n : K\n : K extends '_id'\n ? 'id'\n : K]: T[K] extends mongo.Decimal128 | mongo.ObjectId ? string : T[K];\n};\n\nconst excludedFields = <const>[\n 'created_at',\n 'createdAt',\n 'updated_at',\n 'updatedAt',\n '_id',\n];\n\nexport function formatMongoResult<T extends Document, Remove extends boolean>(\n data: T[],\n removeColumns?: Remove,\n): MongoResult<\n T extends Document<any, any, infer R> ? FlattenMaps<Default__v<Require_id<R>>> : never,\n Remove\n>[];\nexport function formatMongoResult<T extends Record<string, any>, Remove extends boolean>(\n data: T[],\n removeColumns?: Remove,\n): MongoResult<T, Remove>[];\nexport function formatMongoResult<T extends Document | null, Remove extends boolean>(\n data: T,\n removeColumns?: Remove,\n): T extends Document\n ? MongoResult<\n T extends Document<any, any, infer R>\n ? FlattenMaps<Default__v<Require_id<R>>>\n : never,\n Remove\n >\n : null;\nexport function formatMongoResult<\n T extends Record<string, any> | null,\n Remove extends boolean,\n>(\n data: T,\n removeColumns?: Remove,\n): T extends Record<string, any> ? MongoResult<T, Remove> : null;\n/**\n * 格式化mongo查询结果,支持传入 纯JSON 和 Document 两种对象格式,返回结果遵循如下规则:\n * - 去掉 __v 字段\n * - decimal128类型 转为 字符串\n * - objectId类型 转为 字符串\n * - removeColumns=true时,去掉 _id 字段\n * - removeColumns=false时,_id 字段转为 id\n * - removeColumns=true时,去掉 createdAt/created_at 字段\n * - removeColumns=true时,去掉 updatedAt/updated_at 字段\n *\n * @param {Boolean} removeColumns 是否去掉数据库扩展的字段\n */\nexport function formatMongoResult(\n data: Record<string, any> | Record<string, any>[] | Document | Document[] | null,\n removeColumns: boolean = false,\n) {\n if (data == null) return null;\n\n const newDate = (Array.isArray(data) ? data : [data]).map((item) => {\n if (item instanceof Document) {\n item = item.toJSON({ flattenMaps: true });\n }\n\n const newItem: Record<string, any> = {};\n for (let [key, value] of Object.entries(item)) {\n if (key === '__v') continue;\n if (removeColumns && excludedFields.includes(key as any)) continue;\n if (key === '_id') key = 'id';\n\n if (value instanceof mongo.Decimal128) {\n newItem[key] = value.toString();\n } else if (value instanceof mongo.ObjectId) {\n newItem[key] = value.toHexString();\n } else {\n newItem[key] = value;\n }\n }\n return newItem;\n });\n return Array.isArray(data) ? newDate : newDate[0];\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,OACK;;;ACNP,SAAS,QAAAA,aAAY;;;ACArB,SAAS,YAAY;AAEd,IAAM,KAAK,KAAK,OAAO;AAAA,EAC5B,WAAW;AAAA,IACT,YAAY;AAAA,MACV,oBAAoB;AAAA,IACtB;AAAA,IACA,UAAU;AAAA,MACR,kBAAkB;AAAA,IACpB;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR,uBAAuB;AAAA,EACzB;AAAA,EACA,WAAW;AAAA,IACT,QAAQ;AAAA,IACR,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,gBAAgB;AAAA,EAClB;AACF,CAAC;;;ACpBD,SAAS,QAAAC,aAAY;AAGd,IAAM,KAAKC,MAAK,UAAU,EAAE,EAAE,OAAO;AAAA,EAC1C,WAAW;AAAA,IACT,YAAY;AAAA,MACV,oBAAoB;AAAA,IACtB;AAAA,IACA,UAAU;AAAA,MACR,kBAAkB;AAAA,IACpB;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR,uBAAuB;AAAA,EACzB;AAAA,EACA,WAAW;AAAA,IACT,QAAQ;AAAA,IACR,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,gBAAgB;AAAA,EAClB;AACF,CAAC;;;AClBM,IAAM,UAAU;AAAA,EACrB,OAAO;AAAA,EACP,OAAO;AACT;;;AHHO,IAAM,OAA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ValidateResult","Rule","mongo","Validator","ValidateResult","Rule","Schema","schema","Schema","middleware","middleware","mkdir","rule","rule","pathToFiles","path","mongoose","mkdir","commandName","middleware","pathToFiles","path","migrate","middleware","mongoose","createConnection","terminal","pathToFiles","mkdir","path","commandName","middleware","migrate","middleware","mongo"]}
|
|
1
|
+
{"version":3,"sources":["../src/validators/mongo-decimal128.validator.ts","../src/i18n/index.ts","../src/i18n/locales/zh-cn.ts","../src/i18n/locales/en-us.ts","../src/i18n/locales/index.ts","../src/validators/mongo-object-id.validator.ts","../src/define-mongoose-model.ts","../src/libs/validator-to-schema.ts","../src/middleware/mongoose-migration.md.ts","../src/middleware/migration-create-file.md.ts","../src/middleware/migration-up.md.ts","../src/libs/sync-collection-index.ts","../src/models/migration.model.ts","../src/libs/migrate.ts","../src/middleware/migration-down.md.ts","../src/libs/format-mongo-result.ts"],"sourcesContent":["import {\n Validator,\n type TransformedValidator,\n ValidateResult,\n OpenAPI,\n Rule,\n} from '@aomex/common';\nimport { i18n } from '../i18n';\nimport { mongo } from 'mongoose';\n\nexport class MongoDecimal128Validator<T = mongo.Decimal128> extends Validator<T> {\n protected declare config: Validator.Options<T>;\n\n public declare docs: (\n docs: Validator.PartialOpenAPISchema,\n mode?: Validator.DocumentMergeMode,\n ) => this;\n public declare optional: () => MongoDecimal128Validator<T | Validator.TOptional>;\n public declare nullable: () => MongoDecimal128Validator<T | null>;\n public declare transform: <T1>(\n fn: Validator.TransformFn<T, T1>,\n ) => TransformedValidator<T1>;\n\n override default(\n value: number | string | mongo.Decimal128,\n ): MongoDecimal128Validator<T | Validator.TDefault> {\n const validator = super.default(\n typeof value === 'string' || typeof value === 'number'\n ? mongo.Decimal128.fromString(value.toString())\n : value,\n );\n return validator as MongoDecimal128Validator<T | Validator.TDefault>;\n }\n\n protected validateValue(\n value: any,\n _key: string,\n label: string,\n ): ValidateResult.Any<mongo.Decimal128> {\n if (value instanceof mongo.Decimal128) {\n return ValidateResult.accept(value);\n }\n\n try {\n return ValidateResult.accept(mongo.Decimal128.fromString(value));\n } catch {\n return ValidateResult.deny(\n i18n.t('validator.decimal128.must_be_decimal128', { label }),\n );\n }\n }\n\n protected declare copy: () => MongoDecimal128Validator<T>;\n\n protected override toDocument(): OpenAPI.SchemaObject {\n const defaultValue: mongo.Decimal128 | undefined = this.getDefaultValue(\n this.config.defaultValue,\n );\n return {\n type: 'string',\n default: defaultValue && defaultValue.toString(),\n };\n }\n}\n\ndeclare module '@aomex/common' {\n export interface Rule {\n mongoDecimal128(): MongoDecimal128Validator;\n }\n}\n\nRule.register('mongoDecimal128', MongoDecimal128Validator);\n","import { I18n } from '@aomex/common';\nimport { locales } from './locales';\n\nexport const i18n = new I18n({\n resources: locales,\n defaultLanguage: 'zh_CN',\n});\n","import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n validator: {\n decimal128: {\n must_be_decimal128: '{{label}}:必须是 Decimal128 类型',\n },\n objectId: {\n must_be_objectId: '{{label}}:必须是 ObjectId 类型',\n },\n },\n mongoose: {\n unsupported_validator: '暂不支持 {{validator}} 验证器',\n },\n migration: {\n create: '创建迁移文件',\n up: '执行迁移逻辑',\n down: '回滚迁移逻辑',\n file_not_found: \"迁移文件 '{{file}}' 不存在\",\n input_file_name: '迁移文件名是什么?',\n },\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n validator: {\n decimal128: {\n must_be_decimal128: '{{label}}: must be Decimal128',\n },\n objectId: {\n must_be_objectId: '{{label}}: must be ObjectId',\n },\n },\n mongoose: {\n unsupported_validator: '{{validator} is not supported yet',\n },\n migration: {\n create: 'Generate migration file',\n up: 'Execute migration logic',\n down: 'Rollback migration logic',\n file_not_found: \"Migration file '{{file}}' not found\",\n input_file_name: 'What is migration file name?',\n },\n});\n","import { zh } from './zh-cn';\nimport { en } from './en-us';\n\nexport const locales = {\n zh_CN: zh,\n en_US: en,\n};\n","import {\n Validator,\n type TransformedValidator,\n ValidateResult,\n OpenAPI,\n Rule,\n} from '@aomex/common';\nimport { i18n } from '../i18n';\nimport { mongo } from 'mongoose';\n\nexport class MongoObjectIdValidator<T = mongo.ObjectId> extends Validator<T> {\n protected declare config: Validator.Options<T>;\n\n public declare docs: (\n docs: Validator.PartialOpenAPISchema,\n mode?: Validator.DocumentMergeMode,\n ) => this;\n public declare optional: () => MongoObjectIdValidator<T | Validator.TOptional>;\n public declare nullable: () => MongoObjectIdValidator<T | null>;\n public declare transform: <T1>(\n fn: Validator.TransformFn<T, T1>,\n ) => TransformedValidator<T1>;\n\n override default(\n value: string | mongo.ObjectId,\n ): MongoObjectIdValidator<T | Validator.TDefault> {\n const validator = super.default(\n typeof value === 'string'\n ? mongo.ObjectId.createFromHexString(value.toString())\n : value,\n );\n return validator as MongoObjectIdValidator<T | Validator.TDefault>;\n }\n\n protected validateValue(\n value: any,\n _key: string,\n label: string,\n ): ValidateResult.Any<mongo.ObjectId> {\n if (value instanceof mongo.ObjectId) {\n return ValidateResult.accept(value);\n }\n\n try {\n return ValidateResult.accept(mongo.ObjectId.createFromHexString(String(value)));\n } catch {\n return ValidateResult.deny(\n i18n.t('validator.objectId.must_be_objectId', { label }),\n );\n }\n }\n\n protected declare copy: () => MongoObjectIdValidator<T>;\n\n protected override toDocument(): OpenAPI.SchemaObject {\n const defaultValue: mongo.ObjectId | undefined = this.getDefaultValue(\n this.config.defaultValue,\n );\n return {\n type: 'string',\n default: defaultValue && defaultValue.toHexString(),\n };\n }\n}\n\ndeclare module '@aomex/common' {\n export interface Rule {\n mongoObjectId(): MongoObjectIdValidator;\n }\n}\n\nRule.register('mongoObjectId', MongoObjectIdValidator);\n","import type {\n AnyValidator,\n ArrayValidator,\n BooleanValidator,\n DateValidator,\n NumberValidator,\n ObjectValidator,\n StringValidator,\n Validator,\n} from '@aomex/common';\nimport type { NonReadonly } from '@aomex/internal-tools';\nimport {\n Model,\n type IndexDirection,\n type IndexOptions,\n type SchemaOptions,\n type SchemaDefinition,\n Schema,\n model,\n type HydratedDocument,\n} from 'mongoose';\nimport type { TimestampSetting, VersionKeySetting } from './type-d';\nimport { validatorToSchema } from './libs/validator-to-schema';\nimport type { MongoDecimal128Validator, MongoObjectIdValidator } from './validators';\n\nexport const defineMongooseModel = <\n const Schema extends {\n [field: string]:\n | StringValidator<any>\n | NumberValidator<any>\n | BooleanValidator<any>\n | ObjectValidator<any>\n | ArrayValidator<any>\n | DateValidator<any>\n | AnyValidator<any>\n | MongoDecimal128Validator<any>\n | MongoObjectIdValidator<any>;\n },\n Ver extends SchemaOptions['versionKey'],\n const Time extends SchemaOptions['timestamps'],\n Output = NonReadonly<Validator.Infer<Schema>> &\n TimestampSetting<Time> &\n VersionKeySetting<Ver>,\n>(\n collectionName: string,\n opts: {\n readonly schemas: Schema;\n readonly indexes?: ({\n fields: { [K in keyof Schema]?: IndexDirection };\n } & IndexOptions)[];\n readonly timestamps?: Time;\n readonly versionKey?: Ver;\n } & Omit<SchemaOptions, 'timestamps' | 'versionKey'>,\n): Model<Output, {}, {}, {}, HydratedDocument<Output>, Schema> => {\n const { schemas, indexes, ...schemaOptions } = opts;\n\n const definition: SchemaDefinition = {};\n Object.entries(schemas).forEach(([key, schema]) => {\n definition[key] = validatorToSchema(schema);\n });\n const schema = new Schema(definition, {\n collection: collectionName,\n ...schemaOptions,\n });\n\n indexes?.forEach(({ fields, ...indexRest }) => {\n schema.index(\n // @ts-expect-error\n fields,\n indexRest,\n );\n });\n\n const customModel = model(collectionName, schema);\n return customModel as Model<any>;\n};\n","import {\n AnyValidator,\n ArrayValidator,\n BooleanValidator,\n DateValidator,\n NumberValidator,\n ObjectValidator,\n StringValidator,\n Validator,\n} from '@aomex/common';\nimport { Schema, SchemaTypes, type SchemaDefinition } from 'mongoose';\nimport { i18n } from '../i18n';\nimport { MongoDecimal128Validator, MongoObjectIdValidator } from '../validators';\n\nexport const validatorToSchema = (validator: Validator) => {\n const defaultValue = validator['config']['nullable']\n ? null\n : validator['config']['defaultValue'];\n const schema: SchemaDefinition[string] = {\n required: defaultValue === undefined && validator['config']['required'],\n default: defaultValue,\n };\n\n if (validator instanceof StringValidator) {\n schema.type = SchemaTypes.String;\n } else if (validator instanceof NumberValidator) {\n schema.type = SchemaTypes.Number;\n } else if (validator instanceof BooleanValidator) {\n schema.type = SchemaTypes.Boolean;\n } else if (validator instanceof MongoDecimal128Validator) {\n schema.type = SchemaTypes.Decimal128;\n } else if (validator instanceof ArrayValidator) {\n const items = validator['config']['itemValidator'];\n if (items) {\n schema.type = [validatorToSchema(items)];\n } else {\n schema.type = SchemaTypes.Array;\n }\n } else if (validator instanceof ObjectValidator) {\n schema.type = SchemaTypes.Map;\n const properties = validator['config']['properties'];\n if (properties) {\n schema.type = new Schema(\n Object.fromEntries(\n Object.entries(properties).map(\n ([key, value]) => <const>[key, validatorToSchema(value)],\n ),\n ),\n { _id: false, timestamps: false, versionKey: false },\n );\n }\n } else if (validator instanceof DateValidator) {\n schema.type = SchemaTypes.Date;\n } else if (validator instanceof MongoObjectIdValidator) {\n schema.type = SchemaTypes.ObjectId;\n } else if (validator instanceof AnyValidator) {\n schema.type = SchemaTypes.Mixed;\n } else {\n throw new Error(\n i18n.t('mongoose.unsupported_validator', { validator: validator.constructor.name }),\n );\n }\n\n return schema;\n};\n","import { compose, middleware } from '@aomex/common';\nimport type { ConsoleMiddleware } from '@aomex/console';\nimport { migrationCreateFile } from './migration-create-file.md';\nimport { migrationUp } from './migration-up.md';\nimport { migrationDown } from './migration-down.md';\nimport type { Connection, ConnectOptions } from 'mongoose';\n\nexport interface MigrationOptions {\n /**\n * 模型存放位置,用于执行`mongoose.syncIndexes()`同步索引。默认值:`src/models`\n */\n modelsPath?: string;\n /**\n * 迁移文件存放位置。默认值:`src/migrations`\n */\n migrationsPath?: string;\n /**\n * 连接参数。如果已经连接并且拥有读写权限,则可以传入`mongoose.connection`\n */\n connection:\n | Connection\n | {\n uri: string;\n options?: ConnectOptions;\n };\n}\n\nexport const mongooseMigration = (opts: MigrationOptions): ConsoleMiddleware => {\n const {\n migrationsPath = 'src/migrations',\n modelsPath = 'src/models',\n connection,\n } = opts;\n const middlewareList = [\n migrationCreateFile(migrationsPath),\n migrationUp({ migrationsPath, connection, modelsPath }),\n migrationDown({ migrationsPath, connection, modelsPath }),\n ];\n\n return middleware.console({\n fn: compose(middlewareList),\n help: {\n async onDocument(_, { children }) {\n await children(middlewareList);\n },\n async postDocument(_, { children }) {\n await children(middlewareList);\n },\n },\n });\n};\n","import { middleware, rule, validate } from '@aomex/common';\nimport type { ConsoleMiddleware } from '@aomex/console';\nimport snakeCase from 'lodash.snakecase';\nimport { i18n } from '../i18n';\nimport path from 'node:path';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { createInterface } from 'node:readline/promises';\n\nconst commandName = 'mongoose:migration:create';\n\nexport const migrationCreateFile = (migrationsPath: string): ConsoleMiddleware => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n ctx.commandMatched = true;\n\n let { name } = await validate(ctx.input.parseArgv(), {\n name: rule.string().optional().trim().transform(snakeCase),\n });\n\n if (!name) {\n const readline = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n while (!name) {\n name = await readline.question(i18n.t('migration.input_file_name'));\n name = snakeCase(name.trim());\n }\n readline.close();\n }\n\n const filename = `${new Date().toISOString().replaceAll(/[-TZ.:]/gi, '')}_${name}.ts`;\n const fullPath = path.join(migrationsPath, filename);\n await mkdir(path.dirname(fullPath), { recursive: true });\n await writeFile(\n fullPath,\n `import { migrate } from '@aomex/mongoose';\n\nexport default migrate({\n up: async (db, session) => {\n // up transaction\n },\n down: async (db, session) => {\n // down transaction\n },\n});\n`,\n );\n },\n help: {\n onDocument(doc) {\n doc[commandName] = {\n summary: i18n.t('migration.create'),\n parameters: [{ type: 'string', name: 'name' }],\n };\n },\n },\n });\n};\n","import { middleware } from '@aomex/common';\nimport type { MigrationOptions } from './mongoose-migration.md';\nimport { i18n } from '../i18n';\nimport { syncCollectionIndex } from '../libs/sync-collection-index';\nimport { MigrationModel } from '../models/migration.model';\nimport { pathToFiles } from '@aomex/internal-file-import';\nimport path from 'node:path';\nimport { Migrate } from '../libs/migrate';\nimport mongoose, { createConnection } from 'mongoose';\nimport { terminal } from '@aomex/console';\nimport { mkdir } from 'node:fs/promises';\n\nconst commandName = 'mongoose:migration:up';\n\nexport const migrationUp = (opts: Required<MigrationOptions>) => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n ctx.commandMatched = true;\n\n const connection =\n opts.connection instanceof mongoose.Connection\n ? opts.connection\n : await createConnection(\n opts.connection.uri,\n opts.connection.options,\n ).asPromise();\n const db = connection.db!;\n\n await syncCollectionIndex(opts.modelsPath);\n\n const migratedRows = await MigrationModel.find().sort({ filename: 'asc' }).lean();\n const migratedFiles = migratedRows.map((item) => item.filename);\n await mkdir(opts.migrationsPath, { recursive: true });\n const allFiles = await pathToFiles(opts.migrationsPath);\n const waitingMigrateFiles = allFiles\n .filter(\n (item) => !migratedFiles.includes(path.basename(item, path.extname(item))),\n )\n .sort();\n\n for (const filePath of waitingMigrateFiles) {\n const instance = await import(filePath);\n const migrate = instance.default;\n if (migrate instanceof Migrate) {\n const filename = path.basename(filePath, path.extname(filePath));\n try {\n await connection.transaction(async (session) => {\n await MigrationModel.create([{ filename }], { session });\n await migrate.up(db, session);\n await MigrationModel.updateOne(\n { filename },\n { finished_at: new Date() },\n { session },\n );\n });\n terminal.printSuccess(`[up] ${filename}`);\n } catch (e) {\n terminal.printError(`[up] ${filename}`);\n throw e;\n }\n }\n }\n\n if (!(opts.connection instanceof mongoose.Connection)) {\n await connection.close();\n }\n },\n help: {\n onDocument(doc) {\n doc[commandName] = { summary: i18n.t('migration.up') };\n },\n },\n });\n};\n","import { getFileValues, pathToFiles } from '@aomex/internal-file-import';\nimport mongoose from 'mongoose';\nimport { mkdir } from 'node:fs/promises';\n\nexport const syncCollectionIndex = async (modelsPath: string) => {\n await mkdir(modelsPath, { recursive: true });\n const files = await pathToFiles(modelsPath);\n await getFileValues(files);\n await mongoose.syncIndexes();\n};\n","import { rule } from '@aomex/common';\nimport { defineMongooseModel } from '../define-mongoose-model';\n\nexport const MigrationModel = defineMongooseModel('__aomex_migration__', {\n schemas: {\n filename: rule.string(),\n finished_at: rule.date().nullable(),\n },\n versionKey: false,\n timestamps: { createdAt: 'created_at', updatedAt: false },\n indexes: [\n {\n fields: { filename: 'asc' },\n unique: true,\n },\n ],\n});\n","import mongoose from 'mongoose';\n\ninterface Operation {\n (db: mongoose.mongo.Db, session: mongoose.mongo.ClientSession): Promise<any>;\n}\n\n/**\n * 迁移数据,因为开启了事务,所以任何操作都需要带上session,这样能保证出错时顺利回滚数据。\n *\n * 注意:集合和索引会根据models自动同步,无须写迁移逻辑。\n */\nexport const migrate = (opts: { up: Operation; down: Operation }) => {\n return new Migrate(opts.up, opts.down);\n};\n\nexport class Migrate {\n constructor(\n public readonly up: Operation,\n public readonly down: Operation,\n ) {}\n}\n","import { middleware, rule, validate } from '@aomex/common';\nimport type { MigrationOptions } from './mongoose-migration.md';\nimport { i18n } from '../i18n';\nimport { syncCollectionIndex } from '../libs/sync-collection-index';\nimport { MigrationModel } from '../models/migration.model';\nimport { Migrate } from '../libs/migrate';\nimport mongoose, { createConnection } from 'mongoose';\nimport { terminal } from '@aomex/console';\nimport { pathToFiles } from '@aomex/internal-file-import';\nimport { mkdir } from 'node:fs/promises';\nimport path from 'node:path';\n\nconst commandName = 'mongoose:migration:down';\n\nexport const migrationDown = (opts: Required<MigrationOptions>) => {\n return middleware.console({\n fn: async (ctx, next) => {\n if (ctx.input.command !== commandName) return next();\n ctx.commandMatched = true;\n\n const { all } = await validate(ctx.input.parseArgv(), {\n all: rule.boolean().default(false),\n });\n\n const connection =\n opts.connection instanceof mongoose.Connection\n ? opts.connection\n : await createConnection(\n opts.connection.uri,\n opts.connection.options,\n ).asPromise();\n const db = connection.db!;\n\n await syncCollectionIndex(opts.modelsPath);\n\n const rows = await MigrationModel.find().sort({ filename: 'desc' }).lean();\n if (!rows.length) return;\n\n const migratedFiles = rows.map((item) => item.filename);\n await mkdir(opts.migrationsPath, { recursive: true });\n const allFiles = await pathToFiles(opts.migrationsPath);\n const executeCount = all ? migratedFiles.length : 1;\n\n for (let i = 0; i < executeCount; ++i) {\n const filename = migratedFiles[i]!;\n const fullPath = allFiles.find((item) =>\n item.endsWith(filename + path.extname(item)),\n );\n if (!fullPath) {\n throw new Error(i18n.t('migration.file_not_found', { file: filename }));\n }\n const instance = await import(fullPath);\n const migrate = instance.default;\n if (migrate instanceof Migrate) {\n try {\n await connection.transaction(async (session) => {\n await MigrationModel.deleteOne({ filename }, { session });\n await migrate.down(db, session);\n });\n terminal.printSuccess(`[down] ${filename}`);\n } catch (e) {\n terminal.printError(`[down] ${filename}`);\n throw e;\n }\n }\n }\n\n if (!(opts.connection instanceof mongoose.Connection)) {\n await connection.close();\n }\n },\n help: {\n onDocument(doc) {\n doc[commandName] = {\n summary: i18n.t('migration.down'),\n parameters: [{ type: 'boolean', name: 'all', defaultValue: false }],\n };\n },\n },\n });\n};\n","import {\n Document,\n mongo,\n type Default__v,\n type FlattenMaps,\n type Require_id,\n} from 'mongoose';\n\nexport type MongoResult<T, Remove extends boolean> = {\n [K in keyof T as K extends '__v'\n ? never\n : Remove extends true\n ? K extends (typeof excludedFields)[number]\n ? never\n : K\n : K extends '_id'\n ? 'id'\n : K]: T[K] extends mongo.Decimal128 | mongo.ObjectId ? string : T[K];\n};\n\nconst excludedFields = <const>[\n 'created_at',\n 'createdAt',\n 'updated_at',\n 'updatedAt',\n '_id',\n];\n\nexport function formatMongoResult<T extends Document, Remove extends boolean>(\n data: T[],\n removeColumns?: Remove,\n): MongoResult<\n T extends Document<any, any, infer R> ? FlattenMaps<Default__v<Require_id<R>>> : never,\n Remove\n>[];\nexport function formatMongoResult<T extends Record<string, any>, Remove extends boolean>(\n data: T[],\n removeColumns?: Remove,\n): MongoResult<T, Remove>[];\nexport function formatMongoResult<T extends Document | null, Remove extends boolean>(\n data: T,\n removeColumns?: Remove,\n): T extends Document\n ? MongoResult<\n T extends Document<any, any, infer R>\n ? FlattenMaps<Default__v<Require_id<R>>>\n : never,\n Remove\n >\n : null;\nexport function formatMongoResult<\n T extends Record<string, any> | null,\n Remove extends boolean,\n>(\n data: T,\n removeColumns?: Remove,\n): T extends Record<string, any> ? MongoResult<T, Remove> : null;\n/**\n * 格式化mongo查询结果,支持传入 纯JSON 和 Document 两种对象格式,返回结果遵循如下规则:\n * - 去掉 __v 字段\n * - decimal128类型 转为 字符串\n * - objectId类型 转为 字符串\n * - removeColumns=true时,去掉 _id 字段\n * - removeColumns=false时,_id 字段转为 id\n * - removeColumns=true时,去掉 createdAt/created_at 字段\n * - removeColumns=true时,去掉 updatedAt/updated_at 字段\n *\n * @param {Boolean} removeColumns 是否去掉数据库扩展的字段\n */\nexport function formatMongoResult(\n data: Record<string, any> | Record<string, any>[] | Document | Document[] | null,\n removeColumns: boolean = false,\n) {\n if (data == null) return null;\n\n const newDate = (Array.isArray(data) ? data : [data]).map((item) => {\n if (item instanceof Document) {\n item = item.toJSON({ flattenMaps: true });\n }\n\n const newItem: Record<string, any> = {};\n for (let [key, value] of Object.entries(item)) {\n if (key === '__v') continue;\n if (removeColumns && excludedFields.includes(key as any)) continue;\n if (key === '_id') key = 'id';\n\n if (value instanceof mongo.Decimal128) {\n newItem[key] = value.toString();\n } else if (value instanceof mongo.ObjectId) {\n newItem[key] = value.toHexString();\n } else {\n newItem[key] = value;\n }\n }\n return newItem;\n });\n return Array.isArray(data) ? newDate : newDate[0];\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,OACK;;;ACNP,SAAS,QAAAA,aAAY;;;ACArB,SAAS,YAAY;AAEd,IAAM,KAAK,KAAK,OAAO;AAAA,EAC5B,WAAW;AAAA,IACT,YAAY;AAAA,MACV,oBAAoB;AAAA,IACtB;AAAA,IACA,UAAU;AAAA,MACR,kBAAkB;AAAA,IACp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AAG,IAAI,CAAC,SAAS;AAClE,QAAI,gBAAgB,UAAU;AAC5B,aAAO,KAAK,OAAO,EAAE,aAAa,KAAK,CAAC;AAAA,IAC1C;AAEA,UAAM,UAA+B,CAAC;AACtC,aAAS,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC7C,UAAI,QAAQ,MAAO;AACnB,UAAI,iBAAiB,eAAe,SAAS,GAAU,EAAG;AAC1D,UAAI,QAAQ,MAAO,OAAM;AAEzB,UAAI,iBAAiBA,OAAM,YAAY;AACrC,gBAAQ,GAAG,IAAI,MAAM,SAAS;AAAA,MAChC,WAAW,iBAAiBA,OAAM,UAAU;AAC1C,gBAAQ,GAAG,IAAI,MAAM,YAAY;AAAA,MACnC,OAAO;AACL,gBAAQ,GAAG,IAAI;AAAA,MACjB;AAAA,IACF;AACA,WAAO;AAAA,EACT,CAAC;AACD,SAAO,MAAM,QAAQ,IAAI,IAAI,UAAU,QAAQ,CAAC;AAClD;","names":["I18n","I18n","I18n","I18n","Validator","ValidateResult","Rule","mongo","Validator","ValidateResult","Rule","Schema","schema","Schema","middleware","middleware","mkdir","rule","rule","pathToFiles","path","mongoose","mkdir","commandName","middleware","pathToFiles","path","migrate","middleware","rule","validate","mongoose","createConnection","terminal","pathToFiles","mkdir","path","commandName","middleware","validate","rule","migrate","middleware","mongo"]}
|