@kikiutils/mongoose 9.0.5 → 10.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 +13 -25
- package/dist/_internals.d.ts +10 -1
- package/dist/_internals.d.ts.map +1 -1
- package/dist/_internals.js +20 -1
- package/dist/_internals.js.map +1 -1
- package/dist/assertions.d.ts +5 -2
- package/dist/assertions.d.ts.map +1 -1
- package/dist/assertions.js +10 -4
- package/dist/assertions.js.map +1 -1
- package/dist/builders.d.ts +9 -4
- package/dist/builders.d.ts.map +1 -1
- package/dist/builders.js +9 -9
- package/dist/builders.js.map +1 -1
- package/dist/connection.d.ts +3 -0
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +7 -1
- package/dist/connection.js.map +1 -1
- package/dist/documents.d.ts +8 -0
- package/dist/documents.d.ts.map +1 -0
- package/dist/documents.js +10 -0
- package/dist/documents.js.map +1 -0
- package/dist/errors/duplicate-key.d.ts +9 -0
- package/dist/errors/duplicate-key.d.ts.map +1 -0
- package/dist/errors/duplicate-key.js +15 -0
- package/dist/errors/duplicate-key.js.map +1 -0
- package/dist/errors/mongoose-update-conflict-error.d.ts +4 -0
- package/dist/errors/mongoose-update-conflict-error.d.ts.map +1 -0
- package/dist/errors/mongoose-update-conflict-error.js +7 -0
- package/dist/errors/mongoose-update-conflict-error.js.map +1 -0
- package/dist/options.d.ts +15 -1
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +19 -2
- package/dist/options.js.map +1 -1
- package/dist/plugins/assertions.d.ts +30 -9
- package/dist/plugins/assertions.d.ts.map +1 -1
- package/dist/plugins/assertions.js +32 -4
- package/dist/plugins/assertions.js.map +1 -1
- package/dist/plugins/lean-decimal128-to-string.d.ts +3 -15
- package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -1
- package/dist/plugins/lean-decimal128-to-string.js +30 -23
- package/dist/plugins/lean-decimal128-to-string.js.map +1 -1
- package/dist/plugins/normalize.d.ts +3 -40
- package/dist/plugins/normalize.d.ts.map +1 -1
- package/dist/plugins/normalize.js +98 -44
- package/dist/plugins/normalize.js.map +1 -1
- package/dist/schema-builders/_internals/array.d.ts +9 -0
- package/dist/schema-builders/_internals/array.d.ts.map +1 -0
- package/dist/schema-builders/_internals/array.js +12 -0
- package/dist/schema-builders/_internals/array.js.map +1 -0
- package/dist/schema-builders/_internals/boolean.d.ts +8 -0
- package/dist/schema-builders/_internals/boolean.d.ts.map +1 -0
- package/dist/schema-builders/_internals/boolean.js +9 -0
- package/dist/schema-builders/_internals/boolean.js.map +1 -0
- package/dist/schema-builders/_internals/date.d.ts +8 -0
- package/dist/schema-builders/_internals/date.d.ts.map +1 -0
- package/dist/schema-builders/_internals/date.js +9 -0
- package/dist/schema-builders/_internals/date.js.map +1 -0
- package/dist/schema-builders/_internals/decimal128.d.ts +36 -0
- package/dist/schema-builders/_internals/decimal128.d.ts.map +1 -0
- package/dist/schema-builders/_internals/decimal128.js +38 -0
- package/dist/schema-builders/_internals/decimal128.js.map +1 -0
- package/dist/schema-builders/_internals/int32.d.ts +21 -0
- package/dist/schema-builders/_internals/int32.d.ts.map +1 -0
- package/dist/schema-builders/_internals/int32.js +29 -0
- package/dist/schema-builders/_internals/int32.js.map +1 -0
- package/dist/schema-builders/_internals/mixed.d.ts +9 -0
- package/dist/schema-builders/_internals/mixed.d.ts.map +1 -0
- package/dist/schema-builders/_internals/mixed.js +10 -0
- package/dist/schema-builders/_internals/mixed.js.map +1 -0
- package/dist/schema-builders/_internals/number.d.ts +21 -0
- package/dist/schema-builders/_internals/number.d.ts.map +1 -0
- package/dist/schema-builders/_internals/number.js +20 -0
- package/dist/schema-builders/_internals/number.js.map +1 -0
- package/dist/schema-builders/_internals/object-id.d.ts +9 -0
- package/dist/schema-builders/_internals/object-id.d.ts.map +1 -0
- package/dist/schema-builders/_internals/object-id.js +10 -0
- package/dist/schema-builders/_internals/object-id.js.map +1 -0
- package/dist/schema-builders/_internals/ref.d.ts +8 -0
- package/dist/schema-builders/_internals/ref.d.ts.map +1 -0
- package/dist/schema-builders/_internals/ref.js +13 -0
- package/dist/schema-builders/_internals/ref.js.map +1 -0
- package/dist/schema-builders/_internals/shared.d.ts +104 -0
- package/dist/schema-builders/_internals/shared.d.ts.map +1 -0
- package/dist/schema-builders/_internals/shared.js +128 -0
- package/dist/schema-builders/_internals/shared.js.map +1 -0
- package/dist/schema-builders/_internals/string.d.ts +37 -0
- package/dist/schema-builders/_internals/string.d.ts.map +1 -0
- package/dist/schema-builders/_internals/string.js +39 -0
- package/dist/schema-builders/_internals/string.js.map +1 -0
- package/dist/schema-builders/index.d.ts +12 -13
- package/dist/schema-builders/index.js +11 -13
- package/dist/transaction.d.ts +10 -0
- package/dist/transaction.d.ts.map +1 -0
- package/dist/transaction.js +9 -0
- package/dist/transaction.js.map +1 -0
- package/dist/types/data.d.ts +3 -5
- package/dist/types/data.d.ts.map +1 -1
- package/dist/types/index.d.ts +15 -11
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/paginate.d.ts +4 -19
- package/dist/types/paginate.d.ts.map +1 -1
- package/package.json +17 -19
- package/src/_internals.ts +31 -1
- package/src/assertions.ts +20 -11
- package/src/builders.ts +26 -18
- package/src/connection.ts +8 -2
- package/src/documents.ts +12 -0
- package/src/errors/duplicate-key.ts +14 -0
- package/src/errors/mongoose-update-conflict-error.ts +3 -0
- package/src/options.ts +31 -1
- package/src/plugins/assertions.ts +117 -49
- package/src/plugins/lean-decimal128-to-string.ts +47 -41
- package/src/plugins/normalize.ts +169 -99
- package/src/schema-builders/_internals/array.ts +15 -0
- package/src/schema-builders/_internals/boolean.ts +10 -0
- package/src/schema-builders/_internals/date.ts +11 -0
- package/src/schema-builders/_internals/decimal128.ts +79 -0
- package/src/schema-builders/_internals/int32.ts +58 -0
- package/src/schema-builders/_internals/mixed.ts +12 -0
- package/src/schema-builders/_internals/number.ts +71 -0
- package/src/schema-builders/_internals/object-id.ts +13 -0
- package/src/schema-builders/_internals/ref.ts +18 -0
- package/src/schema-builders/_internals/shared.ts +302 -0
- package/src/schema-builders/_internals/string.ts +113 -0
- package/src/schema-builders/index.ts +26 -35
- package/src/transaction.ts +22 -0
- package/src/types/data.ts +5 -10
- package/src/types/index.ts +32 -22
- package/src/types/paginate.ts +9 -24
- package/dist/schema-builders/_internals.d.ts +0 -18
- package/dist/schema-builders/_internals.d.ts.map +0 -1
- package/dist/schema-builders/_internals.js +0 -36
- package/dist/schema-builders/_internals.js.map +0 -1
- package/dist/schema-builders/base.d.ts +0 -5
- package/dist/schema-builders/base.d.ts.map +0 -1
- package/dist/schema-builders/base.js +0 -33
- package/dist/schema-builders/base.js.map +0 -1
- package/dist/schema-builders/bigint.d.ts +0 -39
- package/dist/schema-builders/bigint.d.ts.map +0 -1
- package/dist/schema-builders/bigint.js +0 -47
- package/dist/schema-builders/bigint.js.map +0 -1
- package/dist/schema-builders/boolean.d.ts +0 -33
- package/dist/schema-builders/boolean.d.ts.map +0 -1
- package/dist/schema-builders/boolean.js +0 -6
- package/dist/schema-builders/boolean.js.map +0 -1
- package/dist/schema-builders/date.d.ts +0 -49
- package/dist/schema-builders/date.d.ts.map +0 -1
- package/dist/schema-builders/date.js +0 -6
- package/dist/schema-builders/date.js.map +0 -1
- package/dist/schema-builders/decimal128.d.ts +0 -79
- package/dist/schema-builders/decimal128.d.ts.map +0 -1
- package/dist/schema-builders/decimal128.js +0 -47
- package/dist/schema-builders/decimal128.js.map +0 -1
- package/dist/schema-builders/double.d.ts +0 -39
- package/dist/schema-builders/double.d.ts.map +0 -1
- package/dist/schema-builders/double.js +0 -51
- package/dist/schema-builders/double.js.map +0 -1
- package/dist/schema-builders/int32.d.ts +0 -39
- package/dist/schema-builders/int32.d.ts.map +0 -1
- package/dist/schema-builders/int32.js +0 -47
- package/dist/schema-builders/int32.js.map +0 -1
- package/dist/schema-builders/mixed.d.ts +0 -33
- package/dist/schema-builders/mixed.d.ts.map +0 -1
- package/dist/schema-builders/mixed.js +0 -7
- package/dist/schema-builders/mixed.js.map +0 -1
- package/dist/schema-builders/number.d.ts +0 -49
- package/dist/schema-builders/number.d.ts.map +0 -1
- package/dist/schema-builders/number.js +0 -6
- package/dist/schema-builders/number.js.map +0 -1
- package/dist/schema-builders/object-id.d.ts +0 -43
- package/dist/schema-builders/object-id.d.ts.map +0 -1
- package/dist/schema-builders/object-id.js +0 -7
- package/dist/schema-builders/object-id.js.map +0 -1
- package/dist/schema-builders/ref.d.ts +0 -44
- package/dist/schema-builders/ref.d.ts.map +0 -1
- package/dist/schema-builders/ref.js +0 -10
- package/dist/schema-builders/ref.js.map +0 -1
- package/dist/schema-builders/string.d.ts +0 -138
- package/dist/schema-builders/string.d.ts.map +0 -1
- package/dist/schema-builders/string.js +0 -48
- package/dist/schema-builders/string.js.map +0 -1
- package/dist/schema-builders/uuid.d.ts +0 -33
- package/dist/schema-builders/uuid.d.ts.map +0 -1
- package/dist/schema-builders/uuid.js +0 -7
- package/dist/schema-builders/uuid.js.map +0 -1
- package/dist/types/_internals.d.ts +0 -24
- package/dist/types/_internals.d.ts.map +0 -1
- package/dist/types/_internals.js +0 -1
- package/dist/types/aggregate-paginate.d.ts +0 -82
- package/dist/types/aggregate-paginate.d.ts.map +0 -1
- package/dist/types/aggregate-paginate.js +0 -1
- package/dist/types/options.d.ts +0 -23
- package/dist/types/options.d.ts.map +0 -1
- package/dist/types/options.js +0 -1
- package/src/schema-builders/_internals.ts +0 -64
- package/src/schema-builders/base.ts +0 -57
- package/src/schema-builders/bigint.ts +0 -156
- package/src/schema-builders/boolean.ts +0 -45
- package/src/schema-builders/date.ts +0 -80
- package/src/schema-builders/decimal128.ts +0 -196
- package/src/schema-builders/double.ts +0 -166
- package/src/schema-builders/int32.ts +0 -157
- package/src/schema-builders/mixed.ts +0 -37
- package/src/schema-builders/number.ts +0 -80
- package/src/schema-builders/object-id.ts +0 -60
- package/src/schema-builders/ref.ts +0 -67
- package/src/schema-builders/string.ts +0 -258
- package/src/schema-builders/uuid.ts +0 -48
- package/src/types/_internals.ts +0 -27
- package/src/types/aggregate-paginate.ts +0 -115
- package/src/types/options.ts +0 -46
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
|
+
ClientSession,
|
|
3
|
+
Model,
|
|
2
4
|
mongo,
|
|
3
5
|
MongooseUpdateQueryOptions,
|
|
4
6
|
QueryFilter,
|
|
@@ -9,73 +11,139 @@ import type {
|
|
|
9
11
|
} from 'mongoose';
|
|
10
12
|
|
|
11
13
|
import { assertMongooseUpdateSuccess } from '../assertions';
|
|
14
|
+
import { MongooseUpdateConflictError } from '../errors/mongoose-update-conflict-error';
|
|
12
15
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
16
|
+
type UpdateIfUnmodified<RawDocType, Result> = (
|
|
17
|
+
updatedAt: Date | number | string,
|
|
18
|
+
update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
|
|
19
|
+
options?: UpdateIfUnmodifiedOptions,
|
|
20
|
+
) => Promise<Result>;
|
|
21
|
+
|
|
22
|
+
export interface MongooseAssertionsDocumentMethods<RawDocType> {
|
|
23
|
+
/**
|
|
24
|
+
* @throws {MongooseUpdateConflictError} If the document was changed or deleted after `updatedAt`.
|
|
25
|
+
*/
|
|
26
|
+
assertUpdateIfUnmodified: UpdateIfUnmodified<RawDocType, void>;
|
|
27
|
+
assertUpdateSuccess: (
|
|
28
|
+
update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
|
|
29
|
+
options?: null | QueryOptions,
|
|
30
|
+
) => Promise<void>;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Updates the document only if its `updatedAt` timestamp still equals `updatedAt`, in one atomic `updateOne`, and
|
|
34
|
+
* returns whether it did. Every update through Mongoose sets a new `updatedAt`, so any change in between, or a
|
|
35
|
+
* deletion, makes it return `false`; timestamps have millisecond precision, so two writes within the same
|
|
36
|
+
* millisecond are not told apart. Uses `options.session` if given, otherwise the document's session.
|
|
37
|
+
*
|
|
38
|
+
* @throws {Error} If the schema has no `updatedAt` timestamp or the document has no `_id`.
|
|
39
|
+
*/
|
|
40
|
+
updateIfUnmodified: UpdateIfUnmodified<RawDocType, boolean>;
|
|
41
|
+
}
|
|
30
42
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
43
|
+
export interface MongooseAssertionsModelStatics<RawDocType> {
|
|
44
|
+
assertUpdateManySuccess: (
|
|
45
|
+
filter: QueryFilter<RawDocType>,
|
|
46
|
+
update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
|
|
47
|
+
options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null,
|
|
48
|
+
minModifiedCount?: number,
|
|
49
|
+
) => Promise<void>;
|
|
50
|
+
|
|
51
|
+
assertUpdateOneSuccess: (
|
|
52
|
+
filter: QueryFilter<RawDocType>,
|
|
53
|
+
update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
|
|
54
|
+
options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null,
|
|
55
|
+
) => Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Only the session is configurable: other update options such as `upsert` or `timestamps` would break the guarantee
|
|
60
|
+
* that a successful update writes a new `updatedAt`.
|
|
61
|
+
*/
|
|
62
|
+
export interface UpdateIfUnmodifiedOptions {
|
|
63
|
+
session?: ClientSession | null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface UpdateIfUnmodifiedThis {
|
|
67
|
+
$session: () => ClientSession | null;
|
|
68
|
+
_id: unknown;
|
|
69
|
+
constructor: Model<any>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function getUpdatedAtPath(schema: Schema) {
|
|
73
|
+
const timestamps = schema.get('timestamps');
|
|
74
|
+
let path: unknown;
|
|
75
|
+
if (timestamps === true) path = 'updatedAt';
|
|
76
|
+
else if (timestamps && typeof timestamps === 'object') {
|
|
77
|
+
path = timestamps.updatedAt === true || !('updatedAt' in timestamps) ? 'updatedAt' : timestamps.updatedAt;
|
|
50
78
|
}
|
|
79
|
+
|
|
80
|
+
// Mongoose skips timestamp paths it cannot name, e.g. `{ updatedAt: '' }`, so require the path to exist.
|
|
81
|
+
if (typeof path === 'string' && schema.path(path)) return path;
|
|
82
|
+
throw new Error('updateIfUnmodified requires the schema to have an updatedAt timestamp');
|
|
51
83
|
}
|
|
52
84
|
|
|
53
|
-
export function mongooseAssertionsPlugin
|
|
85
|
+
export function mongooseAssertionsPlugin(schema: Schema) {
|
|
86
|
+
schema.method('updateIfUnmodified', updateIfUnmodified);
|
|
87
|
+
schema.method(
|
|
88
|
+
'assertUpdateIfUnmodified',
|
|
89
|
+
async function (this: UpdateIfUnmodifiedThis, ...args: Parameters<UpdateIfUnmodified<any, void>>) {
|
|
90
|
+
if (await updateIfUnmodified.apply(this, args)) return;
|
|
91
|
+
throw new MongooseUpdateConflictError('Document was modified or deleted');
|
|
92
|
+
},
|
|
93
|
+
);
|
|
94
|
+
|
|
54
95
|
schema.method(
|
|
55
96
|
'assertUpdateSuccess',
|
|
97
|
+
async function (update?: UpdateQuery<any> | UpdateWithAggregationPipeline, options?: null | QueryOptions) {
|
|
98
|
+
return await assertMongooseUpdateSuccess(this.updateOne(update, options));
|
|
99
|
+
},
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
schema.static(
|
|
103
|
+
'assertUpdateManySuccess',
|
|
56
104
|
async function (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
105
|
+
filter: QueryFilter<any>,
|
|
106
|
+
update: UpdateQuery<any> | UpdateWithAggregationPipeline,
|
|
107
|
+
options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,
|
|
108
|
+
minModifiedCount?: number,
|
|
60
109
|
) {
|
|
61
|
-
return await assertMongooseUpdateSuccess(this.
|
|
110
|
+
return await assertMongooseUpdateSuccess(this.updateMany(filter, update, options), minModifiedCount);
|
|
62
111
|
},
|
|
63
112
|
);
|
|
64
113
|
|
|
65
114
|
schema.static(
|
|
66
|
-
'
|
|
115
|
+
'assertUpdateOneSuccess',
|
|
67
116
|
async function (
|
|
68
117
|
filter: QueryFilter<any>,
|
|
69
118
|
update: UpdateQuery<any> | UpdateWithAggregationPipeline,
|
|
70
119
|
options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,
|
|
71
|
-
expectedModifiedCount: number = 1,
|
|
72
120
|
) {
|
|
73
|
-
return await assertMongooseUpdateSuccess(
|
|
74
|
-
expectedModifiedCount === 1
|
|
75
|
-
? this.updateOne(filter, update, options)
|
|
76
|
-
: this.updateMany(filter, update, options),
|
|
77
|
-
expectedModifiedCount,
|
|
78
|
-
);
|
|
121
|
+
return await assertMongooseUpdateSuccess(this.updateOne(filter, update, options));
|
|
79
122
|
},
|
|
80
123
|
);
|
|
81
124
|
}
|
|
125
|
+
|
|
126
|
+
async function updateIfUnmodified(
|
|
127
|
+
this: UpdateIfUnmodifiedThis,
|
|
128
|
+
updatedAt: Date | number | string,
|
|
129
|
+
update: UpdateQuery<any> | UpdateWithAggregationPipeline,
|
|
130
|
+
options?: UpdateIfUnmodifiedOptions,
|
|
131
|
+
) {
|
|
132
|
+
// With `ignoreUndefined`, an undefined `_id` would be dropped from the filter and match another document.
|
|
133
|
+
if (this._id === null || this._id === undefined) throw new Error('updateIfUnmodified requires the document _id');
|
|
134
|
+
const session = options && 'session' in options ? options.session : this.$session() ?? undefined;
|
|
135
|
+
const model = this.constructor;
|
|
136
|
+
const result = await model.updateOne(
|
|
137
|
+
{
|
|
138
|
+
_id: this._id,
|
|
139
|
+
[getUpdatedAtPath(model.schema)]: updatedAt,
|
|
140
|
+
},
|
|
141
|
+
update,
|
|
142
|
+
// Without a session the key is omitted, so `transactionAsyncLocalStorage` can still supply one. An explicit
|
|
143
|
+
// `null` opts out of any session, as Mongoose's own options do, although its types only allow `undefined`.
|
|
144
|
+
session === undefined ? undefined : { session: session as ClientSession },
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
if (!result.acknowledged) throw new Error('Update was not acknowledged');
|
|
148
|
+
return result.matchedCount === 1;
|
|
149
|
+
}
|
|
@@ -10,58 +10,55 @@ import {
|
|
|
10
10
|
objectValues,
|
|
11
11
|
} from 'ts-extras';
|
|
12
12
|
|
|
13
|
+
import { decimal128ToPlainString } from '../_internals';
|
|
14
|
+
|
|
13
15
|
declare module 'mongoose' {
|
|
14
16
|
interface LeanOptions {
|
|
15
|
-
/**
|
|
16
|
-
* Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting.
|
|
17
|
-
*/
|
|
18
17
|
decimal128ToString?: boolean;
|
|
19
18
|
}
|
|
20
19
|
}
|
|
21
20
|
|
|
22
|
-
type QueryWithOptionalMap = Query<unknown, unknown> & { map?: (transform: (result: unknown) => unknown) => unknown };
|
|
23
|
-
|
|
24
21
|
export interface MongooseLeanDecimal128ToStringPluginOptions {
|
|
25
|
-
/**
|
|
26
|
-
* Whether marked fields are converted on lean queries by default. Defaults to true.
|
|
27
|
-
*/
|
|
28
22
|
enabledByDefault?: boolean;
|
|
29
23
|
}
|
|
30
24
|
|
|
31
|
-
|
|
25
|
+
const conversionPathsCache = new WeakMap<Schema, Array<[pathSegments: string[], schemaType: SchemaType]>>();
|
|
32
26
|
const registeredSchemas = new WeakSet<Schema>();
|
|
33
27
|
|
|
34
|
-
// Functions
|
|
35
28
|
const isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';
|
|
36
29
|
|
|
30
|
+
function canContainMarkedDecimal128(schemaType: SchemaType): boolean {
|
|
31
|
+
// Subdocument schemas are filtered by their own cached paths when converted.
|
|
32
|
+
if (schemaType.schema) return true;
|
|
33
|
+
if (schemaType.instance === 'Decimal128') return schemaType.options.leanDecimal128ToString === true;
|
|
34
|
+
const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
|
|
35
|
+
return !!embeddedSchemaType && canContainMarkedDecimal128(embeddedSchemaType);
|
|
36
|
+
}
|
|
37
|
+
|
|
37
38
|
function convertDocument(schema: Schema, value: unknown) {
|
|
38
39
|
if (!isNonNullObject(value)) return;
|
|
39
40
|
const discriminatorKey = schema.get('discriminatorKey') ?? '__t';
|
|
40
|
-
const discriminatorSchema = objectValues(schema.discriminators
|
|
41
|
+
const discriminatorSchema = schema.discriminators && objectValues(schema.discriminators).find(
|
|
41
42
|
(childSchema) => childSchema.get('discriminatorKey') === discriminatorKey
|
|
42
43
|
&& (childSchema as Schema & { discriminatorMapping?: { value: unknown } }).discriminatorMapping?.value
|
|
43
44
|
=== value[discriminatorKey],
|
|
44
45
|
);
|
|
45
46
|
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const pathSegments = path.split('.');
|
|
50
|
-
if (pathSegments.includes('$*')) return;
|
|
51
|
-
convertPath(value, pathSegments, schemaType);
|
|
52
|
-
});
|
|
47
|
+
for (const [pathSegments, schemaType] of getConversionPaths(discriminatorSchema ?? schema)) {
|
|
48
|
+
convertPath(value, pathSegments, 0, schemaType);
|
|
49
|
+
}
|
|
53
50
|
}
|
|
54
51
|
|
|
55
|
-
function convertPath(value: unknown, pathSegments: string[], schemaType: SchemaType) {
|
|
52
|
+
function convertPath(value: unknown, pathSegments: string[], index: number, schemaType: SchemaType) {
|
|
56
53
|
if (Array.isArray(value)) {
|
|
57
|
-
value.forEach((item) => convertPath(item, pathSegments, schemaType));
|
|
54
|
+
value.forEach((item) => convertPath(item, pathSegments, index, schemaType));
|
|
58
55
|
return;
|
|
59
56
|
}
|
|
60
57
|
|
|
61
58
|
if (!isNonNullObject(value)) return;
|
|
62
|
-
const
|
|
59
|
+
const key = pathSegments[index];
|
|
63
60
|
if (key === undefined || !objectHasOwn(value, key)) return;
|
|
64
|
-
if (
|
|
61
|
+
if (index < pathSegments.length - 1) convertPath(value[key], pathSegments, index + 1, schemaType);
|
|
65
62
|
else value[key] = convertValue(value[key], schemaType);
|
|
66
63
|
}
|
|
67
64
|
|
|
@@ -95,22 +92,34 @@ function convertValue(value: unknown, schemaType: SchemaType): unknown {
|
|
|
95
92
|
&& schemaType.options.leanDecimal128ToString === true
|
|
96
93
|
&& isNonNullObject(value)
|
|
97
94
|
&& value._bsontype === 'Decimal128'
|
|
98
|
-
|
|
99
|
-
) return (value as Types.Decimal128).toString();
|
|
95
|
+
) return decimal128ToPlainString(value as Types.Decimal128);
|
|
100
96
|
|
|
101
97
|
return value;
|
|
102
98
|
}
|
|
103
99
|
|
|
100
|
+
function getConversionPaths(schema: Schema) {
|
|
101
|
+
let conversionPaths = conversionPathsCache.get(schema);
|
|
102
|
+
if (conversionPaths) return conversionPaths;
|
|
103
|
+
conversionPaths = [];
|
|
104
|
+
schema.eachPath((path, schemaType) => {
|
|
105
|
+
// Maps are handled through their embedded schema type, not their synthetic $* path.
|
|
106
|
+
const pathSegments = path.split('.');
|
|
107
|
+
if (!pathSegments.includes('$*') && canContainMarkedDecimal128(schemaType)) {
|
|
108
|
+
conversionPaths.push([
|
|
109
|
+
pathSegments,
|
|
110
|
+
schemaType,
|
|
111
|
+
]);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
conversionPathsCache.set(schema, conversionPaths);
|
|
116
|
+
return conversionPaths;
|
|
117
|
+
}
|
|
118
|
+
|
|
104
119
|
/**
|
|
105
|
-
* Converts marked
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
* `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
|
|
109
|
-
* Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
|
|
110
|
-
* Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
|
|
111
|
-
* Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
|
|
112
|
-
* Registration is idempotent; the first registration's default options take precedence.
|
|
113
|
-
* Runtime conversion does not override Mongoose's inferred lean result types.
|
|
120
|
+
* Converts paths marked by `s.decimal128().setToStringGetter()` on lean queries, except with
|
|
121
|
+
* `lean({ decimal128ToString: false })` and in aggregate results.
|
|
122
|
+
* Convertible paths are collected per schema on its first converted query; paths added later are ignored.
|
|
114
123
|
*/
|
|
115
124
|
export function mongooseLeanDecimal128ToStringPlugin(
|
|
116
125
|
schema: Schema,
|
|
@@ -119,7 +128,7 @@ export function mongooseLeanDecimal128ToStringPlugin(
|
|
|
119
128
|
if (registeredSchemas.has(schema)) return;
|
|
120
129
|
registeredSchemas.add(schema);
|
|
121
130
|
|
|
122
|
-
function convertResult(query:
|
|
131
|
+
function convertResult(query: Query<unknown, unknown>, result: unknown) {
|
|
123
132
|
const leanOptions = query.mongooseOptions().lean;
|
|
124
133
|
if (!leanOptions) return result;
|
|
125
134
|
const conversionEnabled = typeof leanOptions === 'object'
|
|
@@ -135,14 +144,11 @@ export function mongooseLeanDecimal128ToStringPlugin(
|
|
|
135
144
|
return result;
|
|
136
145
|
}
|
|
137
146
|
|
|
138
|
-
//
|
|
147
|
+
// `Query#transform` also applies to cursors, which do not run post('find') hooks.
|
|
139
148
|
schema.pre(
|
|
140
149
|
'find',
|
|
141
|
-
function (this:
|
|
142
|
-
|
|
143
|
-
if (typeof this.map === 'function') this.map(transform);
|
|
144
|
-
else if (typeof this.transform === 'function') this.transform(transform);
|
|
145
|
-
else this.setOptions({ transform });
|
|
150
|
+
function (this: Query<unknown, unknown>) {
|
|
151
|
+
this.transform((result) => convertResult(this, result));
|
|
146
152
|
},
|
|
147
153
|
);
|
|
148
154
|
|
|
@@ -153,7 +159,7 @@ export function mongooseLeanDecimal128ToStringPlugin(
|
|
|
153
159
|
'findOneAndDelete',
|
|
154
160
|
'findOneAndReplace',
|
|
155
161
|
],
|
|
156
|
-
function (this:
|
|
162
|
+
function (this: Query<unknown, unknown>, result: unknown) {
|
|
157
163
|
convertResult(this, result);
|
|
158
164
|
},
|
|
159
165
|
);
|
package/src/plugins/normalize.ts
CHANGED
|
@@ -3,123 +3,193 @@ import {
|
|
|
3
3
|
set as setProp,
|
|
4
4
|
unset as unsetProp,
|
|
5
5
|
} from 'es-toolkit/compat';
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
* @remarks
|
|
30
|
-
* Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.
|
|
31
|
-
*
|
|
32
|
-
* @defaultValue `true`.
|
|
33
|
-
*/
|
|
34
|
-
toHexIdIfObjectId?: boolean;
|
|
6
|
+
import {
|
|
7
|
+
Model,
|
|
8
|
+
Schema,
|
|
9
|
+
Types,
|
|
10
|
+
} from 'mongoose';
|
|
11
|
+
import type {
|
|
12
|
+
Document,
|
|
13
|
+
SchemaType,
|
|
14
|
+
} from 'mongoose';
|
|
15
|
+
import {
|
|
16
|
+
objectEntries,
|
|
17
|
+
objectFromEntries,
|
|
18
|
+
objectValues,
|
|
19
|
+
} from 'ts-extras';
|
|
20
|
+
|
|
21
|
+
import { decimal128ToPlainString } from '../_internals';
|
|
22
|
+
|
|
23
|
+
type DiscriminatorFunction = (name: unknown, schema: unknown, ...args: unknown[]) => unknown;
|
|
24
|
+
type DiscriminatorMap = Record<string, { schema: Schema }>;
|
|
25
|
+
|
|
26
|
+
interface NormalizedPaths {
|
|
27
|
+
decimal128Paths: Array<[path: string, schemaType: SchemaType]>;
|
|
28
|
+
privatePaths: string[];
|
|
35
29
|
}
|
|
36
30
|
|
|
37
|
-
|
|
31
|
+
const normalizedPathsCache = new WeakMap<Schema, NormalizedPaths>();
|
|
32
|
+
const normalizeTransforms = new WeakSet<object>();
|
|
38
33
|
const registeredSchemas = new WeakSet<Schema>();
|
|
39
34
|
|
|
40
|
-
|
|
35
|
+
const isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';
|
|
41
36
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
)
|
|
63
|
-
if (
|
|
64
|
-
|
|
37
|
+
function containsDecimal128(schemaType: SchemaType): boolean {
|
|
38
|
+
if (schemaType.instance === 'Decimal128') return true;
|
|
39
|
+
const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
|
|
40
|
+
// Subdocuments are normalized by their own schema's transform.
|
|
41
|
+
return !!embeddedSchemaType && !embeddedSchemaType.schema && containsDecimal128(embeddedSchemaType);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function decimal128ToString(value: unknown, schemaType: SchemaType): unknown {
|
|
45
|
+
if (schemaType.instance === 'Decimal128') {
|
|
46
|
+
// `flattenDecimals` serializes to `{ $numberDecimal }`; getters may return plain values.
|
|
47
|
+
if (isNonNullObject(value)) {
|
|
48
|
+
if (value._bsontype === 'Decimal128') return decimal128ToPlainString(value as Types.Decimal128);
|
|
49
|
+
return typeof value.$numberDecimal === 'string' ? decimal128ToPlainString(value.$numberDecimal) : value;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return typeof value === 'bigint' || typeof value === 'number' ? String(value) : value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
|
|
56
|
+
if (!embeddedSchemaType) return value;
|
|
57
|
+
if (Array.isArray(value)) return value.map((item) => decimal128ToString(item, embeddedSchemaType));
|
|
58
|
+
if (schemaType.instance !== 'Map') return value;
|
|
59
|
+
if (value instanceof Map) {
|
|
60
|
+
return new Map(Array.from(
|
|
61
|
+
value,
|
|
62
|
+
([key, item]) => [
|
|
63
|
+
key,
|
|
64
|
+
decimal128ToString(item, embeddedSchemaType),
|
|
65
|
+
],
|
|
66
|
+
));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (isNonNullObject(value)) {
|
|
70
|
+
return objectFromEntries(
|
|
71
|
+
objectEntries(value).map(([key, item]) => [
|
|
72
|
+
key,
|
|
73
|
+
decimal128ToString(item, embeddedSchemaType),
|
|
74
|
+
]),
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function getNormalizedPaths(schema: Schema) {
|
|
82
|
+
let normalizedPaths = normalizedPathsCache.get(schema);
|
|
83
|
+
if (normalizedPaths) return normalizedPaths;
|
|
84
|
+
normalizedPaths = {
|
|
85
|
+
decimal128Paths: [],
|
|
86
|
+
privatePaths: [],
|
|
87
|
+
};
|
|
65
88
|
|
|
66
|
-
// Collect special paths (Decimal128 & private)
|
|
67
|
-
const decimalPaths: string[] = [];
|
|
68
|
-
const privatePaths: string[] = [];
|
|
69
89
|
for (const [path, schemaType] of objectEntries(schema.paths)) {
|
|
70
|
-
|
|
71
|
-
|
|
90
|
+
// Map values are handled through the map path's embedded schema type, not the synthetic `$*` path.
|
|
91
|
+
if (path.split('.').includes('$*')) continue;
|
|
92
|
+
if (schemaType.options?.private) normalizedPaths.privatePaths.push(path);
|
|
93
|
+
else if (containsDecimal128(schemaType)) {
|
|
94
|
+
normalizedPaths.decimal128Paths.push([
|
|
95
|
+
path,
|
|
96
|
+
schemaType,
|
|
97
|
+
]);
|
|
98
|
+
}
|
|
72
99
|
}
|
|
73
100
|
|
|
74
|
-
|
|
101
|
+
normalizedPathsCache.set(schema, normalizedPaths);
|
|
102
|
+
return normalizedPaths;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Child and discriminator schemas are registered too, so register after the schema's paths are defined.
|
|
107
|
+
* `toJSON` options cannot be changed afterwards.
|
|
108
|
+
*/
|
|
109
|
+
export function mongooseNormalizePlugin(schema: Schema) {
|
|
110
|
+
if (registeredSchemas.has(schema)) return;
|
|
111
|
+
registeredSchemas.add(schema);
|
|
75
112
|
const toJson = schema.get('toJSON');
|
|
76
113
|
const toJsonTransform = toJson?.transform;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
'
|
|
81
|
-
{
|
|
114
|
+
// Discriminator schemas may inherit the base transform, which already uses each document's own schema.
|
|
115
|
+
if (typeof toJsonTransform !== 'function' || !normalizeTransforms.has(toJsonTransform)) {
|
|
116
|
+
// Not `Schema#set`: it copies the options minus the transform onto implicitly created child schemas, which may
|
|
117
|
+
// already be registered and shared with a discriminator's base schema.
|
|
118
|
+
schema.options.toJSON = {
|
|
82
119
|
...toJson,
|
|
83
120
|
transform(doc, ret, options) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
let _id = copiedRet._id;
|
|
91
|
-
delete copiedRet._id;
|
|
92
|
-
if (pluginOptions?.toHexIdIfObjectId !== false && _id instanceof Types.ObjectId) {
|
|
93
|
-
_id = _id.toHexString();
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
if (_id !== undefined) {
|
|
97
|
-
if (pluginOptions?.convertIdField !== false) copiedRet.id = _id;
|
|
98
|
-
else copiedRet._id = _id;
|
|
99
|
-
}
|
|
121
|
+
normalize(doc, ret);
|
|
122
|
+
if (typeof toJsonTransform !== 'function') return ret;
|
|
123
|
+
const transformed = toJsonTransform(doc, ret, options);
|
|
124
|
+
return transformed === undefined ? ret : transformed;
|
|
125
|
+
},
|
|
126
|
+
};
|
|
100
127
|
|
|
101
|
-
|
|
102
|
-
|
|
128
|
+
const transform = schema.options.toJSON.transform;
|
|
129
|
+
if (typeof transform === 'function') normalizeTransforms.add(transform);
|
|
130
|
+
}
|
|
103
131
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
132
|
+
const childSchemas = new Set<Schema>(schema.childSchemas.map(({ schema: child }) => child));
|
|
133
|
+
objectValues(schema.discriminators ?? {}).forEach((child) => childSchemas.add(child));
|
|
134
|
+
for (const pathSchemaType of objectValues(schema.paths)) {
|
|
135
|
+
// `childSchemas` omits subdocuments nested in arrays of arrays or maps of arrays.
|
|
136
|
+
let schemaType: SchemaType | undefined = pathSchemaType;
|
|
137
|
+
while (schemaType) {
|
|
138
|
+
const embedded = schemaType as SchemaType & {
|
|
139
|
+
Constructor?: { discriminators?: DiscriminatorMap };
|
|
140
|
+
discriminator?: DiscriminatorFunction;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
if (embedded.schema) {
|
|
144
|
+
childSchemas.add(embedded.schema);
|
|
145
|
+
if (typeof embedded.discriminator === 'function') {
|
|
146
|
+
embedded.discriminator = registerAfterDiscriminator(embedded.discriminator);
|
|
108
147
|
}
|
|
148
|
+
}
|
|
109
149
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
150
|
+
// Embedded discriminators live on the path's constructor; `schema.discriminators` is keyed by name only,
|
|
151
|
+
// so paths sharing a schema overwrite each other there.
|
|
152
|
+
objectValues(embedded.Constructor?.discriminators ?? {}).forEach((child) => childSchemas.add(child.schema));
|
|
153
|
+
schemaType = schemaType.getEmbeddedSchemaType();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
115
156
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
)
|
|
157
|
+
childSchemas.forEach((child) => child.plugin(mongooseNormalizePlugin));
|
|
158
|
+
schema.static('discriminator', registerAfterDiscriminator(Model.discriminator));
|
|
159
|
+
// `Schema#set` replaces the whole `toJSON` object, which would drop the normalize transform.
|
|
160
|
+
const set = schema.set;
|
|
161
|
+
schema.set = function (this: Schema, ...args: Parameters<Schema['set']>) {
|
|
162
|
+
if (args[0] === 'toJSON' && args.length > 1) {
|
|
163
|
+
throw new Error('toJSON options cannot be changed after mongooseNormalizePlugin is registered.');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return set.apply(this, args);
|
|
167
|
+
} as Schema['set'];
|
|
168
|
+
}
|
|
121
169
|
|
|
122
|
-
|
|
123
|
-
|
|
170
|
+
function normalize(doc: Document<unknown>, ret: Record<string, any>) {
|
|
171
|
+
// A data field named `schema` shadows `Document#schema`; the constructor holds the schema Mongoose serializes with.
|
|
172
|
+
const schema = (doc.constructor as { schema?: Schema }).schema ?? doc.schema;
|
|
173
|
+
const { decimal128Paths, privatePaths } = getNormalizedPaths(schema);
|
|
174
|
+
const versionKey = schema.get('versionKey');
|
|
175
|
+
if (typeof versionKey === 'string') unsetProp(ret, versionKey);
|
|
176
|
+
const _id = ret._id;
|
|
177
|
+
delete ret._id;
|
|
178
|
+
if (_id !== undefined) ret.id = _id instanceof Types.ObjectId ? _id.toHexString() : _id;
|
|
179
|
+
for (const path of privatePaths) unsetProp(ret, path);
|
|
180
|
+
for (const [path, schemaType] of decimal128Paths) {
|
|
181
|
+
const value = getProp(ret, path);
|
|
182
|
+
if (value !== undefined) setProp(ret, path, decimal128ToString(value, schemaType));
|
|
124
183
|
}
|
|
125
184
|
}
|
|
185
|
+
|
|
186
|
+
// Mongoose clones and merges the discriminator schema, so register on the schema it actually uses. Registering before
|
|
187
|
+
// the merge would give a schema without its own `toJSON` one, which replaces the inherited options.
|
|
188
|
+
function registerAfterDiscriminator<T extends (...args: any[]) => any>(discriminator: T) {
|
|
189
|
+
return function (this: unknown, ...args: Parameters<T>): ReturnType<T> {
|
|
190
|
+
const result = discriminator.apply(this, args);
|
|
191
|
+
const { schema } = result as { schema?: unknown };
|
|
192
|
+
if (schema instanceof Schema) schema.plugin(mongooseNormalizePlugin);
|
|
193
|
+
return result;
|
|
194
|
+
};
|
|
195
|
+
}
|