@kikiutils/mongoose 9.0.4 → 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 +10 -10
- 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 +8 -2
- 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 +16 -12
- 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 +19 -21
- 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
package/README.md
CHANGED
|
@@ -1,45 +1,30 @@
|
|
|
1
|
-
<!-- TODO: Update -->
|
|
2
|
-
|
|
3
1
|
# @kikiutils/mongoose
|
|
4
2
|
|
|
5
3
|
[![npm version][npm-version-src]][npm-version-href]
|
|
6
4
|
[![npm downloads][npm-downloads-src]][npm-downloads-href]
|
|
5
|
+
[![Node.js][node-src]][node-href]
|
|
7
6
|
[![codecov][codecov-src]][codecov-href]
|
|
8
7
|
[![License][license-src]][license-href]
|
|
9
8
|
|
|
10
|
-
|
|
9
|
+
Typed Mongoose schema builders and a `buildMongooseModel` that applies pagination, JSON normalization, lean Decimal128-to-string conversion and update assertions, plus connection, transaction and duplicate-key helpers. ESM only.
|
|
11
10
|
|
|
12
11
|
- [✨ Release Notes](./CHANGELOG.md)
|
|
13
12
|
|
|
14
|
-
## Features
|
|
15
|
-
|
|
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
|
-
|
|
24
|
-
## Requirements
|
|
25
|
-
|
|
26
|
-
- **Mongoose** `>=9`
|
|
27
|
-
- **Node.js** `>=22.12.0`
|
|
28
|
-
|
|
29
13
|
## Installation
|
|
30
14
|
|
|
31
|
-
Using [pnpm](https://pnpm.io):
|
|
32
|
-
|
|
33
15
|
```bash
|
|
34
|
-
pnpm add @kikiutils/mongoose
|
|
16
|
+
pnpm add @kikiutils/mongoose
|
|
35
17
|
```
|
|
36
18
|
|
|
37
|
-
|
|
19
|
+
## Configuration
|
|
20
|
+
|
|
21
|
+
Models built without an explicit `connection` share a default connection, created on first use from the `MONGODB_URI` environment variable. Its options must be set before that:
|
|
38
22
|
|
|
39
|
-
|
|
23
|
+
```typescript
|
|
24
|
+
import { setCustomMongooseOptions } from '@kikiutils/mongoose/options';
|
|
40
25
|
|
|
41
|
-
|
|
42
|
-
|
|
26
|
+
setCustomMongooseOptions('defaultConnectionOptions', { maxPoolSize: 10 });
|
|
27
|
+
```
|
|
43
28
|
|
|
44
29
|
## License
|
|
45
30
|
|
|
@@ -52,6 +37,9 @@ To be completed.
|
|
|
52
37
|
[npm-downloads-href]: https://npmjs.com/package/@kikiutils/mongoose
|
|
53
38
|
[npm-downloads-src]: https://img.shields.io/npm/dm/@kikiutils/mongoose.svg?colorA=18181b&colorB=28cf8d&style=flat
|
|
54
39
|
|
|
40
|
+
[node-href]: ./package.json
|
|
41
|
+
[node-src]: https://img.shields.io/node/v/@kikiutils/mongoose?colorA=18181b&colorB=28cf8d&style=flat
|
|
42
|
+
|
|
55
43
|
[codecov-href]: https://codecov.io/gh/kikiutils/node-mongoose
|
|
56
44
|
[codecov-src]: https://codecov.io/gh/kikiutils/node-mongoose/graph/badge.svg?token=DM89MM6FPK
|
|
57
45
|
|
package/dist/_internals.d.ts
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
|
-
import { CustomMongooseOptions } from "./types/options.js";
|
|
2
1
|
import { Connection } from "mongoose";
|
|
2
|
+
import { BeforeMongooseModelBuildHook, CustomMongooseOptions } from "./options.js";
|
|
3
|
+
export declare const beforeModelBuildHooks: BeforeMongooseModelBuildHook[];
|
|
3
4
|
export declare const customMongooseOptions: CustomMongooseOptions;
|
|
4
5
|
export declare const mongooseConnectionState: {
|
|
5
6
|
defaultConnection?: Connection;
|
|
6
7
|
};
|
|
8
|
+
/**
|
|
9
|
+
* `Decimal128#toString()` switches to exponent notation (`1E-8`, `0E-8`) when the adjusted exponent is below -6, as the
|
|
10
|
+
* BSON Decimal128 spec requires. This moves the decimal point instead, keeping the sign and the number of decimal
|
|
11
|
+
* places, and returns every other value unchanged so trailing zeros such as `12.30` are kept.
|
|
12
|
+
*/
|
|
13
|
+
export declare function decimal128ToPlainString(value: {
|
|
14
|
+
toString: () => string;
|
|
15
|
+
}): string;
|
|
7
16
|
//# 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":";;qBAOa,uBAAuB;qBACvB,uBAAuB;qBACvB;EAA2B,oBAAoB;;;;;;;wBAS5C,wBAAwB;EAAS"}
|
package/dist/_internals.js
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
// src/_internals.ts
|
|
2
|
+
const beforeModelBuildHooks = [];
|
|
2
3
|
const customMongooseOptions = {};
|
|
3
4
|
const mongooseConnectionState = {};
|
|
4
|
-
|
|
5
|
+
const exponentNotationPattern = /^([-+]?)(\d+)(?:\.(\d+))?e([-+]\d+)$/i;
|
|
6
|
+
/**
|
|
7
|
+
* `Decimal128#toString()` switches to exponent notation (`1E-8`, `0E-8`) when the adjusted exponent is below -6, as the
|
|
8
|
+
* BSON Decimal128 spec requires. This moves the decimal point instead, keeping the sign and the number of decimal
|
|
9
|
+
* places, and returns every other value unchanged so trailing zeros such as `12.30` are kept.
|
|
10
|
+
*/
|
|
11
|
+
function decimal128ToPlainString(value) {
|
|
12
|
+
const text = value.toString();
|
|
13
|
+
const match = exponentNotationPattern.exec(text);
|
|
14
|
+
if (!match) return text;
|
|
15
|
+
const [, sign = "", integerDigits = "", fractionDigits = "", exponent = "0"] = match;
|
|
16
|
+
const digits = integerDigits + fractionDigits;
|
|
17
|
+
const pointIndex = integerDigits.length + Number(exponent);
|
|
18
|
+
if (pointIndex <= 0) return `${sign}0.${"0".repeat(-pointIndex)}${digits}`;
|
|
19
|
+
const integerPart = digits.padEnd(pointIndex, "0").slice(0, pointIndex).replace(/^0+(?=\d)/, "");
|
|
20
|
+
const fractionPart = digits.slice(pointIndex);
|
|
21
|
+
return `${sign}${integerPart}${fractionPart ? `.${fractionPart}` : ""}`;
|
|
22
|
+
}
|
|
23
|
+
export { beforeModelBuildHooks, customMongooseOptions, decimal128ToPlainString, mongooseConnectionState };
|
|
5
24
|
|
|
6
25
|
//# sourceMappingURL=_internals.js.map
|
package/dist/_internals.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_internals.js","names":[],"sources":["../src/_internals.ts"],"sourcesContent":["import type { Connection } from 'mongoose';\n\nimport type {
|
|
1
|
+
{"version":3,"file":"_internals.js","names":[],"sources":["../src/_internals.ts"],"sourcesContent":["import type { Connection } from 'mongoose';\n\nimport type {\n BeforeMongooseModelBuildHook,\n CustomMongooseOptions,\n} from './options';\n\nexport const beforeModelBuildHooks: BeforeMongooseModelBuildHook[] = [];\nexport const customMongooseOptions: CustomMongooseOptions = {};\nexport const mongooseConnectionState: { defaultConnection?: Connection } = {};\n\nconst exponentNotationPattern = /^([-+]?)(\\d+)(?:\\.(\\d+))?e([-+]\\d+)$/i;\n\n/**\n * `Decimal128#toString()` switches to exponent notation (`1E-8`, `0E-8`) when the adjusted exponent is below -6, as the\n * BSON Decimal128 spec requires. This moves the decimal point instead, keeping the sign and the number of decimal\n * places, and returns every other value unchanged so trailing zeros such as `12.30` are kept.\n */\nexport function decimal128ToPlainString(value: { toString: () => string }) {\n const text = value.toString();\n const match = exponentNotationPattern.exec(text);\n if (!match) return text;\n const [\n , sign = '',\n integerDigits = '',\n fractionDigits = '',\n exponent = '0',\n ] = match;\n\n const digits = integerDigits + fractionDigits;\n const pointIndex = integerDigits.length + Number(exponent);\n if (pointIndex <= 0) return `${sign}0.${'0'.repeat(-pointIndex)}${digits}`;\n const integerPart = digits.padEnd(pointIndex, '0').slice(0, pointIndex).replace(/^0+(?=\\d)/, '');\n const fractionPart = digits.slice(pointIndex);\n return `${sign}${integerPart}${fractionPart ? `.${fractionPart}` : ''}`;\n}\n"],"mappings":";AAOA,MAAa,wBAAwD,CAAC;AACtE,MAAa,wBAA+C,CAAC;AAC7D,MAAa,0BAA8D,CAAC;AAE5E,MAAM,0BAA0B;;;;;;AAOhC,SAAgB,wBAAwB,OAAmC;CACvE,MAAM,OAAO,MAAM,SAAS;CAC5B,MAAM,QAAQ,wBAAwB,KAAK,IAAI;CAC/C,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,GACA,OAAO,IACT,gBAAgB,IAChB,iBAAiB,IACjB,WAAW,OACX;CAEJ,MAAM,SAAS,gBAAgB;CAC/B,MAAM,aAAa,cAAc,SAAS,OAAO,QAAQ;CACzD,IAAI,cAAc,GAAG,OAAO,GAAG,KAAK,IAAI,IAAI,OAAO,CAAC,UAAU,IAAI;CAClE,MAAM,cAAc,OAAO,OAAO,YAAY,GAAG,CAAC,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC,QAAQ,aAAa,EAAE;CAC/F,MAAM,eAAe,OAAO,MAAM,UAAU;CAC5C,OAAO,GAAG,OAAO,cAAc,eAAe,IAAI,iBAAiB;AACvE"}
|
package/dist/assertions.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { mongo } from "mongoose";
|
|
2
|
+
/**
|
|
3
|
+
* Matched documents whose values were already equal to the update do not count as modified.
|
|
4
|
+
*/
|
|
5
|
+
export declare function assertMongooseUpdateSuccess(update: PromiseLike<mongo.UpdateResult<any>>, minModifiedCount?: number): Promise<void>;
|
|
3
6
|
//# sourceMappingURL=assertions.d.ts.map
|
package/dist/assertions.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assertions.d.ts","names":[],"sources":["../src/assertions.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"assertions.d.ts","names":[],"sources":["../src/assertions.ts"],"mappings":";;;;wBAKsB,4BAClB,QAAQ,YAAY,MAAM,oBAC1B,4BAAoB"}
|
package/dist/assertions.js
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
// src/assertions.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Matched documents whose values were already equal to the update do not count as modified.
|
|
4
|
+
*/
|
|
5
|
+
async function assertMongooseUpdateSuccess(update, minModifiedCount = 1) {
|
|
6
|
+
if (typeof minModifiedCount !== "number") throw new TypeError("minModifiedCount must be a number");
|
|
7
|
+
if (!Number.isSafeInteger(minModifiedCount) || minModifiedCount < 1) throw new RangeError("minModifiedCount must be a positive safe integer");
|
|
8
|
+
const updateResult = await update;
|
|
9
|
+
if (!updateResult.acknowledged) throw new Error("Update was not acknowledged (Mongoose also reports this when the cast update is empty)");
|
|
10
|
+
const modifiedCount = updateResult.modifiedCount + updateResult.upsertedCount;
|
|
11
|
+
if (modifiedCount < minModifiedCount) throw new Error(`Expected to modify at least ${minModifiedCount} document(s), but modified ${modifiedCount}`);
|
|
6
12
|
}
|
|
7
13
|
export { assertMongooseUpdateSuccess };
|
|
8
14
|
|
package/dist/assertions.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assertions.js","names":[],"sources":["../src/assertions.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"assertions.js","names":[],"sources":["../src/assertions.ts"],"sourcesContent":["import type { mongo } from 'mongoose';\n\n/**\n * Matched documents whose values were already equal to the update do not count as modified.\n */\nexport async function assertMongooseUpdateSuccess(\n update: PromiseLike<mongo.UpdateResult<any>>,\n minModifiedCount = 1,\n) {\n if (typeof minModifiedCount !== 'number') throw new TypeError('minModifiedCount must be a number');\n if (!Number.isSafeInteger(minModifiedCount) || minModifiedCount < 1) {\n throw new RangeError('minModifiedCount must be a positive safe integer');\n }\n\n const updateResult = await update;\n if (!updateResult.acknowledged) {\n throw new Error('Update was not acknowledged (Mongoose also reports this when the cast update is empty)');\n }\n\n const modifiedCount = updateResult.modifiedCount + updateResult.upsertedCount;\n if (modifiedCount < minModifiedCount) {\n throw new Error(`Expected to modify at least ${minModifiedCount} document(s), but modified ${modifiedCount}`);\n }\n}\n"],"mappings":";;;;AAKA,eAAsB,4BAClB,QACA,mBAAmB,GACrB;CACE,IAAI,OAAO,qBAAqB,UAAU,MAAM,IAAI,UAAU,mCAAmC;CACjG,IAAI,CAAC,OAAO,cAAc,gBAAgB,KAAK,mBAAmB,GAC9D,MAAM,IAAI,WAAW,kDAAkD;CAG3E,MAAM,eAAe,MAAM;CAC3B,IAAI,CAAC,aAAa,cACd,MAAM,IAAI,MAAM,wFAAwF;CAG5G,MAAM,gBAAgB,aAAa,gBAAgB,aAAa;CAChE,IAAI,gBAAgB,kBAChB,MAAM,IAAI,MAAM,+BAA+B,iBAAiB,6BAA6B,eAAe;AAEpH"}
|
package/dist/builders.d.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Connection, Schema } from "mongoose";
|
|
2
|
+
import { MongooseLeanDecimal128ToStringPluginOptions } from "./plugins/lean-decimal128-to-string.js";
|
|
2
3
|
import { BaseMongoosePaginateModel } from "./types/index.js";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
export interface BuildMongooseModelOptions {
|
|
5
|
+
connection?: Connection;
|
|
6
|
+
plugins?: {
|
|
7
|
+
leanDecimal128ToString?: boolean | MongooseLeanDecimal128ToStringPluginOptions;
|
|
8
|
+
normalize?: boolean;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
6
11
|
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;
|
|
7
12
|
//# sourceMappingURL=builders.d.ts.map
|
package/dist/builders.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builders.d.ts","names":[],"sources":["../src/builders.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"builders.d.ts","names":[],"sources":["../src/builders.ts"],"mappings":";;;iBAgBiB;EACb,aAAa;EACb;IACI,mCAAmC;IACnC;;;wBAIQ,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,22 +1,22 @@
|
|
|
1
|
-
import
|
|
1
|
+
import mongoosePaginate from "mongoose-paginate-v2";
|
|
2
|
+
import { beforeModelBuildHooks } from "./_internals.js";
|
|
2
3
|
import { getDefaultMongooseConnection } from "./connection.js";
|
|
3
4
|
import { mongooseAssertionsPlugin } from "./plugins/assertions.js";
|
|
4
5
|
import { mongooseLeanDecimal128ToStringPlugin } from "./plugins/lean-decimal128-to-string.js";
|
|
5
6
|
import { mongooseNormalizePlugin } from "./plugins/normalize.js";
|
|
6
|
-
import mongooseAggregatePaginate from "mongoose-aggregate-paginate-v2";
|
|
7
|
-
import mongoosePaginate from "mongoose-paginate-v2";
|
|
8
7
|
// src/builders.ts
|
|
8
|
+
const builtSchemas = /* @__PURE__ */ new WeakSet();
|
|
9
9
|
function buildMongooseModel(collection, name, schema, options) {
|
|
10
|
+
const connection = options?.connection ?? getDefaultMongooseConnection();
|
|
11
|
+
if (!builtSchemas.has(schema)) [...beforeModelBuildHooks].forEach((hook) => hook(schema));
|
|
12
|
+
builtSchemas.add(schema);
|
|
10
13
|
const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;
|
|
11
|
-
if (leanDecimal128ToStringPluginOptions !== false) schema.plugin(mongooseLeanDecimal128ToStringPlugin,
|
|
12
|
-
const normalizePluginOptions = options?.plugins?.normalize;
|
|
13
|
-
if (normalizePluginOptions !== false) schema.plugin(mongooseNormalizePlugin, typeof normalizePluginOptions === "object" ? normalizePluginOptions : void 0);
|
|
14
|
-
schema.plugin(mongooseAggregatePaginate);
|
|
14
|
+
if (leanDecimal128ToStringPluginOptions !== false) schema.plugin(mongooseLeanDecimal128ToStringPlugin, leanDecimal128ToStringPluginOptions === true ? void 0 : leanDecimal128ToStringPluginOptions);
|
|
15
15
|
schema.plugin(mongooseAssertionsPlugin);
|
|
16
16
|
schema.plugin(mongoosePaginate);
|
|
17
|
-
schema.
|
|
18
|
-
|
|
19
|
-
return
|
|
17
|
+
if (schema.get("timestamps") === void 0) schema.set("timestamps", true);
|
|
18
|
+
if (options?.plugins?.normalize !== false) schema.plugin(mongooseNormalizePlugin);
|
|
19
|
+
return connection.model(name, schema, collection);
|
|
20
20
|
}
|
|
21
21
|
export { buildMongooseModel };
|
|
22
22
|
|
package/dist/builders.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builders.js","names":[],"sources":["../src/builders.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"builders.js","names":[],"sources":["../src/builders.ts"],"sourcesContent":["import type {\n Connection,\n Schema,\n} from 'mongoose';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { beforeModelBuildHooks } from './_internals';\nimport { getDefaultMongooseConnection } from './connection';\nimport { mongooseAssertionsPlugin } from './plugins/assertions';\nimport { mongooseLeanDecimal128ToStringPlugin } from './plugins/lean-decimal128-to-string';\nimport type { MongooseLeanDecimal128ToStringPluginOptions } from './plugins/lean-decimal128-to-string';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BaseMongoosePaginateModel } from './types';\n\nconst builtSchemas = new WeakSet<object>();\n\nexport interface BuildMongooseModelOptions {\n connection?: Connection;\n plugins?: {\n leanDecimal128ToString?: boolean | MongooseLeanDecimal128ToStringPluginOptions;\n normalize?: boolean;\n };\n}\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 // Resolve first so a missing default connection fails before the schema is mutated.\n const connection = options?.connection ?? getDefaultMongooseConnection();\n // Hook settings such as `toJSON` and `timestamps` must be in place before the plugins and defaults below read them,\n // and a rebuilt schema has its `toJSON` options locked. Copied because a hook may remove itself while running.\n if (!builtSchemas.has(schema)) [...beforeModelBuildHooks].forEach((hook) => hook(schema));\n builtSchemas.add(schema);\n const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;\n if (leanDecimal128ToStringPluginOptions !== false) {\n schema.plugin(\n mongooseLeanDecimal128ToStringPlugin,\n leanDecimal128ToStringPluginOptions === true ? undefined : leanDecimal128ToStringPluginOptions,\n );\n }\n\n schema.plugin(mongooseAssertionsPlugin);\n schema.plugin(mongoosePaginate);\n // Schema#set('timestamps') registers the timestamp hooks again, so only fill in the default.\n if (schema.get('timestamps') === undefined) schema.set('timestamps', true);\n // Registered last because it locks the schema's `toJSON` options.\n if (options?.plugins?.normalize !== false) schema.plugin(mongooseNormalizePlugin);\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n"],"mappings":";;;;;;;AAcA,MAAM,+BAAe,IAAI,QAAgB;AAUzC,SAAgB,mBAMZ,YACA,MACA,QACA,SACK;CAEL,MAAM,aAAa,SAAS,cAAc,6BAA6B;CAGvE,IAAI,CAAC,aAAa,IAAI,MAAM,GAAG,CAAC,GAAG,qBAAqB,CAAC,CAAC,SAAS,SAAS,KAAK,MAAM,CAAC;CACxF,aAAa,IAAI,MAAM;CACvB,MAAM,sCAAsC,SAAS,SAAS;CAC9D,IAAI,wCAAwC,OACxC,OAAO,OACH,sCACA,wCAAwC,OAAO,KAAA,IAAY,mCAC/D;CAGJ,OAAO,OAAO,wBAAwB;CACtC,OAAO,OAAO,gBAAgB;CAE9B,IAAI,OAAO,IAAI,YAAY,MAAM,KAAA,GAAW,OAAO,IAAI,cAAc,IAAI;CAEzE,IAAI,SAAS,SAAS,cAAc,OAAO,OAAO,OAAO,uBAAuB;CAChF,OAAO,WAAW,MAAoC,MAAM,QAAQ,UAAU;AAClF"}
|
package/dist/connection.d.ts
CHANGED
package/dist/connection.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connection.d.ts","names":[],"sources":["../src/connection.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"connection.d.ts","names":[],"sources":["../src/connection.ts"],"mappings":";;;;wBAWgB,gCAAgC"}
|
package/dist/connection.js
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
import { customMongooseOptions, mongooseConnectionState } from "./_internals.js";
|
|
2
1
|
import mongoose from "mongoose";
|
|
2
|
+
import { customMongooseOptions, mongooseConnectionState } from "./_internals.js";
|
|
3
3
|
// src/connection.ts
|
|
4
|
+
/**
|
|
5
|
+
* @throws {Error} If `MONGODB_URI` is unset or empty while the default connection has not been created.
|
|
6
|
+
*/
|
|
4
7
|
function getDefaultMongooseConnection() {
|
|
5
|
-
|
|
8
|
+
if (mongooseConnectionState.defaultConnection) return mongooseConnectionState.defaultConnection;
|
|
9
|
+
const uri = process.env.MONGODB_URI;
|
|
10
|
+
if (!uri) throw new Error("MONGODB_URI must be set before the default connection is created.");
|
|
11
|
+
return mongooseConnectionState.defaultConnection = mongoose.createConnection(uri, customMongooseOptions.defaultConnectionOptions);
|
|
6
12
|
}
|
|
7
13
|
export { getDefaultMongooseConnection };
|
|
8
14
|
|
package/dist/connection.js.map
CHANGED
|
@@ -1 +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
|
|
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\n/**\n * @throws {Error} If `MONGODB_URI` is unset or empty while the default connection has not been created.\n */\nexport function getDefaultMongooseConnection(): Connection {\n if (mongooseConnectionState.defaultConnection) return mongooseConnectionState.defaultConnection;\n const uri = process.env.MONGODB_URI;\n if (!uri) throw new Error('MONGODB_URI must be set before the default connection is created.');\n return mongooseConnectionState.defaultConnection = mongoose.createConnection(\n uri,\n customMongooseOptions.defaultConnectionOptions,\n );\n}\n"],"mappings":";;;;;;AAWA,SAAgB,+BAA2C;CACvD,IAAI,wBAAwB,mBAAmB,OAAO,wBAAwB;CAC9E,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,mEAAmE;CAC7F,OAAO,wBAAwB,oBAAoB,SAAS,iBACxD,KACA,sBAAsB,wBAC1B;AACJ"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Types } from "mongoose";
|
|
2
|
+
export type MongooseDocumentId<T> = T extends string | Types.ObjectId ? T : T extends {
|
|
3
|
+
_id: infer Id;
|
|
4
|
+
} ? Id : never;
|
|
5
|
+
export declare function getMongooseDocumentId<T extends string | Types.ObjectId | {
|
|
6
|
+
_id: unknown;
|
|
7
|
+
}>(value: T): MongooseDocumentId<T>;
|
|
8
|
+
//# sourceMappingURL=documents.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documents.d.ts","names":[],"sources":["../src/documents.ts"],"mappings":";YAEY,mBAAmB,KAAK,mBAAmB,MAAM,WAAW,IAAI;EAAY,WAAW;IAAO;wBAE1F,sBAAsB,mBAAmB,MAAM;EAAa;GACxE,OAAO,IACR,mBAAmB"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Types } from "mongoose";
|
|
2
|
+
// src/documents.ts
|
|
3
|
+
function getMongooseDocumentId(value) {
|
|
4
|
+
const input = value;
|
|
5
|
+
if (typeof input === "string" || input instanceof Types.ObjectId || "_bsontype" in input && input._bsontype === "ObjectId") return input;
|
|
6
|
+
return input._id;
|
|
7
|
+
}
|
|
8
|
+
export { getMongooseDocumentId };
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=documents.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documents.js","names":[],"sources":["../src/documents.ts"],"sourcesContent":["import { Types } from 'mongoose';\n\nexport type MongooseDocumentId<T> = T extends string | Types.ObjectId ? T : T extends { _id: infer Id } ? Id : never;\n\nexport function getMongooseDocumentId<T extends string | Types.ObjectId | { _id: unknown }>(\n value: T,\n): MongooseDocumentId<T> {\n const input: string | Types.ObjectId | { _id: unknown } = value;\n // `_bsontype` also recognizes ObjectIds created by another copy of the bson package.\n if (typeof input === 'string' || input instanceof Types.ObjectId || ('_bsontype' in input && input._bsontype === 'ObjectId')) return input as never;\n return input._id as never;\n}\n"],"mappings":";;AAIA,SAAgB,sBACZ,OACqB;CACrB,MAAM,QAAoD;CAE1D,IAAI,OAAO,UAAU,YAAY,iBAAiB,MAAM,YAAa,eAAe,SAAS,MAAM,cAAc,YAAa,OAAO;CACrI,OAAO,MAAM;AACjB"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { mongo } from "mongoose";
|
|
2
|
+
/**
|
|
3
|
+
* Also matches a bulk write error, e.g. from an unordered `insertMany`, when any of its write errors is a duplicate
|
|
4
|
+
* key; the driver sets only the first write error's code on the error itself.
|
|
5
|
+
*/
|
|
6
|
+
export declare function isMongooseDuplicateKeyError(error: unknown): error is mongo.MongoServerError & {
|
|
7
|
+
code: 11000;
|
|
8
|
+
};
|
|
9
|
+
//# sourceMappingURL=duplicate-key.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"duplicate-key.d.ts","names":[],"sources":["../../src/errors/duplicate-key.ts"],"mappings":";;;;;wBAMgB,4BAA4B,iBAAiB,SAAS,MAAM;EAAqB"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { mongo } from "mongoose";
|
|
2
|
+
// src/errors/duplicate-key.ts
|
|
3
|
+
/**
|
|
4
|
+
* Also matches a bulk write error, e.g. from an unordered `insertMany`, when any of its write errors is a duplicate
|
|
5
|
+
* key; the driver sets only the first write error's code on the error itself.
|
|
6
|
+
*/
|
|
7
|
+
function isMongooseDuplicateKeyError(error) {
|
|
8
|
+
if (error instanceof mongo.MongoBulkWriteError) {
|
|
9
|
+
if ((Array.isArray(error.writeErrors) ? error.writeErrors : [error.writeErrors]).some((writeError) => writeError?.code === 11e3)) return true;
|
|
10
|
+
}
|
|
11
|
+
return error instanceof mongo.MongoServerError && error.code === 11e3;
|
|
12
|
+
}
|
|
13
|
+
export { isMongooseDuplicateKeyError };
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=duplicate-key.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"duplicate-key.js","names":[],"sources":["../../src/errors/duplicate-key.ts"],"sourcesContent":["import { mongo } from 'mongoose';\n\n/**\n * Also matches a bulk write error, e.g. from an unordered `insertMany`, when any of its write errors is a duplicate\n * key; the driver sets only the first write error's code on the error itself.\n */\nexport function isMongooseDuplicateKeyError(error: unknown): error is mongo.MongoServerError & { code: 11000 } {\n if (error instanceof mongo.MongoBulkWriteError) {\n const writeErrors = Array.isArray(error.writeErrors) ? error.writeErrors : [error.writeErrors];\n if (writeErrors.some((writeError) => writeError?.code === 11000)) return true;\n }\n\n return error instanceof mongo.MongoServerError && error.code === 11000;\n}\n"],"mappings":";;;;;;AAMA,SAAgB,4BAA4B,OAAmE;CAC3G,IAAI,iBAAiB,MAAM,qBACH;OAAA,MAAM,QAAQ,MAAM,WAAW,IAAI,MAAM,cAAc,CAAC,MAAM,WAAW,EAAA,CAC7E,MAAM,eAAe,YAAY,SAAS,IAAK,GAAG,OAAO;CAAA;CAG7E,OAAO,iBAAiB,MAAM,oBAAoB,MAAM,SAAS;AACrE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mongoose-update-conflict-error.d.ts","names":[],"sources":["../../src/errors/mongoose-update-conflict-error.ts"],"mappings":"A,qBAAa,oCAAoC;EACpC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mongoose-update-conflict-error.js","names":[],"sources":["../../src/errors/mongoose-update-conflict-error.ts"],"sourcesContent":["export class MongooseUpdateConflictError extends Error {\n override name = 'MongooseUpdateConflictError';\n}\n"],"mappings":";AAAA,IAAa,8BAAb,cAAiD,MAAM;CAC1C,OAAO;AACpB"}
|
package/dist/options.d.ts
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ConnectOptions, Schema } from "mongoose";
|
|
2
|
+
export type BeforeMongooseModelBuildHook = (schema: Schema<any, any, any, any>) => void;
|
|
3
|
+
export interface CustomMongooseOptions {
|
|
4
|
+
defaultConnectionOptions?: ConnectOptions;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Hooks run in registration order on every schema passed to `buildMongooseModel`, once per schema, before the
|
|
8
|
+
* package plugins and the `timestamps` default are applied.
|
|
9
|
+
*
|
|
10
|
+
* @returns A function that removes the hook.
|
|
11
|
+
*/
|
|
12
|
+
export declare function addBeforeMongooseModelBuildHook(hook: BeforeMongooseModelBuildHook): () => void;
|
|
13
|
+
/**
|
|
14
|
+
* @throws {Error} If `defaultConnectionOptions` is set after the default connection has been created.
|
|
15
|
+
*/
|
|
2
16
|
export declare function setCustomMongooseOptions<K extends keyof CustomMongooseOptions>(key: K, value: CustomMongooseOptions[K]): void;
|
|
3
17
|
//# sourceMappingURL=options.d.ts.map
|
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":";YAWY,gCAAgC,QAAQ;iBAEnC;EACb,2BAA2B;;;;;;;;wBASf,gCAAgC,MAAM;;;;wBAatC,yBAAyB,gBAAgB,uBACrD,KAAK,GACL,OAAO,sBAAsB"}
|
package/dist/options.js
CHANGED
|
@@ -1,9 +1,26 @@
|
|
|
1
|
-
import { customMongooseOptions, mongooseConnectionState } from "./_internals.js";
|
|
1
|
+
import { beforeModelBuildHooks, customMongooseOptions, mongooseConnectionState } from "./_internals.js";
|
|
2
2
|
// src/options.ts
|
|
3
|
+
/**
|
|
4
|
+
* Hooks run in registration order on every schema passed to `buildMongooseModel`, once per schema, before the
|
|
5
|
+
* package plugins and the `timestamps` default are applied.
|
|
6
|
+
*
|
|
7
|
+
* @returns A function that removes the hook.
|
|
8
|
+
*/
|
|
9
|
+
function addBeforeMongooseModelBuildHook(hook) {
|
|
10
|
+
const registration = (schema) => hook(schema);
|
|
11
|
+
beforeModelBuildHooks.push(registration);
|
|
12
|
+
return () => {
|
|
13
|
+
const index = beforeModelBuildHooks.indexOf(registration);
|
|
14
|
+
if (index !== -1) beforeModelBuildHooks.splice(index, 1);
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* @throws {Error} If `defaultConnectionOptions` is set after the default connection has been created.
|
|
19
|
+
*/
|
|
3
20
|
function setCustomMongooseOptions(key, value) {
|
|
4
21
|
if (key === "defaultConnectionOptions" && mongooseConnectionState.defaultConnection) throw new Error("Default connection options must be set before the default connection is created.");
|
|
5
22
|
customMongooseOptions[key] = value;
|
|
6
23
|
}
|
|
7
|
-
export { setCustomMongooseOptions };
|
|
24
|
+
export { addBeforeMongooseModelBuildHook, setCustomMongooseOptions };
|
|
8
25
|
|
|
9
26
|
//# sourceMappingURL=options.js.map
|
package/dist/options.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../src/options.ts"],"sourcesContent":["import {\n customMongooseOptions,\n mongooseConnectionState,\n} from './_internals';\
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../src/options.ts"],"sourcesContent":["import type {\n ConnectOptions,\n Schema,\n} from 'mongoose';\n\nimport {\n beforeModelBuildHooks,\n customMongooseOptions,\n mongooseConnectionState,\n} from './_internals';\n\nexport type BeforeMongooseModelBuildHook = (schema: Schema<any, any, any, any>) => void;\n\nexport interface CustomMongooseOptions {\n defaultConnectionOptions?: ConnectOptions;\n}\n\n/**\n * Hooks run in registration order on every schema passed to `buildMongooseModel`, once per schema, before the\n * package plugins and the `timestamps` default are applied.\n *\n * @returns A function that removes the hook.\n */\nexport function addBeforeMongooseModelBuildHook(hook: BeforeMongooseModelBuildHook) {\n // Wrapping keeps each registration distinct, so removing one never removes another of the same function.\n const registration: BeforeMongooseModelBuildHook = (schema) => hook(schema);\n beforeModelBuildHooks.push(registration);\n return () => {\n const index = beforeModelBuildHooks.indexOf(registration);\n if (index !== -1) beforeModelBuildHooks.splice(index, 1);\n };\n}\n\n/**\n * @throws {Error} If `defaultConnectionOptions` is set after the default connection has been created.\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":";;;;;;;;AAuBA,SAAgB,gCAAgC,MAAoC;CAEhF,MAAM,gBAA8C,WAAW,KAAK,MAAM;CAC1E,sBAAsB,KAAK,YAAY;CACvC,aAAa;EACT,MAAM,QAAQ,sBAAsB,QAAQ,YAAY;EACxD,IAAI,UAAU,IAAI,sBAAsB,OAAO,OAAO,CAAC;CAC3D;AACJ;;;;AAKA,SAAgB,yBACZ,KACA,OACF;CACE,IAAI,QAAQ,8BAA8B,wBAAwB,mBAC9D,MAAM,IAAI,MAAM,kFAAkF;CAGtG,sBAAsB,OAAO;AACjC"}
|
|
@@ -1,11 +1,32 @@
|
|
|
1
|
-
import { Schema, mongo } from "mongoose";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import { ClientSession, MongooseUpdateQueryOptions, QueryFilter, QueryOptions, Schema, UpdateQuery, UpdateWithAggregationPipeline, mongo } from "mongoose";
|
|
2
|
+
type UpdateIfUnmodified<RawDocType, Result> = (updatedAt: Date | number | string, update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, options?: UpdateIfUnmodifiedOptions) => Promise<Result>;
|
|
3
|
+
export interface MongooseAssertionsDocumentMethods<RawDocType> {
|
|
4
|
+
/**
|
|
5
|
+
* @throws {MongooseUpdateConflictError} If the document was changed or deleted after `updatedAt`.
|
|
6
|
+
*/
|
|
7
|
+
assertUpdateIfUnmodified: UpdateIfUnmodified<RawDocType, void>;
|
|
8
|
+
assertUpdateSuccess: (update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, options?: null | QueryOptions) => Promise<void>;
|
|
9
|
+
/**
|
|
10
|
+
* Updates the document only if its `updatedAt` timestamp still equals `updatedAt`, in one atomic `updateOne`, and
|
|
11
|
+
* returns whether it did. Every update through Mongoose sets a new `updatedAt`, so any change in between, or a
|
|
12
|
+
* deletion, makes it return `false`; timestamps have millisecond precision, so two writes within the same
|
|
13
|
+
* millisecond are not told apart. Uses `options.session` if given, otherwise the document's session.
|
|
14
|
+
*
|
|
15
|
+
* @throws {Error} If the schema has no `updatedAt` timestamp or the document has no `_id`.
|
|
16
|
+
*/
|
|
17
|
+
updateIfUnmodified: UpdateIfUnmodified<RawDocType, boolean>;
|
|
9
18
|
}
|
|
10
|
-
export
|
|
19
|
+
export interface MongooseAssertionsModelStatics<RawDocType> {
|
|
20
|
+
assertUpdateManySuccess: (filter: QueryFilter<RawDocType>, update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null, minModifiedCount?: number) => Promise<void>;
|
|
21
|
+
assertUpdateOneSuccess: (filter: QueryFilter<RawDocType>, update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null) => Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Only the session is configurable: other update options such as `upsert` or `timestamps` would break the guarantee
|
|
25
|
+
* that a successful update writes a new `updatedAt`.
|
|
26
|
+
*/
|
|
27
|
+
export interface UpdateIfUnmodifiedOptions {
|
|
28
|
+
session?: ClientSession | null;
|
|
29
|
+
}
|
|
30
|
+
export declare function mongooseAssertionsPlugin(schema: Schema): void;
|
|
31
|
+
export {};
|
|
11
32
|
//# sourceMappingURL=assertions.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assertions.d.ts","names":[],"sources":["../../src/plugins/assertions.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"assertions.d.ts","names":[],"sources":["../../src/plugins/assertions.ts"],"mappings":";KAeK,mBAAmB,YAAY,WAChC,WAAW,wBACX,QAAQ,YAAY,cAAc,+BAClC,UAAU,8BACT,QAAQ;iBAEI,kCAAkC;;;;EAI/C,0BAA0B,mBAAmB;EAC7C,sBACI,SAAS,YAAY,cAAc,+BACnC,iBAAiB,iBAChB;;;;;;;;;EAUL,oBAAoB,mBAAmB;;iBAG1B,+BAA+B;EAC5C,0BACI,QAAQ,YAAY,aACpB,QAAQ,YAAY,cAAc,+BAClC,WAAW,MAAM,gBAAgB,2BAA2B,qBAC5D,8BACC;EAEL,yBACI,QAAQ,YAAY,aACpB,QAAQ,YAAY,cAAc,+BAClC,WAAW,MAAM,gBAAgB,2BAA2B,wBAC3D;;;;;;iBAOQ;EACb,UAAU;;wBAsBE,yBAAyB,QAAQ"}
|
|
@@ -1,12 +1,40 @@
|
|
|
1
1
|
import { assertMongooseUpdateSuccess } from "../assertions.js";
|
|
2
|
+
import { MongooseUpdateConflictError } from "../errors/mongoose-update-conflict-error.js";
|
|
2
3
|
// src/plugins/assertions.ts
|
|
4
|
+
function getUpdatedAtPath(schema) {
|
|
5
|
+
const timestamps = schema.get("timestamps");
|
|
6
|
+
let path;
|
|
7
|
+
if (timestamps === true) path = "updatedAt";
|
|
8
|
+
else if (timestamps && typeof timestamps === "object") path = timestamps.updatedAt === true || !("updatedAt" in timestamps) ? "updatedAt" : timestamps.updatedAt;
|
|
9
|
+
if (typeof path === "string" && schema.path(path)) return path;
|
|
10
|
+
throw new Error("updateIfUnmodified requires the schema to have an updatedAt timestamp");
|
|
11
|
+
}
|
|
3
12
|
function mongooseAssertionsPlugin(schema) {
|
|
4
|
-
schema.method("
|
|
5
|
-
|
|
13
|
+
schema.method("updateIfUnmodified", updateIfUnmodified);
|
|
14
|
+
schema.method("assertUpdateIfUnmodified", async function(...args) {
|
|
15
|
+
if (await updateIfUnmodified.apply(this, args)) return;
|
|
16
|
+
throw new MongooseUpdateConflictError("Document was modified or deleted");
|
|
17
|
+
});
|
|
18
|
+
schema.method("assertUpdateSuccess", async function(update, options) {
|
|
19
|
+
return await assertMongooseUpdateSuccess(this.updateOne(update, options));
|
|
6
20
|
});
|
|
7
|
-
schema.static("
|
|
8
|
-
return await assertMongooseUpdateSuccess(
|
|
21
|
+
schema.static("assertUpdateManySuccess", async function(filter, update, options, minModifiedCount) {
|
|
22
|
+
return await assertMongooseUpdateSuccess(this.updateMany(filter, update, options), minModifiedCount);
|
|
9
23
|
});
|
|
24
|
+
schema.static("assertUpdateOneSuccess", async function(filter, update, options) {
|
|
25
|
+
return await assertMongooseUpdateSuccess(this.updateOne(filter, update, options));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
async function updateIfUnmodified(updatedAt, update, options) {
|
|
29
|
+
if (this._id === null || this._id === void 0) throw new Error("updateIfUnmodified requires the document _id");
|
|
30
|
+
const session = options && "session" in options ? options.session : this.$session() ?? void 0;
|
|
31
|
+
const model = this.constructor;
|
|
32
|
+
const result = await model.updateOne({
|
|
33
|
+
_id: this._id,
|
|
34
|
+
[getUpdatedAtPath(model.schema)]: updatedAt
|
|
35
|
+
}, update, session === void 0 ? void 0 : { session });
|
|
36
|
+
if (!result.acknowledged) throw new Error("Update was not acknowledged");
|
|
37
|
+
return result.matchedCount === 1;
|
|
10
38
|
}
|
|
11
39
|
export { mongooseAssertionsPlugin };
|
|
12
40
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assertions.js","names":[],"sources":["../../src/plugins/assertions.ts"],"sourcesContent":["import type {\n mongo,\n MongooseUpdateQueryOptions,\n QueryFilter,\n QueryOptions,\n Schema,\n UpdateQuery,\n UpdateWithAggregationPipeline,\n} from 'mongoose';\n\nimport { assertMongooseUpdateSuccess } from '../assertions';\
|
|
1
|
+
{"version":3,"file":"assertions.js","names":[],"sources":["../../src/plugins/assertions.ts"],"sourcesContent":["import type {\n ClientSession,\n Model,\n mongo,\n MongooseUpdateQueryOptions,\n QueryFilter,\n QueryOptions,\n Schema,\n UpdateQuery,\n UpdateWithAggregationPipeline,\n} from 'mongoose';\n\nimport { assertMongooseUpdateSuccess } from '../assertions';\nimport { MongooseUpdateConflictError } from '../errors/mongoose-update-conflict-error';\n\ntype UpdateIfUnmodified<RawDocType, Result> = (\n updatedAt: Date | number | string,\n update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,\n options?: UpdateIfUnmodifiedOptions,\n) => Promise<Result>;\n\nexport interface MongooseAssertionsDocumentMethods<RawDocType> {\n /**\n * @throws {MongooseUpdateConflictError} If the document was changed or deleted after `updatedAt`.\n */\n assertUpdateIfUnmodified: UpdateIfUnmodified<RawDocType, void>;\n assertUpdateSuccess: (\n update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,\n options?: null | QueryOptions,\n ) => Promise<void>;\n\n /**\n * Updates the document only if its `updatedAt` timestamp still equals `updatedAt`, in one atomic `updateOne`, and\n * returns whether it did. Every update through Mongoose sets a new `updatedAt`, so any change in between, or a\n * deletion, makes it return `false`; timestamps have millisecond precision, so two writes within the same\n * millisecond are not told apart. Uses `options.session` if given, otherwise the document's session.\n *\n * @throws {Error} If the schema has no `updatedAt` timestamp or the document has no `_id`.\n */\n updateIfUnmodified: UpdateIfUnmodified<RawDocType, boolean>;\n}\n\nexport interface MongooseAssertionsModelStatics<RawDocType> {\n assertUpdateManySuccess: (\n filter: QueryFilter<RawDocType>,\n update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null,\n minModifiedCount?: number,\n ) => Promise<void>;\n\n assertUpdateOneSuccess: (\n filter: QueryFilter<RawDocType>,\n update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null,\n ) => Promise<void>;\n}\n\n/**\n * Only the session is configurable: other update options such as `upsert` or `timestamps` would break the guarantee\n * that a successful update writes a new `updatedAt`.\n */\nexport interface UpdateIfUnmodifiedOptions {\n session?: ClientSession | null;\n}\n\ninterface UpdateIfUnmodifiedThis {\n $session: () => ClientSession | null;\n _id: unknown;\n constructor: Model<any>;\n}\n\nfunction getUpdatedAtPath(schema: Schema) {\n const timestamps = schema.get('timestamps');\n let path: unknown;\n if (timestamps === true) path = 'updatedAt';\n else if (timestamps && typeof timestamps === 'object') {\n path = timestamps.updatedAt === true || !('updatedAt' in timestamps) ? 'updatedAt' : timestamps.updatedAt;\n }\n\n // Mongoose skips timestamp paths it cannot name, e.g. `{ updatedAt: '' }`, so require the path to exist.\n if (typeof path === 'string' && schema.path(path)) return path;\n throw new Error('updateIfUnmodified requires the schema to have an updatedAt timestamp');\n}\n\nexport function mongooseAssertionsPlugin(schema: Schema) {\n schema.method('updateIfUnmodified', updateIfUnmodified);\n schema.method(\n 'assertUpdateIfUnmodified',\n async function (this: UpdateIfUnmodifiedThis, ...args: Parameters<UpdateIfUnmodified<any, void>>) {\n if (await updateIfUnmodified.apply(this, args)) return;\n throw new MongooseUpdateConflictError('Document was modified or deleted');\n },\n );\n\n schema.method(\n 'assertUpdateSuccess',\n async function (update?: UpdateQuery<any> | UpdateWithAggregationPipeline, options?: null | QueryOptions) {\n return await assertMongooseUpdateSuccess(this.updateOne(update, options));\n },\n );\n\n schema.static(\n 'assertUpdateManySuccess',\n async function (\n filter: QueryFilter<any>,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,\n minModifiedCount?: number,\n ) {\n return await assertMongooseUpdateSuccess(this.updateMany(filter, update, options), minModifiedCount);\n },\n );\n\n schema.static(\n 'assertUpdateOneSuccess',\n async function (\n filter: QueryFilter<any>,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,\n ) {\n return await assertMongooseUpdateSuccess(this.updateOne(filter, update, options));\n },\n );\n}\n\nasync function updateIfUnmodified(\n this: UpdateIfUnmodifiedThis,\n updatedAt: Date | number | string,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: UpdateIfUnmodifiedOptions,\n) {\n // With `ignoreUndefined`, an undefined `_id` would be dropped from the filter and match another document.\n if (this._id === null || this._id === undefined) throw new Error('updateIfUnmodified requires the document _id');\n const session = options && 'session' in options ? options.session : this.$session() ?? undefined;\n const model = this.constructor;\n const result = await model.updateOne(\n {\n _id: this._id,\n [getUpdatedAtPath(model.schema)]: updatedAt,\n },\n update,\n // Without a session the key is omitted, so `transactionAsyncLocalStorage` can still supply one. An explicit\n // `null` opts out of any session, as Mongoose's own options do, although its types only allow `undefined`.\n session === undefined ? undefined : { session: session as ClientSession },\n );\n\n if (!result.acknowledged) throw new Error('Update was not acknowledged');\n return result.matchedCount === 1;\n}\n"],"mappings":";;;AAuEA,SAAS,iBAAiB,QAAgB;CACtC,MAAM,aAAa,OAAO,IAAI,YAAY;CAC1C,IAAI;CACJ,IAAI,eAAe,MAAM,OAAO;MAC3B,IAAI,cAAc,OAAO,eAAe,UACzC,OAAO,WAAW,cAAc,QAAQ,EAAE,eAAe,cAAc,cAAc,WAAW;CAIpG,IAAI,OAAO,SAAS,YAAY,OAAO,KAAK,IAAI,GAAG,OAAO;CAC1D,MAAM,IAAI,MAAM,uEAAuE;AAC3F;AAEA,SAAgB,yBAAyB,QAAgB;CACrD,OAAO,OAAO,sBAAsB,kBAAkB;CACtD,OAAO,OACH,4BACA,eAA8C,GAAG,MAAiD;EAC9F,IAAI,MAAM,mBAAmB,MAAM,MAAM,IAAI,GAAG;EAChD,MAAM,IAAI,4BAA4B,kCAAkC;CAC5E,CACJ;CAEA,OAAO,OACH,uBACA,eAAgB,QAA2D,SAA+B;EACtG,OAAO,MAAM,4BAA4B,KAAK,UAAU,QAAQ,OAAO,CAAC;CAC5E,CACJ;CAEA,OAAO,OACH,2BACA,eACI,QACA,QACA,SACA,kBACF;EACE,OAAO,MAAM,4BAA4B,KAAK,WAAW,QAAQ,QAAQ,OAAO,GAAG,gBAAgB;CACvG,CACJ;CAEA,OAAO,OACH,0BACA,eACI,QACA,QACA,SACF;EACE,OAAO,MAAM,4BAA4B,KAAK,UAAU,QAAQ,QAAQ,OAAO,CAAC;CACpF,CACJ;AACJ;AAEA,eAAe,mBAEX,WACA,QACA,SACF;CAEE,IAAI,KAAK,QAAQ,QAAQ,KAAK,QAAQ,KAAA,GAAW,MAAM,IAAI,MAAM,8CAA8C;CAC/G,MAAM,UAAU,WAAW,aAAa,UAAU,QAAQ,UAAU,KAAK,SAAS,KAAK,KAAA;CACvF,MAAM,QAAQ,KAAK;CACnB,MAAM,SAAS,MAAM,MAAM,UACvB;EACI,KAAK,KAAK;GACT,iBAAiB,MAAM,MAAM,IAAI;CACtC,GACA,QAGA,YAAY,KAAA,IAAY,KAAA,IAAY,EAAW,QAAyB,CAC5E;CAEA,IAAI,CAAC,OAAO,cAAc,MAAM,IAAI,MAAM,6BAA6B;CACvE,OAAO,OAAO,iBAAiB;AACnC"}
|