@aomex/mongoose 3.21.1 → 3.23.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 CHANGED
@@ -3,6 +3,29 @@
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.23.0](https://github.com/aomex/aomex/compare/v3.22.0...v3.23.0) (2025-04-16)
7
+
8
+
9
+ ### Features
10
+
11
+ * **mongoose:** 支持数据迁移 ([5e24813](https://github.com/aomex/aomex/commit/5e24813b5a7d0b87688e3cf4f666f7a9dcb2748e))
12
+ * **mongoose:** 模型名称和集合名称保持一致 ([6cbb02f](https://github.com/aomex/aomex/commit/6cbb02fcdb59a64207e5029585d517453043a465))
13
+
14
+
15
+
16
+
17
+
18
+ # [3.22.0](https://github.com/aomex/aomex/compare/v3.21.1...v3.22.0) (2025-04-07)
19
+
20
+
21
+ ### Bug Fixes
22
+
23
+ * **mongoose:** 泛型 ModelInput 推导的可选属性无法跳过 ([29f60b7](https://github.com/aomex/aomex/commit/29f60b7d3d4a100faa934681be183e2cecebd135))
24
+
25
+
26
+
27
+
28
+
6
29
  ## [3.21.1](https://github.com/aomex/aomex/compare/v3.21.0...v3.21.1) (2025-04-06)
7
30
 
8
31
 
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Validator, TransformedValidator, ValidateResult, OpenAPI, StringValidator, NumberValidator, BooleanValidator, ObjectValidator, ArrayValidator, DateValidator, AnyValidator } from '@aomex/common';
2
- import { mongo, Model, SchemaOptions, IndexDirection, IndexOptions, HydratedDocument, Document, FlattenMaps, Default__v, Require_id } from 'mongoose';
2
+ import mongoose, { mongo, Model, SchemaOptions, IndexDirection, IndexOptions, HydratedDocument, Connection, ConnectOptions, Document, FlattenMaps, Default__v, Require_id } from 'mongoose';
3
3
  import { NonReadonly } from '@aomex/internal-tools';
4
+ import { ConsoleMiddleware } from '@aomex/console';
4
5
 
5
6
  declare class MongoDecimal128Validator<T = mongo.Decimal128> extends Validator<T> {
6
7
  protected config: Validator.Options<T>;
@@ -34,9 +35,12 @@ declare module '@aomex/common' {
34
35
  }
35
36
  }
36
37
 
37
- type ModelInput<M extends Model<any, any, any, any, any, any>> = M extends Model<any, any, any, any, any, infer R extends Record<string, Validator>> ? {
38
- -readonly [K in keyof R]: R[K] extends Validator<infer U> ? U extends null ? null | undefined : U extends Validator.TDefault | Validator.TOptional ? undefined : U : never;
38
+ type ModelInput<M extends Model<any, any, any, any, any, any>> = M extends Model<any, any, any, any, any, infer T extends Record<string, Validator>> ? {
39
+ -readonly [K in keyof T as true extends IsInputRequired<T[K]> ? K : never]: T[K] extends Validator<infer U> ? U extends null | Validator.TDefault | Validator.TOptional ? never : U : never;
40
+ } & {
41
+ -readonly [K in keyof T as true extends IsInputRequired<T[K]> ? never : K]?: T[K] extends Validator<infer U> ? U extends null ? null | undefined : U extends Validator.TDefault | Validator.TOptional ? undefined : U : never;
39
42
  } : never;
43
+ type IsInputRequired<T> = true extends Validator.HasUndefined<T> ? false : true extends Validator.HasNull<T> ? false : true extends Validator.HasDefault<T> ? false : true;
40
44
  type ModelOutput<M extends Model<any, any, any, any, any, any>> = {
41
45
  _id: mongo.ObjectId;
42
46
  } & (M extends Model<infer R, any, any, any, any, any> ? R : never);
@@ -90,6 +94,25 @@ declare const defineMongooseModel: <const Schema extends {
90
94
  readonly versionKey?: Ver;
91
95
  } & Omit<SchemaOptions, "timestamps" | "versionKey">) => Model<Output, {}, {}, {}, HydratedDocument<Output>, Schema>;
92
96
 
97
+ interface MigrationOptions {
98
+ /**
99
+ * 模型存放位置,用于执行`mongoose.syncIndexes()`同步索引。默认值:`src/models`
100
+ */
101
+ modelsPath?: string;
102
+ /**
103
+ * 迁移文件存放位置。默认值:`src/migrations`
104
+ */
105
+ migrationsPath?: string;
106
+ /**
107
+ * 连接参数。如果已经连接并且拥有读写权限,则可以传入`mongoose.connection`
108
+ */
109
+ connection: Connection | {
110
+ uri: string;
111
+ options?: ConnectOptions;
112
+ };
113
+ }
114
+ declare const mongooseMigration: (opts: MigrationOptions) => ConsoleMiddleware;
115
+
93
116
  type MongoResult<T, Remove extends boolean> = {
94
117
  [K in keyof T as K extends '__v' ? never : Remove extends true ? K extends (typeof excludedFields)[number] ? never : K : K extends '_id' ? 'id' : K]: T[K] extends mongo.Decimal128 | mongo.ObjectId ? string : T[K];
95
118
  };
@@ -99,4 +122,22 @@ declare function formatMongoResult<T extends Record<string, any>, Remove extends
99
122
  declare function formatMongoResult<T extends Document | null, Remove extends boolean>(data: T, removeColumns?: Remove): T extends Document ? MongoResult<T extends Document<any, any, infer R> ? FlattenMaps<Default__v<Require_id<R>>> : never, Remove> : null;
100
123
  declare function formatMongoResult<T extends Record<string, any> | null, Remove extends boolean>(data: T, removeColumns?: Remove): T extends Record<string, any> ? MongoResult<T, Remove> : null;
101
124
 
102
- export { type ModelInput, type ModelOutput, MongoDecimal128Validator, MongoObjectIdValidator, type MongoResult, defineMongooseModel, formatMongoResult };
125
+ interface Operation {
126
+ (db: mongoose.mongo.Db, session: mongoose.mongo.ClientSession): Promise<any>;
127
+ }
128
+ /**
129
+ * 迁移数据,因为开启了事务,所以任何操作都需要带上session,这样能保证出错时顺利回滚数据。
130
+ *
131
+ * 注意:集合和索引会根据models自动同步,无须写迁移逻辑。
132
+ */
133
+ declare const migrate: (opts: {
134
+ up: Operation;
135
+ down: Operation;
136
+ }) => Migrate;
137
+ declare class Migrate {
138
+ readonly up: Operation;
139
+ readonly down: Operation;
140
+ constructor(up: Operation, down: Operation);
141
+ }
142
+
143
+ export { Migrate, type MigrationOptions, type ModelInput, type ModelOutput, MongoDecimal128Validator, MongoObjectIdValidator, type MongoResult, defineMongooseModel, formatMongoResult, migrate, mongooseMigration };
package/dist/index.js CHANGED
@@ -21,6 +21,11 @@ var zh = I18n.define({
21
21
  },
22
22
  mongoose: {
23
23
  unsupported_validator: "\u6682\u4E0D\u652F\u6301 {{validator}} \u9A8C\u8BC1\u5668"
24
+ },
25
+ migration: {
26
+ create: "\u521B\u5EFA\u8FC1\u79FB\u6587\u4EF6",
27
+ up: "\u6267\u884C\u8FC1\u79FB\u903B\u8F91",
28
+ down: "\u56DE\u6EDA\u8FC1\u79FB\u903B\u8F91"
24
29
  }
25
30
  });
26
31
 
@@ -37,6 +42,11 @@ var en = I18n2.satisfies(zh).define({
37
42
  },
38
43
  mongoose: {
39
44
  unsupported_validator: "{{validator} is not supported yet"
45
+ },
46
+ migration: {
47
+ create: "Generate migration file",
48
+ up: "Execute migration logic",
49
+ down: "Rollback migration logic"
40
50
  }
41
51
  });
42
52
 
@@ -170,12 +180,15 @@ var validatorToSchema = (validator) => {
170
180
 
171
181
  // src/define-mongoose-model.ts
172
182
  var defineMongooseModel = (collectionName, opts) => {
173
- const { schemas, indexes, timestamps, ...schemaOptions } = opts;
183
+ const { schemas, indexes, ...schemaOptions } = opts;
174
184
  const definition = {};
175
- Object.entries(opts.schemas).forEach(([key, schema2]) => {
185
+ Object.entries(schemas).forEach(([key, schema2]) => {
176
186
  definition[key] = validatorToSchema(schema2);
177
187
  });
178
- const schema = new Schema2(definition, { ...schemaOptions, timestamps });
188
+ const schema = new Schema2(definition, {
189
+ collection: collectionName,
190
+ ...schemaOptions
191
+ });
179
192
  indexes?.forEach(({ fields, ...indexRest }) => {
180
193
  schema.index(
181
194
  // @ts-expect-error
@@ -187,6 +200,223 @@ var defineMongooseModel = (collectionName, opts) => {
187
200
  return customModel;
188
201
  };
189
202
 
203
+ // src/middleware/mongoose-migration.md.ts
204
+ import { compose, middleware as middleware4 } from "@aomex/common";
205
+
206
+ // src/middleware/migration-create-file.md.ts
207
+ import { middleware, rule, validate } from "@aomex/common";
208
+ import snakeCase from "lodash.snakecase";
209
+ import path from "node:path";
210
+ import { mkdir, writeFile } from "node:fs/promises";
211
+ var commandName = "mongoose:migration:create";
212
+ var migrationCreateFile = (migrationsPath) => {
213
+ return middleware.console({
214
+ fn: async (ctx, next) => {
215
+ if (ctx.input.command !== commandName) return next();
216
+ ctx.commandMatched = true;
217
+ const { name } = await validate(ctx.input.parseArgv(), {
218
+ name: rule.string().optional().trim().transform(snakeCase)
219
+ });
220
+ const filename = `${(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[-TZ.:]/gi, "")}_${name}.ts`;
221
+ const fullPath = path.join(migrationsPath, filename);
222
+ await mkdir(path.dirname(fullPath), { recursive: true });
223
+ await writeFile(
224
+ fullPath,
225
+ `import { migrate } from '@aomex/mongoose';
226
+
227
+ export default migrate({
228
+ up: async (db, session) => {
229
+ // up transaction
230
+ },
231
+ down: async (db, session) => {
232
+ // down transaction
233
+ },
234
+ });
235
+ `
236
+ );
237
+ },
238
+ help: {
239
+ onDocument(doc) {
240
+ doc[commandName] = {
241
+ summary: i18n.t("migration.create"),
242
+ parameters: [{ type: "string", name: "name" }]
243
+ };
244
+ }
245
+ }
246
+ });
247
+ };
248
+
249
+ // src/middleware/migration-up.md.ts
250
+ import { middleware as middleware2 } from "@aomex/common";
251
+
252
+ // src/libs/sync-collection-index.ts
253
+ import { getFileValues, pathToFiles } from "@aomex/internal-file-import";
254
+ import mongoose from "mongoose";
255
+ var syncCollectionIndex = async (modelsPath) => {
256
+ const files = await pathToFiles(modelsPath);
257
+ await getFileValues(files);
258
+ await mongoose.syncIndexes();
259
+ };
260
+
261
+ // src/models/migration.model.ts
262
+ import { rule as rule2 } from "@aomex/common";
263
+ var MigrationModel = defineMongooseModel("__aomex_migration__", {
264
+ schemas: {
265
+ filename: rule2.string(),
266
+ finished_at: rule2.date().nullable()
267
+ },
268
+ versionKey: false,
269
+ timestamps: { createdAt: "created_at", updatedAt: false },
270
+ indexes: [
271
+ {
272
+ fields: { filename: "asc" },
273
+ unique: true
274
+ }
275
+ ]
276
+ });
277
+
278
+ // src/middleware/migration-up.md.ts
279
+ import { pathToFiles as pathToFiles2 } from "@aomex/internal-file-import";
280
+ import path2 from "node:path";
281
+
282
+ // src/libs/migrate.ts
283
+ import "mongoose";
284
+ var migrate = (opts) => {
285
+ return new Migrate(opts.up, opts.down);
286
+ };
287
+ var Migrate = class {
288
+ constructor(up, down) {
289
+ this.up = up;
290
+ this.down = down;
291
+ }
292
+ };
293
+
294
+ // src/middleware/migration-up.md.ts
295
+ import { Connection, createConnection } from "mongoose";
296
+ import { terminal } from "@aomex/console";
297
+ var commandName2 = "mongoose:migration:up";
298
+ var migrationUp = (opts) => {
299
+ return middleware2.console({
300
+ fn: async (ctx, next) => {
301
+ if (ctx.input.command !== commandName2) return next();
302
+ ctx.commandMatched = true;
303
+ const connection = opts.connection instanceof Connection ? opts.connection : await createConnection(
304
+ opts.connection.uri,
305
+ opts.connection.options
306
+ ).asPromise();
307
+ const db = connection.db;
308
+ await syncCollectionIndex(opts.modelsPath);
309
+ const migratedRows = await MigrationModel.find().sort({ filename: "asc" }).lean();
310
+ const migratedFiles = migratedRows.map((item) => item.filename);
311
+ const allFiles = await pathToFiles2(opts.migrationsPath);
312
+ const waitingMigrateFiles = allFiles.filter((item) => !migratedFiles.includes(path2.basename(item))).sort();
313
+ for (const filePath of waitingMigrateFiles) {
314
+ const instance = await import(filePath);
315
+ const migrate2 = instance.default;
316
+ if (migrate2 instanceof Migrate) {
317
+ const filename = path2.basename(filePath);
318
+ try {
319
+ await connection.transaction(async (session) => {
320
+ await MigrationModel.create([{ filename }], { session });
321
+ await migrate2.up(db, session);
322
+ await MigrationModel.updateOne(
323
+ { filename },
324
+ { finished_at: /* @__PURE__ */ new Date() },
325
+ { session }
326
+ );
327
+ });
328
+ terminal.printSuccess(`[up] ${filename}`);
329
+ } catch (e) {
330
+ terminal.printError(`[up] ${filename}`);
331
+ throw e;
332
+ }
333
+ }
334
+ }
335
+ if (!(opts.connection instanceof Connection)) {
336
+ await connection.close();
337
+ }
338
+ },
339
+ help: {
340
+ onDocument(doc) {
341
+ doc[commandName2] = { summary: i18n.t("migration.up") };
342
+ }
343
+ }
344
+ });
345
+ };
346
+
347
+ // src/middleware/migration-down.md.ts
348
+ import { middleware as middleware3 } from "@aomex/common";
349
+ import { Connection as Connection2, createConnection as createConnection2 } from "mongoose";
350
+ import { terminal as terminal2 } from "@aomex/console";
351
+ import { pathToFiles as pathToFiles3 } from "@aomex/internal-file-import";
352
+ var commandName3 = "mongoose:migration:down";
353
+ var migrationDown = (opts) => {
354
+ return middleware3.console({
355
+ fn: async (ctx, next) => {
356
+ if (ctx.input.command !== commandName3) return next();
357
+ ctx.commandMatched = true;
358
+ const connection = opts.connection instanceof Connection2 ? opts.connection : await createConnection2(
359
+ opts.connection.uri,
360
+ opts.connection.options
361
+ ).asPromise();
362
+ const db = connection.db;
363
+ await syncCollectionIndex(opts.modelsPath);
364
+ const lastMigratedRow = await MigrationModel.findOne().sort({ filename: "desc" }).lean();
365
+ const filename = lastMigratedRow?.filename;
366
+ if (!filename) return;
367
+ const allFiles = await pathToFiles3(opts.migrationsPath);
368
+ const fullPath = allFiles.find((item) => item.endsWith(filename));
369
+ const instance = await import(fullPath);
370
+ const migrate2 = instance.default;
371
+ if (migrate2 instanceof Migrate) {
372
+ try {
373
+ await connection.transaction(async (session) => {
374
+ await MigrationModel.deleteOne({ _id: lastMigratedRow._id }, { session });
375
+ await migrate2.down(db, session);
376
+ });
377
+ terminal2.printSuccess(`[down] ${filename}`);
378
+ } catch (e) {
379
+ terminal2.printError(`[down] ${filename}`);
380
+ throw e;
381
+ }
382
+ }
383
+ if (!(opts.connection instanceof Connection2)) {
384
+ await connection.close();
385
+ }
386
+ },
387
+ help: {
388
+ onDocument(doc) {
389
+ doc[commandName3] = { summary: i18n.t("migration.down") };
390
+ }
391
+ }
392
+ });
393
+ };
394
+
395
+ // src/middleware/mongoose-migration.md.ts
396
+ var mongooseMigration = (opts) => {
397
+ const {
398
+ migrationsPath = "src/migrations",
399
+ modelsPath = "src/models",
400
+ connection
401
+ } = opts;
402
+ const middlewareList = [
403
+ migrationCreateFile(migrationsPath),
404
+ migrationUp({ migrationsPath, connection, modelsPath }),
405
+ migrationDown({ migrationsPath, connection, modelsPath })
406
+ ];
407
+ return middleware4.console({
408
+ fn: compose(middlewareList),
409
+ help: {
410
+ async onDocument(_, { children }) {
411
+ await children(middlewareList);
412
+ },
413
+ async postDocument(_, { children }) {
414
+ await children(middlewareList);
415
+ }
416
+ }
417
+ });
418
+ };
419
+
190
420
  // src/libs/format-mongo-result.ts
191
421
  import {
192
422
  Document,
@@ -223,9 +453,12 @@ function formatMongoResult(data, removeColumns = false) {
223
453
  return Array.isArray(data) ? newDate : newDate[0];
224
454
  }
225
455
  export {
456
+ Migrate,
226
457
  MongoDecimal128Validator,
227
458
  MongoObjectIdValidator,
228
459
  defineMongooseModel,
229
- formatMongoResult
460
+ formatMongoResult,
461
+ migrate,
462
+ mongooseMigration
230
463
  };
231
464
  //# sourceMappingURL=index.js.map
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/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});\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});\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, timestamps, ...schemaOptions } = opts;\n\n const definition: SchemaDefinition = {};\n Object.entries(opts.schemas).forEach(([key, schema]) => {\n definition[key] = validatorToSchema(schema);\n });\n const schema = new Schema(definition, { ...schemaOptions, timestamps });\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 {\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;AACF,CAAC;;;ACdD,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,E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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","mongo"]}
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 },\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 },\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 { Connection, createConnection } from 'mongoose';\nimport { terminal } from '@aomex/console';\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 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 const allFiles = await pathToFiles(opts.migrationsPath);\n const waitingMigrateFiles = allFiles\n .filter((item) => !migratedFiles.includes(path.basename(item)))\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);\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 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';\n\nexport const syncCollectionIndex = async (modelsPath: string) => {\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 { Connection, createConnection } from 'mongoose';\nimport { terminal } from '@aomex/console';\nimport { pathToFiles } from '@aomex/internal-file-import';\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 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 const allFiles = await pathToFiles(opts.migrationsPath);\n const fullPath = allFiles.find((item) => item.endsWith(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({ _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 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,EACR;AACF,CAAC;;;ACnBD,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,EACR;AACF,CAAC;;;ACjBM,IAAM,UAAU;AAAA,EACrB,OAAO;AAAA,EACP,OAAO;AACT;;;AHHO,IAAM,OAAO,IAAIC,MAAK;AAAA,EAC3B,WAAW;AAAA,EACX,iBAAiB;AACnB,CAAC;;;ADED,SAAS,aAAa;AAEf,IAAM,2BAAN,cAA6D,UAAa;AAAA,EAerE,cACR,OACA,MACA,OACsC;AACtC,QAAI,iBAAiB,MAAM,YAAY;AACrC,aAAO,e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;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","rule","rule","pathToFiles","path","commandName","middleware","pathToFiles","path","migrate","middleware","Connection","createConnection","terminal","pathToFiles","commandName","middleware","migrate","middleware","mongo"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aomex/mongoose",
3
- "version": "3.21.1",
3
+ "version": "3.23.0",
4
4
  "description": "aomex与mongoose深度集成",
5
5
  "type": "module",
6
6
  "types": "dist/index.d.ts",
@@ -24,16 +24,20 @@
24
24
  "repository": "git@github.com:aomex/aomex.git",
25
25
  "homepage": "https://aomex.js.org",
26
26
  "license": "MIT",
27
- "engines": {
28
- "node": "^20.13.0 || ^22"
29
- },
30
27
  "peerDependencies": {
31
28
  "@aomex/common": "^3",
29
+ "@aomex/console": "^3",
32
30
  "mongoose": ">=8"
33
31
  },
32
+ "dependencies": {
33
+ "@aomex/internal-file-import": "",
34
+ "lodash.snakecase": "^4.1.1"
35
+ },
34
36
  "devDependencies": {
35
37
  "@aomex/common": "",
38
+ "@aomex/console": "",
36
39
  "@aomex/internal-tools": "",
40
+ "@types/lodash.snakecase": "^4.1.9",
37
41
  "mongodb-memory-server": "^10.1.4",
38
42
  "mongoose": "^8.13.2"
39
43
  },