@aomex/mongoose 3.23.0 → 3.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/index.js +19 -8
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,18 @@
|
|
|
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.1](https://github.com/aomex/aomex/compare/v3.23.0...v3.23.1) (2025-04-18)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Bug Fixes
|
|
10
|
+
|
|
11
|
+
* **mongoose:** 无效的导出模块 Connection ([af06e45](https://github.com/aomex/aomex/commit/af06e450318d07ae0489779443fe610b18aea709))
|
|
12
|
+
* **mongoose:** 迁移目录可能目录不存在 ([bcdb986](https://github.com/aomex/aomex/commit/bcdb9869318062097b5a31d501cdfb8a51b53910))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
6
18
|
# [3.23.0](https://github.com/aomex/aomex/compare/v3.22.0...v3.23.0) (2025-04-16)
|
|
7
19
|
|
|
8
20
|
|
package/dist/index.js
CHANGED
|
@@ -25,7 +25,8 @@ var zh = I18n.define({
|
|
|
25
25
|
migration: {
|
|
26
26
|
create: "\u521B\u5EFA\u8FC1\u79FB\u6587\u4EF6",
|
|
27
27
|
up: "\u6267\u884C\u8FC1\u79FB\u903B\u8F91",
|
|
28
|
-
down: "\u56DE\u6EDA\u8FC1\u79FB\u903B\u8F91"
|
|
28
|
+
down: "\u56DE\u6EDA\u8FC1\u79FB\u903B\u8F91",
|
|
29
|
+
file_not_found: "\u8FC1\u79FB\u6587\u4EF6 '{{file}}' \u4E0D\u5B58\u5728"
|
|
29
30
|
}
|
|
30
31
|
});
|
|
31
32
|
|
|
@@ -46,7 +47,8 @@ var en = I18n2.satisfies(zh).define({
|
|
|
46
47
|
migration: {
|
|
47
48
|
create: "Generate migration file",
|
|
48
49
|
up: "Execute migration logic",
|
|
49
|
-
down: "Rollback migration logic"
|
|
50
|
+
down: "Rollback migration logic",
|
|
51
|
+
file_not_found: "Migration file '{{file}}' not found"
|
|
50
52
|
}
|
|
51
53
|
});
|
|
52
54
|
|
|
@@ -252,7 +254,9 @@ import { middleware as middleware2 } from "@aomex/common";
|
|
|
252
254
|
// src/libs/sync-collection-index.ts
|
|
253
255
|
import { getFileValues, pathToFiles } from "@aomex/internal-file-import";
|
|
254
256
|
import mongoose from "mongoose";
|
|
257
|
+
import { mkdir as mkdir2 } from "node:fs/promises";
|
|
255
258
|
var syncCollectionIndex = async (modelsPath) => {
|
|
259
|
+
await mkdir2(modelsPath, { recursive: true });
|
|
256
260
|
const files = await pathToFiles(modelsPath);
|
|
257
261
|
await getFileValues(files);
|
|
258
262
|
await mongoose.syncIndexes();
|
|
@@ -292,15 +296,16 @@ var Migrate = class {
|
|
|
292
296
|
};
|
|
293
297
|
|
|
294
298
|
// src/middleware/migration-up.md.ts
|
|
295
|
-
import {
|
|
299
|
+
import mongoose3, { createConnection } from "mongoose";
|
|
296
300
|
import { terminal } from "@aomex/console";
|
|
301
|
+
import { mkdir as mkdir3 } from "node:fs/promises";
|
|
297
302
|
var commandName2 = "mongoose:migration:up";
|
|
298
303
|
var migrationUp = (opts) => {
|
|
299
304
|
return middleware2.console({
|
|
300
305
|
fn: async (ctx, next) => {
|
|
301
306
|
if (ctx.input.command !== commandName2) return next();
|
|
302
307
|
ctx.commandMatched = true;
|
|
303
|
-
const connection = opts.connection instanceof Connection ? opts.connection : await createConnection(
|
|
308
|
+
const connection = opts.connection instanceof mongoose3.Connection ? opts.connection : await createConnection(
|
|
304
309
|
opts.connection.uri,
|
|
305
310
|
opts.connection.options
|
|
306
311
|
).asPromise();
|
|
@@ -308,6 +313,7 @@ var migrationUp = (opts) => {
|
|
|
308
313
|
await syncCollectionIndex(opts.modelsPath);
|
|
309
314
|
const migratedRows = await MigrationModel.find().sort({ filename: "asc" }).lean();
|
|
310
315
|
const migratedFiles = migratedRows.map((item) => item.filename);
|
|
316
|
+
await mkdir3(opts.migrationsPath, { recursive: true });
|
|
311
317
|
const allFiles = await pathToFiles2(opts.migrationsPath);
|
|
312
318
|
const waitingMigrateFiles = allFiles.filter((item) => !migratedFiles.includes(path2.basename(item))).sort();
|
|
313
319
|
for (const filePath of waitingMigrateFiles) {
|
|
@@ -332,7 +338,7 @@ var migrationUp = (opts) => {
|
|
|
332
338
|
}
|
|
333
339
|
}
|
|
334
340
|
}
|
|
335
|
-
if (!(opts.connection instanceof Connection)) {
|
|
341
|
+
if (!(opts.connection instanceof mongoose3.Connection)) {
|
|
336
342
|
await connection.close();
|
|
337
343
|
}
|
|
338
344
|
},
|
|
@@ -346,16 +352,17 @@ var migrationUp = (opts) => {
|
|
|
346
352
|
|
|
347
353
|
// src/middleware/migration-down.md.ts
|
|
348
354
|
import { middleware as middleware3 } from "@aomex/common";
|
|
349
|
-
import {
|
|
355
|
+
import mongoose4, { createConnection as createConnection2 } from "mongoose";
|
|
350
356
|
import { terminal as terminal2 } from "@aomex/console";
|
|
351
357
|
import { pathToFiles as pathToFiles3 } from "@aomex/internal-file-import";
|
|
358
|
+
import { mkdir as mkdir4 } from "node:fs/promises";
|
|
352
359
|
var commandName3 = "mongoose:migration:down";
|
|
353
360
|
var migrationDown = (opts) => {
|
|
354
361
|
return middleware3.console({
|
|
355
362
|
fn: async (ctx, next) => {
|
|
356
363
|
if (ctx.input.command !== commandName3) return next();
|
|
357
364
|
ctx.commandMatched = true;
|
|
358
|
-
const connection = opts.connection instanceof
|
|
365
|
+
const connection = opts.connection instanceof mongoose4.Connection ? opts.connection : await createConnection2(
|
|
359
366
|
opts.connection.uri,
|
|
360
367
|
opts.connection.options
|
|
361
368
|
).asPromise();
|
|
@@ -364,8 +371,12 @@ var migrationDown = (opts) => {
|
|
|
364
371
|
const lastMigratedRow = await MigrationModel.findOne().sort({ filename: "desc" }).lean();
|
|
365
372
|
const filename = lastMigratedRow?.filename;
|
|
366
373
|
if (!filename) return;
|
|
374
|
+
await mkdir4(opts.migrationsPath, { recursive: true });
|
|
367
375
|
const allFiles = await pathToFiles3(opts.migrationsPath);
|
|
368
376
|
const fullPath = allFiles.find((item) => item.endsWith(filename));
|
|
377
|
+
if (!fullPath) {
|
|
378
|
+
throw new Error(i18n.t("migration.file_not_found", { file: filename }));
|
|
379
|
+
}
|
|
369
380
|
const instance = await import(fullPath);
|
|
370
381
|
const migrate2 = instance.default;
|
|
371
382
|
if (migrate2 instanceof Migrate) {
|
|
@@ -380,7 +391,7 @@ var migrationDown = (opts) => {
|
|
|
380
391
|
throw e;
|
|
381
392
|
}
|
|
382
393
|
}
|
|
383
|
-
if (!(opts.connection instanceof
|
|
394
|
+
if (!(opts.connection instanceof mongoose4.Connection)) {
|
|
384
395
|
await connection.close();
|
|
385
396
|
}
|
|
386
397
|
},
|
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 },\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;AAA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zB,QAAM,WAAW,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,GAAG,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","rule","rule","pathToFiles","path","commandName","middleware","pathToFiles","path","migrate","middleware","Connection","createConnection","terminal","pathToFiles","commandName","middleware","migrate","middleware","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 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((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 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';\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) => item.endsWith(filename));\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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,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","mongoose","createConnection","terminal","pathToFiles","mkdir","commandName","middleware","migrate","middleware","mongo"]}
|