@kikiutils/mongoose 7.1.0 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/dist/_internals.d.ts +4 -0
- package/dist/_internals.d.ts.map +1 -1
- package/dist/_internals.js +2 -1
- package/dist/_internals.js.map +1 -1
- package/dist/builders.d.ts +1 -3
- package/dist/builders.d.ts.map +1 -1
- package/dist/builders.js +8 -9
- package/dist/builders.js.map +1 -1
- package/dist/connection.d.ts +5 -0
- package/dist/connection.d.ts.map +1 -0
- package/dist/connection.js +10 -0
- package/dist/connection.js.map +1 -0
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +2 -1
- package/dist/options.js.map +1 -1
- package/dist/plugins/lean-decimal128-to-string.d.ts +26 -0
- package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -0
- package/dist/plugins/lean-decimal128-to-string.js +85 -0
- package/dist/plugins/lean-decimal128-to-string.js.map +1 -0
- package/dist/plugins/normalize.d.ts +24 -14
- package/dist/plugins/normalize.d.ts.map +1 -1
- package/dist/plugins/normalize.js +20 -10
- package/dist/plugins/normalize.js.map +1 -1
- package/dist/schema-builders/base.d.ts +1 -1
- package/dist/schema-builders/base.d.ts.map +1 -1
- package/dist/schema-builders/base.js.map +1 -1
- package/dist/schema-builders/bigint.d.ts +60 -0
- package/dist/schema-builders/bigint.d.ts.map +1 -0
- package/dist/schema-builders/bigint.js +58 -0
- package/dist/schema-builders/bigint.js.map +1 -0
- package/dist/schema-builders/boolean.d.ts.map +1 -1
- package/dist/schema-builders/boolean.js.map +1 -1
- package/dist/schema-builders/date.d.ts +2 -2
- package/dist/schema-builders/date.d.ts.map +1 -1
- package/dist/schema-builders/date.js.map +1 -1
- package/dist/schema-builders/decimal128.d.ts +20 -14
- package/dist/schema-builders/decimal128.d.ts.map +1 -1
- package/dist/schema-builders/decimal128.js +1 -0
- package/dist/schema-builders/decimal128.js.map +1 -1
- package/dist/schema-builders/double.d.ts +60 -0
- package/dist/schema-builders/double.d.ts.map +1 -0
- package/dist/schema-builders/double.js +62 -0
- package/dist/schema-builders/double.js.map +1 -0
- package/dist/schema-builders/index.d.ts +6 -1
- package/dist/schema-builders/index.js +6 -1
- package/dist/schema-builders/int32.d.ts +60 -0
- package/dist/schema-builders/int32.d.ts.map +1 -0
- package/dist/schema-builders/int32.js +58 -0
- package/dist/schema-builders/int32.js.map +1 -0
- package/dist/schema-builders/mixed.d.ts +34 -0
- package/dist/schema-builders/mixed.d.ts.map +1 -0
- package/dist/schema-builders/mixed.js +8 -0
- package/dist/schema-builders/mixed.js.map +1 -0
- package/dist/schema-builders/number.d.ts +2 -2
- package/dist/schema-builders/number.d.ts.map +1 -1
- package/dist/schema-builders/number.js.map +1 -1
- package/dist/schema-builders/object-id.d.ts +2 -2
- package/dist/schema-builders/object-id.d.ts.map +1 -1
- package/dist/schema-builders/object-id.js.map +1 -1
- package/dist/schema-builders/ref.d.ts +2 -2
- package/dist/schema-builders/ref.d.ts.map +1 -1
- package/dist/schema-builders/ref.js.map +1 -1
- package/dist/schema-builders/string.d.ts +35 -25
- package/dist/schema-builders/string.d.ts.map +1 -1
- package/dist/schema-builders/string.js.map +1 -1
- package/dist/schema-builders/uuid.d.ts +34 -0
- package/dist/schema-builders/uuid.d.ts.map +1 -0
- package/dist/schema-builders/uuid.js +8 -0
- package/dist/schema-builders/uuid.js.map +1 -0
- package/dist/types/aggregate-paginate.d.ts +24 -8
- package/dist/types/aggregate-paginate.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -4
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/options.d.ts +9 -4
- package/dist/types/options.d.ts.map +1 -1
- package/dist/types/paginate.d.ts +6 -2
- package/dist/types/paginate.d.ts.map +1 -1
- package/package.json +17 -12
- package/src/_internals.ts +3 -0
- package/src/builders.ts +18 -32
- package/src/connection.ts +14 -0
- package/src/options.ts +8 -1
- package/src/plugins/lean-decimal128-to-string.ts +149 -0
- package/src/plugins/normalize.ts +39 -15
- package/src/schema-builders/base.ts +6 -1
- package/src/schema-builders/bigint.ts +190 -0
- package/src/schema-builders/boolean.ts +1 -4
- package/src/schema-builders/date.ts +2 -2
- package/src/schema-builders/decimal128.ts +21 -14
- package/src/schema-builders/double.ts +198 -0
- package/src/schema-builders/index.ts +15 -0
- package/src/schema-builders/int32.ts +191 -0
- package/src/schema-builders/mixed.ts +37 -0
- package/src/schema-builders/number.ts +2 -2
- package/src/schema-builders/object-id.ts +2 -2
- package/src/schema-builders/ref.ts +2 -2
- package/src/schema-builders/string.ts +35 -25
- package/src/schema-builders/uuid.ts +48 -0
- package/src/types/aggregate-paginate.ts +29 -8
- package/src/types/index.ts +0 -5
- package/src/types/options.ts +12 -3
- package/src/types/paginate.ts +6 -2
- package/dist/constants.d.ts +0 -5
- package/dist/constants.d.ts.map +0 -1
- package/dist/constants.js +0 -6
- package/dist/constants.js.map +0 -1
- package/dist/helpers.d.ts +0 -5
- package/dist/helpers.d.ts.map +0 -1
- package/dist/helpers.js +0 -9
- package/dist/helpers.js.map +0 -1
- package/src/constants.ts +0 -3
- package/src/helpers.ts +0 -5
package/README.md
CHANGED
|
@@ -7,19 +7,19 @@
|
|
|
7
7
|
[![codecov][codecov-src]][codecov-href]
|
|
8
8
|
[![License][license-src]][license-href]
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
Provides Mongoose schema builders and utilities for connections, pagination, JSON normalization, and update checks.
|
|
11
11
|
|
|
12
12
|
- [✨ Release Notes](./CHANGELOG.md)
|
|
13
13
|
|
|
14
14
|
## Features
|
|
15
15
|
|
|
16
|
-
- ✨
|
|
17
|
-
- 🔌
|
|
18
|
-
- 🛠
|
|
19
|
-
- 🧮
|
|
20
|
-
- 🔄
|
|
21
|
-
-
|
|
22
|
-
- 🔧
|
|
16
|
+
- ✨ Supports custom connections and reuses an automatically created default connection with configurable creation options.
|
|
17
|
+
- 🔌 Registers `mongoose-aggregate-paginate-v2`, `mongoose-paginate-v2`, and update-result assertion plugins, with optional recursive JSON normalization.
|
|
18
|
+
- 🛠 Provides chainable schema builders for `bigint`, `boolean`, `date`, `decimal128`, `double`, `int32`, `mixed`, `number`, `objectId`, `ref`, `string`, and `uuid`, with field options tailored to each schema type.
|
|
19
|
+
- 🧮 Provides `Decimal128` rounding, fixed-decimal formatting, string getters, and inclusive range validation.
|
|
20
|
+
- 🔄 Normalizes JSON output by default: adds `id`, removes `_id`, `__v`, and private fields, and serializes `Decimal128` values as strings.
|
|
21
|
+
- 🔗 Defines ObjectId reference fields using model names, model constructors, or callbacks.
|
|
22
|
+
- 🔧 Checks update acknowledgment and a minimum modified-document count through function, model, and document APIs.
|
|
23
23
|
|
|
24
24
|
## Requirements
|
|
25
25
|
|
package/dist/_internals.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { CustomMongooseOptions } from "./types/options.js";
|
|
2
|
+
import { Connection } from "mongoose";
|
|
2
3
|
//#region src/_internals.d.ts
|
|
3
4
|
export declare const customMongooseOptions: CustomMongooseOptions;
|
|
5
|
+
export declare const mongooseConnectionState: {
|
|
6
|
+
defaultConnection?: Connection;
|
|
7
|
+
};
|
|
4
8
|
//#endregion
|
|
5
9
|
//# sourceMappingURL=_internals.d.ts.map
|
package/dist/_internals.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_internals.d.ts","names":[],"sources":["../src/_internals.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"_internals.d.ts","names":[],"sources":["../src/_internals.ts"],"mappings":";;;qBAIa,uBAAuB;qBACvB;EAA2B,oBAAoB"}
|
package/dist/_internals.js
CHANGED
package/dist/_internals.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_internals.js","names":[],"sources":["../src/_internals.ts"],"sourcesContent":["import type { CustomMongooseOptions } from './types/options';\n\nexport const customMongooseOptions: CustomMongooseOptions = {};\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"_internals.js","names":[],"sources":["../src/_internals.ts"],"sourcesContent":["import type { Connection } from 'mongoose';\n\nimport type { CustomMongooseOptions } from './types/options';\n\nexport const customMongooseOptions: CustomMongooseOptions = {};\nexport const mongooseConnectionState: { defaultConnection?: Connection } = {};\n"],"mappings":";AAIA,MAAa,wBAA+C,CAAC;AAC7D,MAAa,0BAA8D,CAAC"}
|
package/dist/builders.d.ts
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
import { MongooseNormalizePluginOptions } from "./plugins/normalize.js";
|
|
2
1
|
import { BaseMongoosePaginateModel } from "./types/index.js";
|
|
3
2
|
import { BuildMongooseModelOptions } from "./types/options.js";
|
|
4
3
|
import { mongooseAssertionsPlugin } from "./plugins/assertions.js";
|
|
5
|
-
import {
|
|
4
|
+
import { Schema } from "mongoose";
|
|
6
5
|
//#region src/builders.d.ts
|
|
7
6
|
export type DoNotRemoveOrUseThisType = typeof mongooseAssertionsPlugin;
|
|
8
7
|
export declare function buildMongooseModel<DocType, Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>, InstanceMethodsAndOverrides = object, QueryHelpers = object>(collection: string, name: string, schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>, options?: BuildMongooseModelOptions): Model;
|
|
9
|
-
export declare function registerMongooseNormalizePlugin<DocType, Model$1 extends Model<DocType, QueryHelpers, InstanceMethodsAndOverrides>, InstanceMethodsAndOverrides = object, QueryHelpers = object>(schema: Schema<DocType, Model$1, InstanceMethodsAndOverrides, QueryHelpers>, recursive?: boolean, options?: MongooseNormalizePluginOptions): void;
|
|
10
8
|
//#endregion
|
|
11
9
|
//# sourceMappingURL=builders.d.ts.map
|
package/dist/builders.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builders.d.ts","names":[
|
|
1
|
+
{"version":3,"file":"builders.d.ts","names":[],"sources":["../src/builders.ts"],"mappings":";;;;;YAYY,kCAAkC;wBAE9B,mBACZ,SACA,cAAc,0BAA0B,SAAS,6BAA6B,eAC9E,sCACA,uBAEA,oBACA,cACA,QAAQ,OAAO,SAAS,OAAO,6BAA6B,eAC5D,UAAU,4BACX"}
|
package/dist/builders.js
CHANGED
|
@@ -1,25 +1,24 @@
|
|
|
1
1
|
import { customMongooseOptions } from "./_internals.js";
|
|
2
|
-
import {
|
|
2
|
+
import { getDefaultMongooseConnection } from "./connection.js";
|
|
3
3
|
import { mongooseAssertionsPlugin } from "./plugins/assertions.js";
|
|
4
|
+
import { mongooseLeanDecimal128ToStringPlugin } from "./plugins/lean-decimal128-to-string.js";
|
|
4
5
|
import { mongooseNormalizePlugin } from "./plugins/normalize.js";
|
|
5
|
-
import mongoose from "mongoose";
|
|
6
6
|
import mongooseAggregatePaginate from "mongoose-aggregate-paginate-v2";
|
|
7
7
|
import mongoosePaginate from "mongoose-paginate-v2";
|
|
8
8
|
//#region src/builders.ts
|
|
9
9
|
function buildMongooseModel(collection, name, schema, options) {
|
|
10
|
-
|
|
10
|
+
const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;
|
|
11
|
+
if (leanDecimal128ToStringPluginOptions !== false) schema.plugin(mongooseLeanDecimal128ToStringPlugin, typeof leanDecimal128ToStringPluginOptions === "object" ? leanDecimal128ToStringPluginOptions : void 0);
|
|
12
|
+
const normalizePluginOptions = options?.plugins?.normalize;
|
|
13
|
+
if (normalizePluginOptions !== false) schema.plugin(mongooseNormalizePlugin, typeof normalizePluginOptions === "object" ? normalizePluginOptions : void 0);
|
|
11
14
|
schema.plugin(mongooseAggregatePaginate);
|
|
12
15
|
schema.plugin(mongooseAssertionsPlugin);
|
|
13
16
|
schema.plugin(mongoosePaginate);
|
|
14
17
|
schema.set("timestamps", options?.timestamps ?? schema.get("timestamps") ?? true);
|
|
15
18
|
customMongooseOptions.beforeModelBuild?.(schema);
|
|
16
|
-
return (options?.connection
|
|
17
|
-
}
|
|
18
|
-
function registerMongooseNormalizePlugin(schema, recursive = true, options) {
|
|
19
|
-
schema.plugin(mongooseNormalizePlugin, options);
|
|
20
|
-
if (recursive) schema.childSchemas.forEach(({ schema }) => registerMongooseNormalizePlugin(schema, recursive, options));
|
|
19
|
+
return (options?.connection ?? getDefaultMongooseConnection()).model(name, schema, collection);
|
|
21
20
|
}
|
|
22
21
|
//#endregion
|
|
23
|
-
export { buildMongooseModel
|
|
22
|
+
export { buildMongooseModel };
|
|
24
23
|
|
|
25
24
|
//# sourceMappingURL=builders.js.map
|
package/dist/builders.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builders.js","names":[],"sources":["../src/builders.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"builders.js","names":[],"sources":["../src/builders.ts"],"sourcesContent":["import type { Schema } from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { getDefaultMongooseConnection } from './connection';\nimport { mongooseAssertionsPlugin } from './plugins/assertions';\nimport { mongooseLeanDecimal128ToStringPlugin } from './plugins/lean-decimal128-to-string';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BaseMongoosePaginateModel } from './types';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof mongooseAssertionsPlugin;\n\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n): Model {\n const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;\n if (leanDecimal128ToStringPluginOptions !== false) {\n schema.plugin(\n mongooseLeanDecimal128ToStringPlugin,\n typeof leanDecimal128ToStringPluginOptions === 'object' ? leanDecimal128ToStringPluginOptions : undefined,\n );\n }\n\n const normalizePluginOptions = options?.plugins?.normalize;\n if (normalizePluginOptions !== false) {\n schema.plugin(\n mongooseNormalizePlugin,\n typeof normalizePluginOptions === 'object' ? normalizePluginOptions : undefined,\n );\n }\n\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongooseAssertionsPlugin);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n const connection = options?.connection ?? getDefaultMongooseConnection();\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,mBAMZ,YACA,MACA,QACA,SACK;CACL,MAAM,sCAAsC,SAAS,SAAS;CAC9D,IAAI,wCAAwC,OACxC,OAAO,OACH,sCACA,OAAO,wCAAwC,WAAW,sCAAsC,KAAA,CACpG;CAGJ,MAAM,yBAAyB,SAAS,SAAS;CACjD,IAAI,2BAA2B,OAC3B,OAAO,OACH,yBACA,OAAO,2BAA2B,WAAW,yBAAyB,KAAA,CAC1E;CAGJ,OAAO,OAAO,yBAAyB;CACvC,OAAO,OAAO,wBAAwB;CACtC,OAAO,OAAO,gBAAgB;CAC9B,OAAO,IAAI,cAAc,SAAS,cAAc,OAAO,IAAI,YAAY,KAAK,IAAI;CAChF,sBAAsB,mBAAmB,MAAM;CAE/C,QADmB,SAAS,cAAc,6BAA6B,EAAA,CACrD,MAAoC,MAAM,QAAQ,UAAU;AAClF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.d.ts","names":[],"sources":["../src/connection.ts"],"mappings":";;wBAQgB,gCAAgC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { customMongooseOptions, mongooseConnectionState } from "./_internals.js";
|
|
2
|
+
import mongoose from "mongoose";
|
|
3
|
+
//#region src/connection.ts
|
|
4
|
+
function getDefaultMongooseConnection() {
|
|
5
|
+
return mongooseConnectionState.defaultConnection ||= mongoose.createConnection(process.env.MONGODB_URI || "mongodb://127.0.0.1:27017", customMongooseOptions.defaultConnectionOptions);
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
export { getDefaultMongooseConnection };
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=connection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.js","names":[],"sources":["../src/connection.ts"],"sourcesContent":["import mongoose from 'mongoose';\nimport type { Connection } from 'mongoose';\n\nimport {\n customMongooseOptions,\n mongooseConnectionState,\n} from './_internals';\n\nexport function getDefaultMongooseConnection(): Connection {\n return mongooseConnectionState.defaultConnection ||= mongoose.createConnection(\n process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017',\n customMongooseOptions.defaultConnectionOptions,\n );\n}\n"],"mappings":";;;AAQA,SAAgB,+BAA2C;CACvD,OAAO,wBAAwB,sBAAsB,SAAS,iBAC1D,QAAQ,IAAI,eAAe,6BAC3B,sBAAsB,wBAC1B;AACJ"}
|
package/dist/options.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.d.ts","names":[],"sources":["../src/options.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"options.d.ts","names":[],"sources":["../src/options.ts"],"mappings":";;wBAMgB,yBAAyB,gBAAgB,uBACrD,KAAK,GACL,OAAO,sBAAsB"}
|
package/dist/options.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { customMongooseOptions } from "./_internals.js";
|
|
1
|
+
import { customMongooseOptions, mongooseConnectionState } from "./_internals.js";
|
|
2
2
|
//#region src/options.ts
|
|
3
3
|
function setCustomMongooseOptions(key, value) {
|
|
4
|
+
if (key === "defaultConnectionOptions" && mongooseConnectionState.defaultConnection) throw new Error("Default connection options must be set before the default connection is created.");
|
|
4
5
|
customMongooseOptions[key] = value;
|
|
5
6
|
}
|
|
6
7
|
//#endregion
|
package/dist/options.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../src/options.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../src/options.ts"],"sourcesContent":["import {\n customMongooseOptions,\n mongooseConnectionState,\n} from './_internals';\nimport type { CustomMongooseOptions } from './types/options';\n\nexport function setCustomMongooseOptions<K extends keyof CustomMongooseOptions>(\n key: K,\n value: CustomMongooseOptions[K],\n) {\n if (key === 'defaultConnectionOptions' && mongooseConnectionState.defaultConnection) {\n throw new Error('Default connection options must be set before the default connection is created.');\n }\n\n customMongooseOptions[key] = value;\n}\n"],"mappings":";;AAMA,SAAgB,yBACZ,KACA,OACF;CACE,IAAI,QAAQ,8BAA8B,wBAAwB,mBAC9D,MAAM,IAAI,MAAM,kFAAkF;CAGtG,sBAAsB,OAAO;AACjC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Schema } from "mongoose";
|
|
2
|
+
//#region src/plugins/lean-decimal128-to-string.d.ts
|
|
3
|
+
declare module 'mongoose' {
|
|
4
|
+
interface LeanOptions {
|
|
5
|
+
/** Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting. */
|
|
6
|
+
decimal128ToString?: boolean;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export interface MongooseLeanDecimal128ToStringPluginOptions {
|
|
10
|
+
/** Whether marked fields are converted on lean queries by default. Defaults to true. */
|
|
11
|
+
enabledByDefault?: boolean;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Converts marked Decimal128 fields to strings on lean queries without invoking getters.
|
|
15
|
+
*
|
|
16
|
+
* @remarks
|
|
17
|
+
* `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
|
|
18
|
+
* Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
|
|
19
|
+
* Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
|
|
20
|
+
* Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
|
|
21
|
+
* Registration is idempotent; the first registration's default options take precedence.
|
|
22
|
+
* Runtime conversion does not override Mongoose's inferred lean result types.
|
|
23
|
+
*/
|
|
24
|
+
export declare function mongooseLeanDecimal128ToStringPlugin(schema: Schema, pluginOptions?: MongooseLeanDecimal128ToStringPluginOptions): void;
|
|
25
|
+
//#endregion
|
|
26
|
+
//# sourceMappingURL=lean-decimal128-to-string.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lean-decimal128-to-string.d.ts","names":[],"sources":["../../src/plugins/lean-decimal128-to-string.ts"],"mappings":";;;YAOc;;IAEN;;;iBAMS;;EAEb;;;;;;;;;;;;;wBAuFY,qCACZ,QAAQ,QACR,gBAAgB"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
//#region src/plugins/lean-decimal128-to-string.ts
|
|
2
|
+
const registeredSchemas = /* @__PURE__ */ new WeakSet();
|
|
3
|
+
const isNonNullObject = (value) => value !== null && typeof value === "object";
|
|
4
|
+
function convertDocument(schema, value) {
|
|
5
|
+
if (!isNonNullObject(value)) return;
|
|
6
|
+
const discriminatorKey = schema.get("discriminatorKey") ?? "__t";
|
|
7
|
+
(Object.values(schema.discriminators ?? {}).find((childSchema) => childSchema.get("discriminatorKey") === discriminatorKey && childSchema.discriminatorMapping?.value === value[discriminatorKey]) ?? schema).eachPath((path, schemaType) => {
|
|
8
|
+
const pathSegments = path.split(".");
|
|
9
|
+
if (pathSegments.includes("$*")) return;
|
|
10
|
+
convertPath(value, pathSegments, schemaType);
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
function convertPath(value, pathSegments, schemaType) {
|
|
14
|
+
if (Array.isArray(value)) {
|
|
15
|
+
value.forEach((item) => convertPath(item, pathSegments, schemaType));
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (!isNonNullObject(value)) return;
|
|
19
|
+
const [key, ...remainingPathSegments] = pathSegments;
|
|
20
|
+
if (key === void 0 || !Object.hasOwn(value, key)) return;
|
|
21
|
+
if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);
|
|
22
|
+
else value[key] = convertValue(value[key], schemaType);
|
|
23
|
+
}
|
|
24
|
+
function convertValue(value, schemaType) {
|
|
25
|
+
if (value === null || value === void 0) return value;
|
|
26
|
+
const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
|
|
27
|
+
if (embeddedSchemaType && Array.isArray(value)) {
|
|
28
|
+
for (let i = 0; i < value.length; i++) if (Object.hasOwn(value, i)) value[i] = convertValue(value[i], embeddedSchemaType);
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
if (embeddedSchemaType && schemaType.instance === "Map") {
|
|
32
|
+
if (value instanceof Map) value.forEach((item, key) => value.set(key, convertValue(item, embeddedSchemaType)));
|
|
33
|
+
else if (isNonNullObject(value)) for (const key of Object.keys(value)) value[key] = convertValue(value[key], embeddedSchemaType);
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
if (schemaType.schema) {
|
|
37
|
+
convertDocument(schemaType.schema, value);
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
if (schemaType.instance === "Decimal128" && schemaType.options.leanDecimal128ToString === true && isNonNullObject(value) && value._bsontype === "Decimal128" && typeof value.toString === "function") return value.toString();
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Converts marked Decimal128 fields to strings on lean queries without invoking getters.
|
|
45
|
+
*
|
|
46
|
+
* @remarks
|
|
47
|
+
* `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
|
|
48
|
+
* Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
|
|
49
|
+
* Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
|
|
50
|
+
* Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
|
|
51
|
+
* Registration is idempotent; the first registration's default options take precedence.
|
|
52
|
+
* Runtime conversion does not override Mongoose's inferred lean result types.
|
|
53
|
+
*/
|
|
54
|
+
function mongooseLeanDecimal128ToStringPlugin(schema, pluginOptions) {
|
|
55
|
+
if (registeredSchemas.has(schema)) return;
|
|
56
|
+
registeredSchemas.add(schema);
|
|
57
|
+
function convertResult(query, result) {
|
|
58
|
+
const leanOptions = query.mongooseOptions().lean;
|
|
59
|
+
if (!leanOptions) return result;
|
|
60
|
+
if (!(typeof leanOptions === "object" ? leanOptions.decimal128ToString ?? pluginOptions?.enabledByDefault ?? true : pluginOptions?.enabledByDefault ?? true)) return result;
|
|
61
|
+
const document = query.getOptions().includeResultMetadata && isNonNullObject(result) ? result.value : result;
|
|
62
|
+
const querySchema = query.model.schema;
|
|
63
|
+
if (Array.isArray(document)) document.forEach((value) => convertDocument(querySchema, value));
|
|
64
|
+
else convertDocument(querySchema, document);
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
schema.pre("find", function() {
|
|
68
|
+
const transform = (result) => convertResult(this, result);
|
|
69
|
+
if (typeof this.map === "function") this.map(transform);
|
|
70
|
+
else if (typeof this.transform === "function") this.transform(transform);
|
|
71
|
+
else this.setOptions({ transform });
|
|
72
|
+
});
|
|
73
|
+
schema.post([
|
|
74
|
+
"findOne",
|
|
75
|
+
"findOneAndUpdate",
|
|
76
|
+
"findOneAndDelete",
|
|
77
|
+
"findOneAndReplace"
|
|
78
|
+
], function(result) {
|
|
79
|
+
convertResult(this, result);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
export { mongooseLeanDecimal128ToStringPlugin };
|
|
84
|
+
|
|
85
|
+
//# sourceMappingURL=lean-decimal128-to-string.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lean-decimal128-to-string.js","names":[],"sources":["../../src/plugins/lean-decimal128-to-string.ts"],"sourcesContent":["import type {\n Query,\n Schema,\n SchemaType,\n} from 'mongoose';\n\ndeclare module 'mongoose' {\n interface LeanOptions {\n /** Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting. */\n decimal128ToString?: boolean;\n }\n}\n\ntype QueryWithOptionalMap = Query<unknown, unknown> & { map?: (transform: (result: unknown) => unknown) => unknown };\n\nexport interface MongooseLeanDecimal128ToStringPluginOptions {\n /** Whether marked fields are converted on lean queries by default. Defaults to true. */\n enabledByDefault?: boolean;\n}\n\n// Constants/Variables\nconst registeredSchemas = new WeakSet<Schema>();\n\n// Functions\nconst isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';\n\nfunction convertDocument(schema: Schema, value: unknown) {\n if (!isNonNullObject(value)) return;\n const discriminatorKey = schema.get('discriminatorKey') ?? '__t';\n const discriminatorSchema = Object.values(schema.discriminators ?? {}).find(\n (childSchema) => childSchema.get('discriminatorKey') === discriminatorKey\n && (childSchema as Schema & { discriminatorMapping?: { value: unknown } }).discriminatorMapping?.value\n === value[discriminatorKey],\n );\n\n const documentSchema = discriminatorSchema ?? schema;\n documentSchema.eachPath((path, schemaType) => {\n // Maps are handled through their embedded schema type, not their synthetic $* path.\n const pathSegments = path.split('.');\n if (pathSegments.includes('$*')) return;\n convertPath(value, pathSegments, schemaType);\n });\n}\n\nfunction convertPath(value: unknown, pathSegments: string[], schemaType: SchemaType) {\n if (Array.isArray(value)) {\n value.forEach((item) => convertPath(item, pathSegments, schemaType));\n return;\n }\n\n if (!isNonNullObject(value)) return;\n const [key, ...remainingPathSegments] = pathSegments;\n if (key === undefined || !Object.hasOwn(value, key)) return;\n if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);\n else value[key] = convertValue(value[key], schemaType);\n}\n\nfunction convertValue(value: unknown, schemaType: SchemaType): unknown {\n if (value === null || value === undefined) return value;\n const embeddedSchemaType = schemaType.getEmbeddedSchemaType();\n if (embeddedSchemaType && Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n if (Object.hasOwn(value, i)) value[i] = convertValue(value[i], embeddedSchemaType);\n }\n\n return value;\n }\n\n if (embeddedSchemaType && schemaType.instance === 'Map') {\n if (value instanceof Map) value.forEach((item, key) => value.set(key, convertValue(item, embeddedSchemaType)));\n else if (isNonNullObject(value)) {\n for (const key of Object.keys(value)) value[key] = convertValue(value[key], embeddedSchemaType);\n }\n\n return value;\n }\n\n if (schemaType.schema) {\n convertDocument(schemaType.schema, value);\n return value;\n }\n\n if (\n schemaType.instance === 'Decimal128'\n && schemaType.options.leanDecimal128ToString === true\n && isNonNullObject(value)\n && value._bsontype === 'Decimal128'\n && typeof value.toString === 'function'\n ) return value.toString();\n\n return value;\n}\n\n/**\n * Converts marked Decimal128 fields to strings on lean queries without invoking getters.\n *\n * @remarks\n * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.\n * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.\n * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.\n * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.\n * Registration is idempotent; the first registration's default options take precedence.\n * Runtime conversion does not override Mongoose's inferred lean result types.\n */\nexport function mongooseLeanDecimal128ToStringPlugin(\n schema: Schema,\n pluginOptions?: MongooseLeanDecimal128ToStringPluginOptions,\n) {\n if (registeredSchemas.has(schema)) return;\n registeredSchemas.add(schema);\n\n function convertResult(query: QueryWithOptionalMap, result: unknown) {\n const leanOptions = query.mongooseOptions().lean;\n if (!leanOptions) return result;\n const conversionEnabled = typeof leanOptions === 'object'\n ? leanOptions.decimal128ToString ?? pluginOptions?.enabledByDefault ?? true\n : pluginOptions?.enabledByDefault ?? true;\n\n if (!conversionEnabled) return result;\n const document = query.getOptions().includeResultMetadata && isNonNullObject(result) ? result.value : result;\n const querySchema = query.model.schema;\n if (Array.isArray(document)) document.forEach((value) => convertDocument(querySchema, value));\n else convertDocument(querySchema, document);\n return result;\n }\n\n // Find cursors do not run post('find'); match Mongoose's query/cursor transform surfaces.\n schema.pre(\n 'find',\n function (this: QueryWithOptionalMap) {\n const transform = (result: unknown) => convertResult(this, result);\n if (typeof this.map === 'function') this.map(transform);\n else if (typeof this.transform === 'function') this.transform(transform);\n else this.setOptions({ transform });\n },\n );\n\n schema.post(\n [\n 'findOne',\n 'findOneAndUpdate',\n 'findOneAndDelete',\n 'findOneAndReplace',\n ],\n function (this: QueryWithOptionalMap, result: unknown) {\n convertResult(this, result);\n },\n );\n}\n"],"mappings":"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"}
|
|
@@ -2,32 +2,42 @@ import { Schema } from "mongoose";
|
|
|
2
2
|
//#region src/plugins/normalize.d.ts
|
|
3
3
|
export interface MongooseNormalizePluginOptions {
|
|
4
4
|
/**
|
|
5
|
-
* Whether to
|
|
6
|
-
* If true, the `_id` field will be replaced with `id`.
|
|
5
|
+
* Whether to move the serialized `_id` value to `id`.
|
|
7
6
|
*
|
|
8
|
-
* @
|
|
7
|
+
* @remarks
|
|
8
|
+
* If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.
|
|
9
|
+
*
|
|
10
|
+
* @defaultValue `true`.
|
|
9
11
|
*/
|
|
10
12
|
convertIdField?: boolean;
|
|
13
|
+
/** Register normalization on child schemas too. Defaults to true. */
|
|
14
|
+
recursive?: boolean;
|
|
11
15
|
/**
|
|
12
|
-
* Whether to convert
|
|
16
|
+
* Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
|
|
17
|
+
*
|
|
18
|
+
* @remarks
|
|
19
|
+
* Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.
|
|
13
20
|
*
|
|
14
|
-
* @
|
|
21
|
+
* @defaultValue `true`.
|
|
15
22
|
*/
|
|
16
23
|
toHexIdIfObjectId?: boolean;
|
|
17
24
|
}
|
|
18
25
|
/**
|
|
19
|
-
*
|
|
26
|
+
* Registers JSON normalization on a Mongoose schema.
|
|
20
27
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* - Convert `Decimal128` fields to strings
|
|
26
|
-
* - Remove the `__v` version key
|
|
28
|
+
* @remarks
|
|
29
|
+
* Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,
|
|
30
|
+
* normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts
|
|
31
|
+
* truthy serialized values at registered `Decimal128` paths to strings.
|
|
27
32
|
*
|
|
28
|
-
*
|
|
33
|
+
* If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
|
|
34
|
+
* preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
|
|
35
|
+
* That transform can change the normalized output, and its errors propagate during serialization.
|
|
36
|
+
* Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
|
|
37
|
+
* Registration is idempotent per schema; the first registration's options take precedence.
|
|
29
38
|
*
|
|
30
|
-
* @param schema - The
|
|
39
|
+
* @param schema - The schema whose JSON serialization configuration is modified.
|
|
40
|
+
* @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
|
|
31
41
|
*/
|
|
32
42
|
export declare function mongooseNormalizePlugin<S extends Schema>(schema: S, pluginOptions?: MongooseNormalizePluginOptions): void;
|
|
33
43
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize.d.ts","names":[],"sources":["../../src/plugins/normalize.ts"],"mappings":";;iBAQiB
|
|
1
|
+
{"version":3,"file":"normalize.d.ts","names":[],"sources":["../../src/plugins/normalize.ts"],"mappings":";;iBAQiB;;;;;;;;;EASb;;EAGA;;;;;;;;;EAUA;;;;;;;;;;;;;;;;;;;wBAyBY,wBAAwB,UAAU,QAC9C,QAAQ,GACR,gBAAgB"}
|
|
@@ -1,21 +1,27 @@
|
|
|
1
1
|
import { Types } from "mongoose";
|
|
2
2
|
import { get, set, unset } from "es-toolkit/compat";
|
|
3
3
|
//#region src/plugins/normalize.ts
|
|
4
|
+
const registeredSchemas = /* @__PURE__ */ new WeakSet();
|
|
4
5
|
/**
|
|
5
|
-
*
|
|
6
|
+
* Registers JSON normalization on a Mongoose schema.
|
|
6
7
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* - Convert `Decimal128` fields to strings
|
|
12
|
-
* - Remove the `__v` version key
|
|
8
|
+
* @remarks
|
|
9
|
+
* Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,
|
|
10
|
+
* normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts
|
|
11
|
+
* truthy serialized values at registered `Decimal128` paths to strings.
|
|
13
12
|
*
|
|
14
|
-
*
|
|
13
|
+
* If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
|
|
14
|
+
* preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
|
|
15
|
+
* That transform can change the normalized output, and its errors propagate during serialization.
|
|
16
|
+
* Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
|
|
17
|
+
* Registration is idempotent per schema; the first registration's options take precedence.
|
|
15
18
|
*
|
|
16
|
-
* @param schema - The
|
|
19
|
+
* @param schema - The schema whose JSON serialization configuration is modified.
|
|
20
|
+
* @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
|
|
17
21
|
*/
|
|
18
22
|
function mongooseNormalizePlugin(schema, pluginOptions) {
|
|
23
|
+
if (registeredSchemas.has(schema)) return;
|
|
24
|
+
registeredSchemas.add(schema);
|
|
19
25
|
const decimalPaths = [];
|
|
20
26
|
const privatePaths = [];
|
|
21
27
|
for (const [path, schemaType] of Object.entries(schema.paths)) if (schemaType?.options?.private) privatePaths.push(path);
|
|
@@ -39,10 +45,14 @@ function mongooseNormalizePlugin(schema, pluginOptions) {
|
|
|
39
45
|
const value = get(copiedRet, path);
|
|
40
46
|
if (value) set(copiedRet, path, value.toString());
|
|
41
47
|
}
|
|
42
|
-
if (toJsonTransform && typeof toJsonTransform !== "boolean")
|
|
48
|
+
if (toJsonTransform && typeof toJsonTransform !== "boolean") {
|
|
49
|
+
const transformed = toJsonTransform(doc, copiedRet, options);
|
|
50
|
+
return transformed === void 0 ? copiedRet : transformed;
|
|
51
|
+
}
|
|
43
52
|
return copiedRet;
|
|
44
53
|
}
|
|
45
54
|
});
|
|
55
|
+
if (pluginOptions?.recursive !== false) schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));
|
|
46
56
|
}
|
|
47
57
|
//#endregion
|
|
48
58
|
export { mongooseNormalizePlugin };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize.js","names":["getProp"],"sources":["../../src/plugins/normalize.ts"],"sourcesContent":["import {\n get as getProp,\n set as setProp,\n unset as unsetProp,\n} from 'es-toolkit/compat';\nimport { Types } from 'mongoose';\nimport type { Schema } from 'mongoose';\n\nexport interface MongooseNormalizePluginOptions {\n /**\n * Whether to
|
|
1
|
+
{"version":3,"file":"normalize.js","names":["getProp"],"sources":["../../src/plugins/normalize.ts"],"sourcesContent":["import {\n get as getProp,\n set as setProp,\n unset as unsetProp,\n} from 'es-toolkit/compat';\nimport { Types } from 'mongoose';\nimport type { Schema } from 'mongoose';\n\nexport interface MongooseNormalizePluginOptions {\n /**\n * Whether to move the serialized `_id` value to `id`.\n *\n * @remarks\n * If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.\n *\n * @defaultValue `true`.\n */\n convertIdField?: boolean;\n\n /** Register normalization on child schemas too. Defaults to true. */\n recursive?: boolean;\n\n /**\n * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.\n *\n * @remarks\n * Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.\n *\n * @defaultValue `true`.\n */\n toHexIdIfObjectId?: boolean;\n}\n\n// Constants/Variables\nconst registeredSchemas = new WeakSet<Schema>();\n\n// Functions\n\n/**\n * Registers JSON normalization on a Mongoose schema.\n *\n * @remarks\n * Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,\n * normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts\n * truthy serialized values at registered `Decimal128` paths to strings.\n *\n * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,\n * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.\n * That transform can change the normalized output, and its errors propagate during serialization.\n * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.\n * Registration is idempotent per schema; the first registration's options take precedence.\n *\n * @param schema - The schema whose JSON serialization configuration is modified.\n * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.\n */\nexport function mongooseNormalizePlugin<S extends Schema>(\n schema: S,\n pluginOptions?: MongooseNormalizePluginOptions,\n) {\n if (registeredSchemas.has(schema)) return;\n registeredSchemas.add(schema);\n\n // Collect special paths (Decimal128 & private)\n const decimalPaths: string[] = [];\n const privatePaths: string[] = [];\n for (const [path, schemaType] of Object.entries(schema.paths)) {\n if (schemaType?.options?.private) privatePaths.push(path);\n else if (schemaType?.instance === 'Decimal128') decimalPaths.push(path);\n }\n\n // Get original toJSON configuration\n const toJson = schema.get('toJSON');\n const toJsonTransform = toJson?.transform;\n\n // Override toJSON with custom transform\n schema.set(\n 'toJSON',\n {\n ...toJson,\n transform(doc, ret, options) {\n // Copy object and remove __v\n const copiedRet = { ...ret };\n // @ts-expect-error Ignore this error\n delete copiedRet.__v;\n\n // Normalize _id (convert to hex and/or move to id)\n let _id = copiedRet._id;\n delete copiedRet._id;\n if (pluginOptions?.toHexIdIfObjectId !== false && _id instanceof Types.ObjectId) {\n _id = _id.toHexString();\n }\n\n if (_id !== undefined) {\n if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;\n else copiedRet._id = _id;\n }\n\n // Remove private fields\n for (const path of privatePaths) unsetProp(copiedRet, path);\n\n // Convert Decimal128 fields to string\n for (const path of decimalPaths) {\n const value = getProp(copiedRet, path) as Types.Decimal128 | undefined;\n if (value) setProp(copiedRet, path, value.toString());\n }\n\n // Run original toJSON transform\n if (toJsonTransform && typeof toJsonTransform !== 'boolean') {\n const transformed = toJsonTransform(doc as any, copiedRet as any, options as any);\n return transformed === undefined ? copiedRet : transformed;\n }\n\n // Return normalized object\n return copiedRet;\n },\n },\n );\n\n if (pluginOptions?.recursive !== false) {\n schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));\n }\n}\n"],"mappings":";;;AAkCA,MAAM,oCAAoB,IAAI,QAAgB;;;;;;;;;;;;;;;;;;AAqB9C,SAAgB,wBACZ,QACA,eACF;CACE,IAAI,kBAAkB,IAAI,MAAM,GAAG;CACnC,kBAAkB,IAAI,MAAM;CAG5B,MAAM,eAAyB,CAAC;CAChC,MAAM,eAAyB,CAAC;CAChC,KAAK,MAAM,CAAC,MAAM,eAAe,OAAO,QAAQ,OAAO,KAAK,GACxD,IAAI,YAAY,SAAS,SAAS,aAAa,KAAK,IAAI;MACnD,IAAI,YAAY,aAAa,cAAc,aAAa,KAAK,IAAI;CAI1E,MAAM,SAAS,OAAO,IAAI,QAAQ;CAClC,MAAM,kBAAkB,QAAQ;CAGhC,OAAO,IACH,UACA;EACI,GAAG;EACH,UAAU,KAAK,KAAK,SAAS;GAEzB,MAAM,YAAY,EAAE,GAAG,IAAI;GAE3B,OAAO,UAAU;GAGjB,IAAI,MAAM,UAAU;GACpB,OAAO,UAAU;GACjB,IAAI,eAAe,sBAAsB,SAAS,eAAe,MAAM,UACnE,MAAM,IAAI,YAAY;GAG1B,IAAI,QAAQ,KAAA,GAAW;IACnB,IAAI,eAAe,mBAAmB,OAAO,UAAU,KAAK;SACvD,UAAU,MAAM;GACzB;GAGA,KAAK,MAAM,QAAQ,cAAc,MAAU,WAAW,IAAI;GAG1D,KAAK,MAAM,QAAQ,cAAc;IAC7B,MAAM,QAAQA,IAAQ,WAAW,IAAI;IACrC,IAAI,OAAO,IAAQ,WAAW,MAAM,MAAM,SAAS,CAAC;GACxD;GAGA,IAAI,mBAAmB,OAAO,oBAAoB,WAAW;IACzD,MAAM,cAAc,gBAAgB,KAAY,WAAkB,OAAc;IAChF,OAAO,gBAAgB,KAAA,IAAY,YAAY;GACnD;GAGA,OAAO;EACX;CACJ,CACJ;CAEA,IAAI,eAAe,cAAc,OAC7B,OAAO,aAAa,SAAS,EAAE,QAAQ,YAAY,MAAM,OAAO,yBAAyB,aAAa,CAAC;AAE/G"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Schema } from "mongoose";
|
|
2
2
|
//#region src/schema-builders/base.d.ts
|
|
3
|
-
type BaseSchemaType = BooleanConstructor | DateConstructor | NumberConstructor | Schema.Types.ObjectId['constructor'] | StringConstructor;
|
|
3
|
+
type BaseSchemaType = BooleanConstructor | DateConstructor | NumberConstructor | Schema.Types.ObjectId['constructor'] | StringConstructor | typeof Schema.Types.BigInt | typeof Schema.Types.Double | typeof Schema.Types.Int32 | typeof Schema.Types.Mixed | typeof Schema.Types.UUID;
|
|
4
4
|
export declare function createBaseSchemaBuilderFactory<Builder = Readonly<Record<string, any>>>(type: BaseSchemaType): (schema?: Record<string, any>) => Builder;
|
|
5
5
|
//#endregion
|
|
6
6
|
//# sourceMappingURL=base.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/schema-builders/base.ts"],"mappings":";;KAEK,iBACD,qBACA,kBACA,oBACA,OAAO,MAAM,0BACb;
|
|
1
|
+
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/schema-builders/base.ts"],"mappings":";;KAEK,iBACD,qBACA,kBACA,oBACA,OAAO,MAAM,0BACb,2BACO,OAAO,MAAM,gBACb,OAAO,MAAM,gBACb,OAAO,MAAM,eACb,OAAO,MAAM,eACb,OAAO,MAAM;wBAcR,+BAA+B,UAAU,SAAS,sBAAsB,MAAM,kBAClF,SAAQ,wBA2BP"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":[],"sources":["../../src/schema-builders/base.ts"],"sourcesContent":["import type { Schema } from 'mongoose';\n\ntype BaseSchemaType =\n | BooleanConstructor\n | DateConstructor\n | NumberConstructor\n | Schema.Types.ObjectId['constructor']\n | StringConstructor;\n\n// Constants/Variables\nconst isFunctionKeys = new Set([\n 'default',\n 'enum',\n 'index',\n 'max',\n 'maxlength',\n 'min',\n 'minlength',\n]);\n\n// Functions\nexport function createBaseSchemaBuilderFactory<Builder = Readonly<Record<string, any>>>(type: BaseSchemaType) {\n return (schema: Record<string, any> = {}) => {\n schema.type = type;\n return new Proxy(\n Object.freeze({}),\n {\n get(_, key, receiver) {\n if (typeof key === 'symbol') throw new Error('Cannot use symbol as a schema attribute');\n if (key in schema) throw new Error(`Duplicate schema attribute: ${key}`);\n if (isFunctionKeys.has(key)) {\n return (value: any) => {\n schema[key] = value;\n return receiver;\n };\n }\n\n if (key === 'nonRequired') return { ...schema };\n if (key === 'required') {\n return {\n ...schema,\n required: true,\n };\n }\n\n schema[key] = true;\n return receiver;\n },\n },\n ) as Builder;\n };\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../src/schema-builders/base.ts"],"sourcesContent":["import type { Schema } from 'mongoose';\n\ntype BaseSchemaType =\n | BooleanConstructor\n | DateConstructor\n | NumberConstructor\n | Schema.Types.ObjectId['constructor']\n | StringConstructor\n | typeof Schema.Types.BigInt\n | typeof Schema.Types.Double\n | typeof Schema.Types.Int32\n | typeof Schema.Types.Mixed\n | typeof Schema.Types.UUID;\n\n// Constants/Variables\nconst isFunctionKeys = new Set([\n 'default',\n 'enum',\n 'index',\n 'max',\n 'maxlength',\n 'min',\n 'minlength',\n]);\n\n// Functions\nexport function createBaseSchemaBuilderFactory<Builder = Readonly<Record<string, any>>>(type: BaseSchemaType) {\n return (schema: Record<string, any> = {}) => {\n schema.type = type;\n return new Proxy(\n Object.freeze({}),\n {\n get(_, key, receiver) {\n if (typeof key === 'symbol') throw new Error('Cannot use symbol as a schema attribute');\n if (key in schema) throw new Error(`Duplicate schema attribute: ${key}`);\n if (isFunctionKeys.has(key)) {\n return (value: any) => {\n schema[key] = value;\n return receiver;\n };\n }\n\n if (key === 'nonRequired') return { ...schema };\n if (key === 'required') {\n return {\n ...schema,\n required: true,\n };\n }\n\n schema[key] = true;\n return receiver;\n },\n },\n ) as Builder;\n };\n}\n"],"mappings":";AAeA,MAAM,iCAAiB,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;AAGD,SAAgB,+BAAwE,MAAsB;CAC1G,QAAQ,SAA8B,CAAC,MAAM;EACzC,OAAO,OAAO;EACd,OAAO,IAAI,MACP,OAAO,OAAO,CAAC,CAAC,GAChB,EACI,IAAI,GAAG,KAAK,UAAU;GAClB,IAAI,OAAO,QAAQ,UAAU,MAAM,IAAI,MAAM,yCAAyC;GACtF,IAAI,OAAO,QAAQ,MAAM,IAAI,MAAM,+BAA+B,KAAK;GACvE,IAAI,eAAe,IAAI,GAAG,GACtB,QAAQ,UAAe;IACnB,OAAO,OAAO;IACd,OAAO;GACX;GAGJ,IAAI,QAAQ,eAAe,OAAO,EAAE,GAAG,OAAO;GAC9C,IAAI,QAAQ,YACR,OAAO;IACH,GAAG;IACH,UAAU;GACd;GAGJ,OAAO,OAAO;GACd,OAAO;EACX,EACJ,CACJ;CACJ;AACJ"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Readonlyable } from "../types/_internals.js";
|
|
2
|
+
import { DefaultType, IndexDirection, IndexOptions, Schema } from "mongoose";
|
|
3
|
+
import { Merge } from "type-fest";
|
|
4
|
+
//#region src/schema-builders/bigint.d.ts
|
|
5
|
+
type BigIntLimit = bigint;
|
|
6
|
+
type ExtendSchemaBuilder<Props extends BaseProps, ExtraOmitFields extends string> = Omit<BigIntSchemaBuilder<Props, ExtraOmitFields>, ExtraOmitFields | keyof Props>;
|
|
7
|
+
interface BaseProps {
|
|
8
|
+
type: typeof Schema.Types.BigInt;
|
|
9
|
+
}
|
|
10
|
+
interface BigIntEnumValidator {
|
|
11
|
+
enumValues: (bigint | null)[];
|
|
12
|
+
message: string;
|
|
13
|
+
type: 'enum';
|
|
14
|
+
validator: (value: bigint | null | undefined) => boolean;
|
|
15
|
+
}
|
|
16
|
+
interface BigIntLimitValidator {
|
|
17
|
+
max?: bigint;
|
|
18
|
+
message: string;
|
|
19
|
+
min?: bigint;
|
|
20
|
+
type: 'max' | 'min';
|
|
21
|
+
validator: (value: bigint | null | undefined) => boolean;
|
|
22
|
+
}
|
|
23
|
+
export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
|
|
24
|
+
default: <T extends ((this: any, doc: any) => DefaultType<D> | null | undefined) | DefaultType<D> | null | undefined, D extends bigint>(value: T) => ExtendSchemaBuilder<Merge<Props, {
|
|
25
|
+
default: T;
|
|
26
|
+
}>, ExtraOmitFields>;
|
|
27
|
+
enum: <T extends Readonlyable<(N | null)[]> | {
|
|
28
|
+
[path: string]: N | null;
|
|
29
|
+
} | {
|
|
30
|
+
message?: M;
|
|
31
|
+
values: Readonlyable<(N | null)[]>;
|
|
32
|
+
}, M extends string, N extends bigint>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'enum' | ExtraOmitFields>;
|
|
33
|
+
immutable: ExtendSchemaBuilder<Merge<Props, {
|
|
34
|
+
immutable: true;
|
|
35
|
+
}>, ExtraOmitFields>;
|
|
36
|
+
index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<Merge<Props, {
|
|
37
|
+
index: T;
|
|
38
|
+
}>, ExtraOmitFields>;
|
|
39
|
+
max: <T extends L | Readonlyable<[L, S]>, L extends BigIntLimit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'max' | ExtraOmitFields>;
|
|
40
|
+
min: <T extends L | Readonlyable<[L, S]>, L extends BigIntLimit, S extends string>(value: T) => ExtendSchemaBuilder<Merge<Props, BigIntValidationSchema>, 'min' | ExtraOmitFields>;
|
|
41
|
+
nonRequired: Props;
|
|
42
|
+
private: ExtendSchemaBuilder<Merge<Props, {
|
|
43
|
+
private: true;
|
|
44
|
+
}>, ExtraOmitFields>;
|
|
45
|
+
required: Merge<Props, {
|
|
46
|
+
required: true;
|
|
47
|
+
}>;
|
|
48
|
+
sparse: ExtendSchemaBuilder<Merge<Props, {
|
|
49
|
+
sparse: true;
|
|
50
|
+
}>, ExtraOmitFields>;
|
|
51
|
+
unique: ExtendSchemaBuilder<Merge<Props, {
|
|
52
|
+
unique: true;
|
|
53
|
+
}>, ExtraOmitFields>;
|
|
54
|
+
}
|
|
55
|
+
interface BigIntValidationSchema {
|
|
56
|
+
validate: (BigIntEnumValidator | BigIntLimitValidator)[];
|
|
57
|
+
}
|
|
58
|
+
export declare function bigintSchemaBuilder(): BigIntSchemaBuilder;
|
|
59
|
+
//#endregion
|
|
60
|
+
//# sourceMappingURL=bigint.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bigint.d.ts","names":[],"sources":["../../src/schema-builders/bigint.ts"],"mappings":";;;;KAYK;KACA,oBACD,cAAc,WACd,kCACA,KACA,oBAAoB,OAAO,kBAC3B,wBAAwB;UAGlB;EACN,aAAa,OAAO,MAAM;;UAGpB;EACN;EACA;EACA;EACA,YAAY;;UAGN;EACN;EACA;EACA;EACA;EACA,YAAY;;iBAGC,oBAAoB,cAAc,YAAY,WAAW;EACtE,UACI,YAAY,WAAW,aAAa,YAAY,yBAAyB,YAAY,uBACrF,kBACF,OAAO,MAAM,oBACX,MAAM;IAAS,SAAS;MACxB;EAGJ,OACI,UACE,cAAc;KACX,eAAe;;IAChB,UAAU;IAAG,QAAQ,cAAc;KACvC,kBACA,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,kCACJ;EAGb,WAAW,oBAAoB,MAAM;IAAS;MAAoB;EAClE,QAAQ,oBAAoB,iBAAiB,cAAc,OAAO,MAAM,oBACpE,MAAM;IAAS,OAAO;MACtB;EAGJ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,MACI,UAAU,IAAI,cAAc,GAAG,KAC/B,UAAU,aACV,kBACF,OAAO,MAAM,oBACX,MAAM,OAAO,iCACL;EAGZ,aAAa;EACb,SAAS,oBAAoB,MAAM;IAAS;MAAkB;EAC9D,UAAU,MAAM;IAAS;;EACzB,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;EAC5D,QAAQ,oBAAoB,MAAM;IAAS;MAAiB;;UAGtD;EACN,WAAW,sBAAsB;;wBAWrB,uBA2DP"}
|