@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/src/_internals.ts
CHANGED
package/src/builders.ts
CHANGED
|
@@ -1,16 +1,12 @@
|
|
|
1
|
-
import
|
|
2
|
-
import type {
|
|
3
|
-
Model as MongooseModel,
|
|
4
|
-
Schema,
|
|
5
|
-
} from 'mongoose';
|
|
1
|
+
import type { Schema } from 'mongoose';
|
|
6
2
|
import mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';
|
|
7
3
|
import mongoosePaginate from 'mongoose-paginate-v2';
|
|
8
4
|
|
|
9
5
|
import { customMongooseOptions } from './_internals';
|
|
10
|
-
import {
|
|
6
|
+
import { getDefaultMongooseConnection } from './connection';
|
|
11
7
|
import { mongooseAssertionsPlugin } from './plugins/assertions';
|
|
8
|
+
import { mongooseLeanDecimal128ToStringPlugin } from './plugins/lean-decimal128-to-string';
|
|
12
9
|
import { mongooseNormalizePlugin } from './plugins/normalize';
|
|
13
|
-
import type { MongooseNormalizePluginOptions } from './plugins/normalize';
|
|
14
10
|
import type { BaseMongoosePaginateModel } from './types';
|
|
15
11
|
import type { BuildMongooseModelOptions } from './types/options';
|
|
16
12
|
|
|
@@ -27,8 +23,20 @@ export function buildMongooseModel<
|
|
|
27
23
|
schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,
|
|
28
24
|
options?: BuildMongooseModelOptions,
|
|
29
25
|
): Model {
|
|
30
|
-
|
|
31
|
-
|
|
26
|
+
const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;
|
|
27
|
+
if (leanDecimal128ToStringPluginOptions !== false) {
|
|
28
|
+
schema.plugin(
|
|
29
|
+
mongooseLeanDecimal128ToStringPlugin,
|
|
30
|
+
typeof leanDecimal128ToStringPluginOptions === 'object' ? leanDecimal128ToStringPluginOptions : undefined,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const normalizePluginOptions = options?.plugins?.normalize;
|
|
35
|
+
if (normalizePluginOptions !== false) {
|
|
36
|
+
schema.plugin(
|
|
37
|
+
mongooseNormalizePlugin,
|
|
38
|
+
typeof normalizePluginOptions === 'object' ? normalizePluginOptions : undefined,
|
|
39
|
+
);
|
|
32
40
|
}
|
|
33
41
|
|
|
34
42
|
schema.plugin(mongooseAggregatePaginate);
|
|
@@ -36,28 +44,6 @@ export function buildMongooseModel<
|
|
|
36
44
|
schema.plugin(mongoosePaginate);
|
|
37
45
|
schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);
|
|
38
46
|
customMongooseOptions.beforeModelBuild?.(schema);
|
|
39
|
-
const connection =
|
|
40
|
-
options?.connection
|
|
41
|
-
|| (
|
|
42
|
-
mongooseConnections.default ||= mongoose.createConnection(
|
|
43
|
-
process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017',
|
|
44
|
-
)
|
|
45
|
-
);
|
|
46
|
-
|
|
47
|
+
const connection = options?.connection ?? getDefaultMongooseConnection();
|
|
47
48
|
return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);
|
|
48
49
|
}
|
|
49
|
-
export function registerMongooseNormalizePlugin<
|
|
50
|
-
DocType,
|
|
51
|
-
Model extends MongooseModel<DocType, QueryHelpers, InstanceMethodsAndOverrides>,
|
|
52
|
-
InstanceMethodsAndOverrides = object,
|
|
53
|
-
QueryHelpers = object,
|
|
54
|
-
>(
|
|
55
|
-
schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,
|
|
56
|
-
recursive: boolean = true,
|
|
57
|
-
options?: MongooseNormalizePluginOptions,
|
|
58
|
-
) {
|
|
59
|
-
schema.plugin(mongooseNormalizePlugin, options);
|
|
60
|
-
if (recursive) {
|
|
61
|
-
schema.childSchemas.forEach(({ schema }) => registerMongooseNormalizePlugin(schema, recursive, options));
|
|
62
|
-
}
|
|
63
|
-
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import type { Connection } from 'mongoose';
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
customMongooseOptions,
|
|
6
|
+
mongooseConnectionState,
|
|
7
|
+
} from './_internals';
|
|
8
|
+
|
|
9
|
+
export function getDefaultMongooseConnection(): Connection {
|
|
10
|
+
return mongooseConnectionState.defaultConnection ||= mongoose.createConnection(
|
|
11
|
+
process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017',
|
|
12
|
+
customMongooseOptions.defaultConnectionOptions,
|
|
13
|
+
);
|
|
14
|
+
}
|
package/src/options.ts
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
customMongooseOptions,
|
|
3
|
+
mongooseConnectionState,
|
|
4
|
+
} from './_internals';
|
|
2
5
|
import type { CustomMongooseOptions } from './types/options';
|
|
3
6
|
|
|
4
7
|
export function setCustomMongooseOptions<K extends keyof CustomMongooseOptions>(
|
|
5
8
|
key: K,
|
|
6
9
|
value: CustomMongooseOptions[K],
|
|
7
10
|
) {
|
|
11
|
+
if (key === 'defaultConnectionOptions' && mongooseConnectionState.defaultConnection) {
|
|
12
|
+
throw new Error('Default connection options must be set before the default connection is created.');
|
|
13
|
+
}
|
|
14
|
+
|
|
8
15
|
customMongooseOptions[key] = value;
|
|
9
16
|
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Query,
|
|
3
|
+
Schema,
|
|
4
|
+
SchemaType,
|
|
5
|
+
} from 'mongoose';
|
|
6
|
+
|
|
7
|
+
declare module 'mongoose' {
|
|
8
|
+
interface LeanOptions {
|
|
9
|
+
/** Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting. */
|
|
10
|
+
decimal128ToString?: boolean;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type QueryWithOptionalMap = Query<unknown, unknown> & { map?: (transform: (result: unknown) => unknown) => unknown };
|
|
15
|
+
|
|
16
|
+
export interface MongooseLeanDecimal128ToStringPluginOptions {
|
|
17
|
+
/** Whether marked fields are converted on lean queries by default. Defaults to true. */
|
|
18
|
+
enabledByDefault?: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Constants/Variables
|
|
22
|
+
const registeredSchemas = new WeakSet<Schema>();
|
|
23
|
+
|
|
24
|
+
// Functions
|
|
25
|
+
const isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';
|
|
26
|
+
|
|
27
|
+
function convertDocument(schema: Schema, value: unknown) {
|
|
28
|
+
if (!isNonNullObject(value)) return;
|
|
29
|
+
const discriminatorKey = schema.get('discriminatorKey') ?? '__t';
|
|
30
|
+
const discriminatorSchema = Object.values(schema.discriminators ?? {}).find(
|
|
31
|
+
(childSchema) => childSchema.get('discriminatorKey') === discriminatorKey
|
|
32
|
+
&& (childSchema as Schema & { discriminatorMapping?: { value: unknown } }).discriminatorMapping?.value
|
|
33
|
+
=== value[discriminatorKey],
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
const documentSchema = discriminatorSchema ?? schema;
|
|
37
|
+
documentSchema.eachPath((path, schemaType) => {
|
|
38
|
+
// Maps are handled through their embedded schema type, not their synthetic $* path.
|
|
39
|
+
const pathSegments = path.split('.');
|
|
40
|
+
if (pathSegments.includes('$*')) return;
|
|
41
|
+
convertPath(value, pathSegments, schemaType);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function convertPath(value: unknown, pathSegments: string[], schemaType: SchemaType) {
|
|
46
|
+
if (Array.isArray(value)) {
|
|
47
|
+
value.forEach((item) => convertPath(item, pathSegments, schemaType));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (!isNonNullObject(value)) return;
|
|
52
|
+
const [key, ...remainingPathSegments] = pathSegments;
|
|
53
|
+
if (key === undefined || !Object.hasOwn(value, key)) return;
|
|
54
|
+
if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);
|
|
55
|
+
else value[key] = convertValue(value[key], schemaType);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function convertValue(value: unknown, schemaType: SchemaType): unknown {
|
|
59
|
+
if (value === null || value === undefined) return value;
|
|
60
|
+
const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
|
|
61
|
+
if (embeddedSchemaType && Array.isArray(value)) {
|
|
62
|
+
for (let i = 0; i < value.length; i++) {
|
|
63
|
+
if (Object.hasOwn(value, i)) value[i] = convertValue(value[i], embeddedSchemaType);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (embeddedSchemaType && schemaType.instance === 'Map') {
|
|
70
|
+
if (value instanceof Map) value.forEach((item, key) => value.set(key, convertValue(item, embeddedSchemaType)));
|
|
71
|
+
else if (isNonNullObject(value)) {
|
|
72
|
+
for (const key of Object.keys(value)) value[key] = convertValue(value[key], embeddedSchemaType);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (schemaType.schema) {
|
|
79
|
+
convertDocument(schemaType.schema, value);
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (
|
|
84
|
+
schemaType.instance === 'Decimal128'
|
|
85
|
+
&& schemaType.options.leanDecimal128ToString === true
|
|
86
|
+
&& isNonNullObject(value)
|
|
87
|
+
&& value._bsontype === 'Decimal128'
|
|
88
|
+
&& typeof value.toString === 'function'
|
|
89
|
+
) return value.toString();
|
|
90
|
+
|
|
91
|
+
return value;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Converts marked Decimal128 fields to strings on lean queries without invoking getters.
|
|
96
|
+
*
|
|
97
|
+
* @remarks
|
|
98
|
+
* `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
|
|
99
|
+
* Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
|
|
100
|
+
* Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
|
|
101
|
+
* Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
|
|
102
|
+
* Registration is idempotent; the first registration's default options take precedence.
|
|
103
|
+
* Runtime conversion does not override Mongoose's inferred lean result types.
|
|
104
|
+
*/
|
|
105
|
+
export function mongooseLeanDecimal128ToStringPlugin(
|
|
106
|
+
schema: Schema,
|
|
107
|
+
pluginOptions?: MongooseLeanDecimal128ToStringPluginOptions,
|
|
108
|
+
) {
|
|
109
|
+
if (registeredSchemas.has(schema)) return;
|
|
110
|
+
registeredSchemas.add(schema);
|
|
111
|
+
|
|
112
|
+
function convertResult(query: QueryWithOptionalMap, result: unknown) {
|
|
113
|
+
const leanOptions = query.mongooseOptions().lean;
|
|
114
|
+
if (!leanOptions) return result;
|
|
115
|
+
const conversionEnabled = typeof leanOptions === 'object'
|
|
116
|
+
? leanOptions.decimal128ToString ?? pluginOptions?.enabledByDefault ?? true
|
|
117
|
+
: pluginOptions?.enabledByDefault ?? true;
|
|
118
|
+
|
|
119
|
+
if (!conversionEnabled) return result;
|
|
120
|
+
const document = query.getOptions().includeResultMetadata && isNonNullObject(result) ? result.value : result;
|
|
121
|
+
const querySchema = query.model.schema;
|
|
122
|
+
if (Array.isArray(document)) document.forEach((value) => convertDocument(querySchema, value));
|
|
123
|
+
else convertDocument(querySchema, document);
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Find cursors do not run post('find'); match Mongoose's query/cursor transform surfaces.
|
|
128
|
+
schema.pre(
|
|
129
|
+
'find',
|
|
130
|
+
function (this: QueryWithOptionalMap) {
|
|
131
|
+
const transform = (result: unknown) => convertResult(this, result);
|
|
132
|
+
if (typeof this.map === 'function') this.map(transform);
|
|
133
|
+
else if (typeof this.transform === 'function') this.transform(transform);
|
|
134
|
+
else this.setOptions({ transform });
|
|
135
|
+
},
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
schema.post(
|
|
139
|
+
[
|
|
140
|
+
'findOne',
|
|
141
|
+
'findOneAndUpdate',
|
|
142
|
+
'findOneAndDelete',
|
|
143
|
+
'findOneAndReplace',
|
|
144
|
+
],
|
|
145
|
+
function (this: QueryWithOptionalMap, result: unknown) {
|
|
146
|
+
convertResult(this, result);
|
|
147
|
+
},
|
|
148
|
+
);
|
|
149
|
+
}
|
package/src/plugins/normalize.ts
CHANGED
|
@@ -8,39 +8,58 @@ import type { Schema } from 'mongoose';
|
|
|
8
8
|
|
|
9
9
|
export interface MongooseNormalizePluginOptions {
|
|
10
10
|
/**
|
|
11
|
-
* Whether to
|
|
12
|
-
* If true, the `_id` field will be replaced with `id`.
|
|
11
|
+
* Whether to move the serialized `_id` value to `id`.
|
|
13
12
|
*
|
|
14
|
-
* @
|
|
13
|
+
* @remarks
|
|
14
|
+
* If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.
|
|
15
|
+
*
|
|
16
|
+
* @defaultValue `true`.
|
|
15
17
|
*/
|
|
16
18
|
convertIdField?: boolean;
|
|
17
19
|
|
|
20
|
+
/** Register normalization on child schemas too. Defaults to true. */
|
|
21
|
+
recursive?: boolean;
|
|
22
|
+
|
|
18
23
|
/**
|
|
19
|
-
* Whether to convert
|
|
24
|
+
* Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
|
|
20
25
|
*
|
|
21
|
-
* @
|
|
26
|
+
* @remarks
|
|
27
|
+
* Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.
|
|
28
|
+
*
|
|
29
|
+
* @defaultValue `true`.
|
|
22
30
|
*/
|
|
23
31
|
toHexIdIfObjectId?: boolean;
|
|
24
32
|
}
|
|
25
33
|
|
|
34
|
+
// Constants/Variables
|
|
35
|
+
const registeredSchemas = new WeakSet<Schema>();
|
|
36
|
+
|
|
37
|
+
// Functions
|
|
38
|
+
|
|
26
39
|
/**
|
|
27
|
-
*
|
|
40
|
+
* Registers JSON normalization on a Mongoose schema.
|
|
28
41
|
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* - Convert `Decimal128` fields to strings
|
|
34
|
-
* - Remove the `__v` version key
|
|
42
|
+
* @remarks
|
|
43
|
+
* Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,
|
|
44
|
+
* normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts
|
|
45
|
+
* truthy serialized values at registered `Decimal128` paths to strings.
|
|
35
46
|
*
|
|
36
|
-
*
|
|
47
|
+
* If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
|
|
48
|
+
* preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
|
|
49
|
+
* That transform can change the normalized output, and its errors propagate during serialization.
|
|
50
|
+
* Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
|
|
51
|
+
* Registration is idempotent per schema; the first registration's options take precedence.
|
|
37
52
|
*
|
|
38
|
-
* @param schema - The
|
|
53
|
+
* @param schema - The schema whose JSON serialization configuration is modified.
|
|
54
|
+
* @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
|
|
39
55
|
*/
|
|
40
56
|
export function mongooseNormalizePlugin<S extends Schema>(
|
|
41
57
|
schema: S,
|
|
42
58
|
pluginOptions?: MongooseNormalizePluginOptions,
|
|
43
59
|
) {
|
|
60
|
+
if (registeredSchemas.has(schema)) return;
|
|
61
|
+
registeredSchemas.add(schema);
|
|
62
|
+
|
|
44
63
|
// Collect special paths (Decimal128 & private)
|
|
45
64
|
const decimalPaths: string[] = [];
|
|
46
65
|
const privatePaths: string[] = [];
|
|
@@ -87,7 +106,8 @@ export function mongooseNormalizePlugin<S extends Schema>(
|
|
|
87
106
|
|
|
88
107
|
// Run original toJSON transform
|
|
89
108
|
if (toJsonTransform && typeof toJsonTransform !== 'boolean') {
|
|
90
|
-
|
|
109
|
+
const transformed = toJsonTransform(doc as any, copiedRet as any, options as any);
|
|
110
|
+
return transformed === undefined ? copiedRet : transformed;
|
|
91
111
|
}
|
|
92
112
|
|
|
93
113
|
// Return normalized object
|
|
@@ -95,4 +115,8 @@ export function mongooseNormalizePlugin<S extends Schema>(
|
|
|
95
115
|
},
|
|
96
116
|
},
|
|
97
117
|
);
|
|
118
|
+
|
|
119
|
+
if (pluginOptions?.recursive !== false) {
|
|
120
|
+
schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));
|
|
121
|
+
}
|
|
98
122
|
}
|
|
@@ -5,7 +5,12 @@ type BaseSchemaType =
|
|
|
5
5
|
| DateConstructor
|
|
6
6
|
| NumberConstructor
|
|
7
7
|
| Schema.Types.ObjectId['constructor']
|
|
8
|
-
| StringConstructor
|
|
8
|
+
| StringConstructor
|
|
9
|
+
| typeof Schema.Types.BigInt
|
|
10
|
+
| typeof Schema.Types.Double
|
|
11
|
+
| typeof Schema.Types.Int32
|
|
12
|
+
| typeof Schema.Types.Mixed
|
|
13
|
+
| typeof Schema.Types.UUID;
|
|
9
14
|
|
|
10
15
|
// Constants/Variables
|
|
11
16
|
const isFunctionKeys = new Set([
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { Schema } from 'mongoose';
|
|
2
|
+
import type {
|
|
3
|
+
DefaultType,
|
|
4
|
+
IndexDirection,
|
|
5
|
+
IndexOptions,
|
|
6
|
+
} from 'mongoose';
|
|
7
|
+
import type { Merge } from 'type-fest';
|
|
8
|
+
|
|
9
|
+
import type { Readonlyable } from '../types/_internals';
|
|
10
|
+
|
|
11
|
+
import { createBaseSchemaBuilderFactory } from './base';
|
|
12
|
+
|
|
13
|
+
type BigIntLimit = bigint;
|
|
14
|
+
type ExtendSchemaBuilder<
|
|
15
|
+
Props extends BaseProps,
|
|
16
|
+
ExtraOmitFields extends string,
|
|
17
|
+
> = Omit<
|
|
18
|
+
BigIntSchemaBuilder<Props, ExtraOmitFields>,
|
|
19
|
+
ExtraOmitFields | keyof Props
|
|
20
|
+
>;
|
|
21
|
+
|
|
22
|
+
interface BaseProps {
|
|
23
|
+
type: typeof Schema.Types.BigInt;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface BigIntEnumValidator {
|
|
27
|
+
enumValues: (bigint | null)[];
|
|
28
|
+
message: string;
|
|
29
|
+
type: 'enum';
|
|
30
|
+
validator: (value: bigint | null | undefined) => boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface BigIntLimitValidator {
|
|
34
|
+
max?: bigint;
|
|
35
|
+
message: string;
|
|
36
|
+
min?: bigint;
|
|
37
|
+
type: 'max' | 'min';
|
|
38
|
+
validator: (value: bigint | null | undefined) => boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
|
|
42
|
+
default: <
|
|
43
|
+
T extends ((this: any, doc: any) => DefaultType<D> | null | undefined) | DefaultType<D> | null | undefined,
|
|
44
|
+
D extends bigint,
|
|
45
|
+
>(value: T) => ExtendSchemaBuilder<
|
|
46
|
+
Merge<Props, { default: T }>,
|
|
47
|
+
ExtraOmitFields
|
|
48
|
+
>;
|
|
49
|
+
|
|
50
|
+
enum: <
|
|
51
|
+
T extends
|
|
52
|
+
| Readonlyable<(N | null)[]>
|
|
53
|
+
| { [path: string]: N | null }
|
|
54
|
+
| { message?: M; values: Readonlyable<(N | null)[]> },
|
|
55
|
+
M extends string,
|
|
56
|
+
N extends bigint,
|
|
57
|
+
>(value: T) => ExtendSchemaBuilder<
|
|
58
|
+
Merge<Props, BigIntValidationSchema>,
|
|
59
|
+
'enum' | ExtraOmitFields
|
|
60
|
+
>;
|
|
61
|
+
|
|
62
|
+
immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;
|
|
63
|
+
index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<
|
|
64
|
+
Merge<Props, { index: T }>,
|
|
65
|
+
ExtraOmitFields
|
|
66
|
+
>;
|
|
67
|
+
|
|
68
|
+
max: <
|
|
69
|
+
T extends L | Readonlyable<[L, S]>,
|
|
70
|
+
L extends BigIntLimit,
|
|
71
|
+
S extends string,
|
|
72
|
+
>(value: T) => ExtendSchemaBuilder<
|
|
73
|
+
Merge<Props, BigIntValidationSchema>,
|
|
74
|
+
'max' | ExtraOmitFields
|
|
75
|
+
>;
|
|
76
|
+
|
|
77
|
+
min: <
|
|
78
|
+
T extends L | Readonlyable<[L, S]>,
|
|
79
|
+
L extends BigIntLimit,
|
|
80
|
+
S extends string,
|
|
81
|
+
>(value: T) => ExtendSchemaBuilder<
|
|
82
|
+
Merge<Props, BigIntValidationSchema>,
|
|
83
|
+
'min' | ExtraOmitFields
|
|
84
|
+
>;
|
|
85
|
+
|
|
86
|
+
nonRequired: Props;
|
|
87
|
+
private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;
|
|
88
|
+
required: Merge<Props, { required: true }>;
|
|
89
|
+
sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;
|
|
90
|
+
unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface BigIntValidationSchema {
|
|
94
|
+
validate: (BigIntEnumValidator | BigIntLimitValidator)[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Constants/Variables
|
|
98
|
+
const defaultEnumValidateMessage = 'Path `{PATH}` ({VALUE}) is not a valid enum value.';
|
|
99
|
+
const defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';
|
|
100
|
+
const defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';
|
|
101
|
+
|
|
102
|
+
// Functions
|
|
103
|
+
const baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.BigInt);
|
|
104
|
+
|
|
105
|
+
export function bigintSchemaBuilder() {
|
|
106
|
+
const schema: Record<string, any> = {};
|
|
107
|
+
const baseBuilder = baseBuilderFactory(schema);
|
|
108
|
+
return new Proxy(
|
|
109
|
+
baseBuilder,
|
|
110
|
+
{
|
|
111
|
+
get(target, key, receiver) {
|
|
112
|
+
if (key === 'enum') {
|
|
113
|
+
if (schema.validate?.some(({ type }: { type: string }) => type === 'enum')) {
|
|
114
|
+
throw new Error('Duplicate schema attribute: enum');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return (
|
|
118
|
+
value: Readonlyable<(bigint | null)[]>
|
|
119
|
+
| { [path: string]: bigint | null }
|
|
120
|
+
| { message?: string; values: Readonlyable<(bigint | null)[]> },
|
|
121
|
+
) => {
|
|
122
|
+
let enumValues: (bigint | null)[];
|
|
123
|
+
let message: string | undefined;
|
|
124
|
+
|
|
125
|
+
if (Array.isArray(value)) enumValues = [...value];
|
|
126
|
+
else if ('values' in value && Array.isArray(value.values)) {
|
|
127
|
+
enumValues = [...value.values];
|
|
128
|
+
if ('message' in value && typeof value.message === 'string') message = value.message;
|
|
129
|
+
} else enumValues = Object.values(value);
|
|
130
|
+
|
|
131
|
+
const allowedValues = new Set(enumValues);
|
|
132
|
+
const validator: BigIntEnumValidator = {
|
|
133
|
+
enumValues,
|
|
134
|
+
message: message ?? defaultEnumValidateMessage,
|
|
135
|
+
type: 'enum',
|
|
136
|
+
validator: (value) => value === null || value === undefined || allowedValues.has(value),
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
schema.validate = [
|
|
140
|
+
...schema.validate ?? [],
|
|
141
|
+
validator,
|
|
142
|
+
];
|
|
143
|
+
|
|
144
|
+
return receiver;
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (key === 'max' || key === 'min') {
|
|
149
|
+
return (value: BigIntLimit | Readonlyable<[BigIntLimit, string]>) => {
|
|
150
|
+
const validator = createLimitValidator(key, value);
|
|
151
|
+
const validators = Array.isArray(schema.validate) ? schema.validate : [];
|
|
152
|
+
schema.validate = [
|
|
153
|
+
...validators.filter(({ type }) => type !== key),
|
|
154
|
+
validator,
|
|
155
|
+
];
|
|
156
|
+
|
|
157
|
+
return receiver;
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return Reflect.get(target, key, receiver);
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
) as BigIntSchemaBuilder;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function createLimitValidator(
|
|
168
|
+
type: 'max' | 'min',
|
|
169
|
+
value: BigIntLimit | Readonlyable<[BigIntLimit, string]>,
|
|
170
|
+
): BigIntLimitValidator {
|
|
171
|
+
const [limit, message] = Array.isArray(value)
|
|
172
|
+
? value as Readonly<[BigIntLimit, string]>
|
|
173
|
+
: [
|
|
174
|
+
value as BigIntLimit,
|
|
175
|
+
undefined,
|
|
176
|
+
];
|
|
177
|
+
|
|
178
|
+
if (typeof limit !== 'bigint') throw new TypeError(`BigInt ${type} limit must be a bigint`);
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
message: message ?? (type === 'min' ? defaultMinValidateMessage : defaultMaxValidateMessage),
|
|
182
|
+
[type]: limit,
|
|
183
|
+
type,
|
|
184
|
+
validator: (value) => {
|
|
185
|
+
if (value === null || value === undefined) return true;
|
|
186
|
+
|
|
187
|
+
return type === 'min' ? value >= limit : value <= limit;
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
@@ -20,10 +20,7 @@ interface BaseProps {
|
|
|
20
20
|
type: BooleanSchemaDefinition;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
export interface BooleanSchemaBuilder<
|
|
24
|
-
Props extends BaseProps = BaseProps,
|
|
25
|
-
ExtraOmitFields extends string = never,
|
|
26
|
-
> {
|
|
23
|
+
export interface BooleanSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
|
|
27
24
|
default: <
|
|
28
25
|
T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null,
|
|
29
26
|
D extends boolean,
|
|
@@ -36,9 +36,9 @@ export interface DateSchemaBuilder<
|
|
|
36
36
|
|
|
37
37
|
enum: <
|
|
38
38
|
T extends
|
|
39
|
-
| Readonlyable<
|
|
39
|
+
| Readonlyable<(D | null)[]>
|
|
40
40
|
| { [path: string]: D | null }
|
|
41
|
-
| { message?: M; values: Readonlyable<
|
|
41
|
+
| { message?: M; values: Readonlyable<(D | null)[]> },
|
|
42
42
|
D extends NativeDate,
|
|
43
43
|
M extends string,
|
|
44
44
|
>(value: T) => ExtendSchemaBuilder<
|
|
@@ -47,9 +47,9 @@ export interface Decimal128SchemaBuilder<
|
|
|
47
47
|
|
|
48
48
|
enum: <
|
|
49
49
|
T extends
|
|
50
|
-
| Readonlyable<
|
|
50
|
+
| Readonlyable<(D | null)[]>
|
|
51
51
|
| { [path: string]: D | null }
|
|
52
|
-
| { message?: M; values: Readonlyable<
|
|
52
|
+
| { message?: M; values: Readonlyable<(D | null)[]> },
|
|
53
53
|
D extends Types.Decimal128,
|
|
54
54
|
M extends string,
|
|
55
55
|
>(value: T) => ExtendSchemaBuilder<
|
|
@@ -86,14 +86,18 @@ export interface Decimal128SchemaBuilder<
|
|
|
86
86
|
required: Merge<Props, { required: true }>;
|
|
87
87
|
|
|
88
88
|
/**
|
|
89
|
-
*
|
|
90
|
-
* This method allows specifying the number of decimal places and the rounding strategy to be used when
|
|
91
|
-
* saving the field to the database.
|
|
89
|
+
* Configures a setter that rounds decimal values and formats them with a fixed number of decimal places.
|
|
92
90
|
*
|
|
93
|
-
* @
|
|
94
|
-
*
|
|
91
|
+
* @remarks
|
|
92
|
+
* Replaces the configured setter on this builder. The setter converts non-nullish values through Decimal.js
|
|
93
|
+
* and returns a decimal string for Mongoose to cast to `Decimal128`. It returns `undefined` for `null` or
|
|
94
|
+
* `undefined`. Decimal.js validates conversion and formatting when the setter processes a value,
|
|
95
|
+
* not when the setter is configured.
|
|
95
96
|
*
|
|
96
|
-
* @
|
|
97
|
+
* @param places - The non-negative integer number of decimal places. Defaults to `2`.
|
|
98
|
+
* @param rounding - The Decimal.js rounding mode. Defaults to `Decimal.ROUND_DOWN`, which rounds toward zero.
|
|
99
|
+
*
|
|
100
|
+
* @returns This instance for chaining.
|
|
97
101
|
*/
|
|
98
102
|
setRoundAndToFixedSetter: (places?: number, rounding?: Decimal.Rounding) => ExtendSchemaBuilder<
|
|
99
103
|
Merge<Props, ToStringSetterSchema>,
|
|
@@ -101,13 +105,14 @@ export interface Decimal128SchemaBuilder<
|
|
|
101
105
|
>;
|
|
102
106
|
|
|
103
107
|
/**
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
+
* Configures a getter that converts decimal values to strings.
|
|
109
|
+
*
|
|
110
|
+
* @remarks
|
|
111
|
+
* Replaces the configured getter on this builder. The getter returns the value's string representation,
|
|
112
|
+
* or `undefined` for `null` or `undefined`. It changes the read representation, not the stored BSON type.
|
|
113
|
+
* Marks this path for the lean Decimal128-to-string plugin; the plugin does not invoke this getter.
|
|
108
114
|
*
|
|
109
|
-
* @returns
|
|
110
|
-
* when accessed in the application.
|
|
115
|
+
* @returns This instance for chaining.
|
|
111
116
|
*/
|
|
112
117
|
setToStringGetter: ExtendSchemaBuilder<Merge<Props, ToStringGetterSchema>, 'setToStringGetter' | ExtraOmitFields>;
|
|
113
118
|
sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;
|
|
@@ -120,6 +125,7 @@ interface Decimal128ValidationSchema {
|
|
|
120
125
|
|
|
121
126
|
interface ToStringGetterSchema {
|
|
122
127
|
get: (value?: Types.Decimal128) => string | undefined;
|
|
128
|
+
leanDecimal128ToString: true;
|
|
123
129
|
}
|
|
124
130
|
|
|
125
131
|
interface ToStringSetterSchema {
|
|
@@ -195,6 +201,7 @@ export function decimal128SchemaBuilder() {
|
|
|
195
201
|
|
|
196
202
|
if (key === 'setToStringGetter') {
|
|
197
203
|
schema.get = (value?: Types.Decimal128) => value?.toString();
|
|
204
|
+
schema.leanDecimal128ToString = true;
|
|
198
205
|
return receiver;
|
|
199
206
|
}
|
|
200
207
|
|