@kikiutils/mongoose 7.1.0 → 8.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.
Files changed (90) hide show
  1. package/README.md +8 -8
  2. package/dist/_internals.d.ts +4 -0
  3. package/dist/_internals.d.ts.map +1 -1
  4. package/dist/_internals.js +2 -1
  5. package/dist/_internals.js.map +1 -1
  6. package/dist/builders.d.ts.map +1 -1
  7. package/dist/builders.js +2 -3
  8. package/dist/builders.js.map +1 -1
  9. package/dist/connection.d.ts +5 -0
  10. package/dist/connection.d.ts.map +1 -0
  11. package/dist/connection.js +10 -0
  12. package/dist/connection.js.map +1 -0
  13. package/dist/options.d.ts.map +1 -1
  14. package/dist/options.js +2 -1
  15. package/dist/options.js.map +1 -1
  16. package/dist/plugins/normalize.d.ts +21 -14
  17. package/dist/plugins/normalize.d.ts.map +1 -1
  18. package/dist/plugins/normalize.js +15 -10
  19. package/dist/plugins/normalize.js.map +1 -1
  20. package/dist/schema-builders/base.d.ts +1 -1
  21. package/dist/schema-builders/base.d.ts.map +1 -1
  22. package/dist/schema-builders/base.js.map +1 -1
  23. package/dist/schema-builders/bigint.d.ts +48 -0
  24. package/dist/schema-builders/bigint.d.ts.map +1 -0
  25. package/dist/schema-builders/bigint.js +36 -0
  26. package/dist/schema-builders/bigint.js.map +1 -0
  27. package/dist/schema-builders/boolean.d.ts.map +1 -1
  28. package/dist/schema-builders/boolean.js.map +1 -1
  29. package/dist/schema-builders/decimal128.d.ts +16 -12
  30. package/dist/schema-builders/decimal128.d.ts.map +1 -1
  31. package/dist/schema-builders/decimal128.js.map +1 -1
  32. package/dist/schema-builders/double.d.ts +48 -0
  33. package/dist/schema-builders/double.d.ts.map +1 -0
  34. package/dist/schema-builders/double.js +37 -0
  35. package/dist/schema-builders/double.js.map +1 -0
  36. package/dist/schema-builders/index.d.ts +6 -1
  37. package/dist/schema-builders/index.js +6 -1
  38. package/dist/schema-builders/int32.d.ts +48 -0
  39. package/dist/schema-builders/int32.d.ts.map +1 -0
  40. package/dist/schema-builders/int32.js +36 -0
  41. package/dist/schema-builders/int32.js.map +1 -0
  42. package/dist/schema-builders/mixed.d.ts +34 -0
  43. package/dist/schema-builders/mixed.d.ts.map +1 -0
  44. package/dist/schema-builders/mixed.js +8 -0
  45. package/dist/schema-builders/mixed.js.map +1 -0
  46. package/dist/schema-builders/string.d.ts +33 -23
  47. package/dist/schema-builders/string.d.ts.map +1 -1
  48. package/dist/schema-builders/string.js.map +1 -1
  49. package/dist/schema-builders/uuid.d.ts +34 -0
  50. package/dist/schema-builders/uuid.d.ts.map +1 -0
  51. package/dist/schema-builders/uuid.js +8 -0
  52. package/dist/schema-builders/uuid.js.map +1 -0
  53. package/dist/types/aggregate-paginate.d.ts +24 -8
  54. package/dist/types/aggregate-paginate.d.ts.map +1 -1
  55. package/dist/types/index.d.ts +1 -4
  56. package/dist/types/index.d.ts.map +1 -1
  57. package/dist/types/options.d.ts +2 -1
  58. package/dist/types/options.d.ts.map +1 -1
  59. package/dist/types/paginate.d.ts +6 -2
  60. package/dist/types/paginate.d.ts.map +1 -1
  61. package/package.json +16 -12
  62. package/src/_internals.ts +3 -0
  63. package/src/builders.ts +3 -10
  64. package/src/connection.ts +14 -0
  65. package/src/options.ts +8 -1
  66. package/src/plugins/normalize.ts +23 -15
  67. package/src/schema-builders/base.ts +6 -1
  68. package/src/schema-builders/bigint.ts +134 -0
  69. package/src/schema-builders/boolean.ts +1 -4
  70. package/src/schema-builders/decimal128.ts +16 -12
  71. package/src/schema-builders/double.ts +135 -0
  72. package/src/schema-builders/index.ts +15 -0
  73. package/src/schema-builders/int32.ts +135 -0
  74. package/src/schema-builders/mixed.ts +37 -0
  75. package/src/schema-builders/string.ts +33 -23
  76. package/src/schema-builders/uuid.ts +48 -0
  77. package/src/types/aggregate-paginate.ts +29 -8
  78. package/src/types/index.ts +0 -5
  79. package/src/types/options.ts +3 -0
  80. package/src/types/paginate.ts +6 -2
  81. package/dist/constants.d.ts +0 -5
  82. package/dist/constants.d.ts.map +0 -1
  83. package/dist/constants.js +0 -6
  84. package/dist/constants.js.map +0 -1
  85. package/dist/helpers.d.ts +0 -5
  86. package/dist/helpers.d.ts.map +0 -1
  87. package/dist/helpers.js +0 -9
  88. package/dist/helpers.js.map +0 -1
  89. package/src/constants.ts +0 -3
  90. package/src/helpers.ts +0 -5
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@kikiutils/mongoose",
3
3
  "type": "module",
4
- "version": "7.1.0",
5
- "description": "A Mongoose plugin for enhanced JSON normalization and common schema creation, with built-in support for pagination and automatic Decimal128 conversion.",
4
+ "version": "8.0.0",
5
+ "description": "Provides Mongoose schema builders and utilities for connections, pagination, JSON normalization, and update checks.",
6
6
  "author": "kiki-kanri",
7
7
  "license": "MIT",
8
8
  "repository": {
@@ -10,14 +10,18 @@
10
10
  "url": "git+https://github.com/kikiutils/node-mongoose.git"
11
11
  },
12
12
  "keywords": [
13
- "Decimal128",
13
+ "bson",
14
+ "decimal128",
14
15
  "json",
15
- "mongo",
16
+ "mongodb",
16
17
  "mongoose",
17
18
  "normalization",
18
19
  "pagination",
19
20
  "plugin",
20
- "schema"
21
+ "schema",
22
+ "schema-builder",
23
+ "typescript",
24
+ "uuid"
21
25
  ],
22
26
  "sideEffects": false,
23
27
  "exports": {
@@ -78,7 +82,7 @@
78
82
  "dependencies": {
79
83
  "decimal.js": "^10.6.0",
80
84
  "es-toolkit": "^1.52.0",
81
- "mongoose": "^9.10.2",
85
+ "mongoose": "^9.10.3",
82
86
  "mongoose-aggregate-paginate-v2": "^1.1.5",
83
87
  "mongoose-paginate-v2": "^1.9.5",
84
88
  "type-fest": "^5.10.0"
@@ -87,15 +91,15 @@
87
91
  "@antfu/eslint-config": "^9.5.1",
88
92
  "@kikiutils/eslint-config": "^9.2.1",
89
93
  "@kikiutils/tsconfigs": "^7.0.0",
90
- "@types/node": "^26.6.3",
91
- "@vitest/coverage-v8": "^5.0.2",
94
+ "@types/node": "^26.6.4",
95
+ "@vitest/coverage-v8": "^5.0.3",
92
96
  "changelogen": "^0.6.2",
93
- "eslint": "^10.11.0",
94
- "knip": "^6.38.0",
95
- "publint": "^0.3.24",
97
+ "eslint": "^10.12.0",
98
+ "knip": "^6.39.0",
99
+ "publint": "^0.3.25",
96
100
  "tsdown": "^0.23.0",
97
101
  "typescript": "^6.0.3",
98
102
  "unplugin-unused": "^0.6.0",
99
- "vitest": "^5.0.2"
103
+ "vitest": "^5.0.3"
100
104
  }
101
105
  }
package/src/_internals.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import type { Connection } from 'mongoose';
2
+
1
3
  import type { CustomMongooseOptions } from './types/options';
2
4
 
3
5
  export const customMongooseOptions: CustomMongooseOptions = {};
6
+ export const mongooseConnectionState: { defaultConnection?: Connection } = {};
package/src/builders.ts CHANGED
@@ -1,4 +1,3 @@
1
- import mongoose from 'mongoose';
2
1
  import type {
3
2
  Model as MongooseModel,
4
3
  Schema,
@@ -7,7 +6,7 @@ import mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';
7
6
  import mongoosePaginate from 'mongoose-paginate-v2';
8
7
 
9
8
  import { customMongooseOptions } from './_internals';
10
- import { mongooseConnections } from './constants';
9
+ import { getDefaultMongooseConnection } from './connection';
11
10
  import { mongooseAssertionsPlugin } from './plugins/assertions';
12
11
  import { mongooseNormalizePlugin } from './plugins/normalize';
13
12
  import type { MongooseNormalizePluginOptions } from './plugins/normalize';
@@ -36,16 +35,10 @@ export function buildMongooseModel<
36
35
  schema.plugin(mongoosePaginate);
37
36
  schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);
38
37
  customMongooseOptions.beforeModelBuild?.(schema);
39
- const connection =
40
- options?.connection
41
- || (
42
- mongooseConnections.default ||= mongoose.createConnection(
43
- process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017',
44
- )
45
- );
46
-
38
+ const connection = options?.connection ?? getDefaultMongooseConnection();
47
39
  return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);
48
40
  }
41
+
49
42
  export function registerMongooseNormalizePlugin<
50
43
  DocType,
51
44
  Model extends MongooseModel<DocType, QueryHelpers, InstanceMethodsAndOverrides>,
@@ -0,0 +1,14 @@
1
+ import mongoose from 'mongoose';
2
+ import type { Connection } from 'mongoose';
3
+
4
+ import {
5
+ customMongooseOptions,
6
+ mongooseConnectionState,
7
+ } from './_internals';
8
+
9
+ export function getDefaultMongooseConnection(): Connection {
10
+ return mongooseConnectionState.defaultConnection ||= mongoose.createConnection(
11
+ process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017',
12
+ customMongooseOptions.defaultConnectionOptions,
13
+ );
14
+ }
package/src/options.ts CHANGED
@@ -1,9 +1,16 @@
1
- import { customMongooseOptions } from './_internals';
1
+ import {
2
+ customMongooseOptions,
3
+ mongooseConnectionState,
4
+ } from './_internals';
2
5
  import type { CustomMongooseOptions } from './types/options';
3
6
 
4
7
  export function setCustomMongooseOptions<K extends keyof CustomMongooseOptions>(
5
8
  key: K,
6
9
  value: CustomMongooseOptions[K],
7
10
  ) {
11
+ if (key === 'defaultConnectionOptions' && mongooseConnectionState.defaultConnection) {
12
+ throw new Error('Default connection options must be set before the default connection is created.');
13
+ }
14
+
8
15
  customMongooseOptions[key] = value;
9
16
  }
@@ -8,34 +8,41 @@ import type { Schema } from 'mongoose';
8
8
 
9
9
  export interface MongooseNormalizePluginOptions {
10
10
  /**
11
- * Whether to convert `_id` field to `id`.
12
- * If true, the `_id` field will be replaced with `id`.
11
+ * Whether to move the serialized `_id` value to `id`.
13
12
  *
14
- * @default true
13
+ * @remarks
14
+ * If `false`, preserves the value under `_id` instead. Only values other than `undefined` are copied.
15
+ *
16
+ * @defaultValue `true`.
15
17
  */
16
18
  convertIdField?: boolean;
17
19
 
18
20
  /**
19
- * Whether to convert the `_id` field to a hex string if it's an ObjectId.
21
+ * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
22
+ *
23
+ * @remarks
24
+ * Applies before choosing the `id` or `_id` output key. Identifiers of other types are unchanged.
20
25
  *
21
- * @default true
26
+ * @defaultValue `true`.
22
27
  */
23
28
  toHexIdIfObjectId?: boolean;
24
29
  }
25
30
 
26
31
  /**
27
- * Mongoose plugin to normalize the JSON output of documents.
32
+ * Registers JSON normalization on a Mongoose schema.
28
33
  *
29
- * This plugin modifies the `toJSON` method of Mongoose schemas to:
30
- * - Add an `id` field equal to the string representation of `_id`
31
- * - Remove the `_id` field
32
- * - Exclude fields marked as `private` from the JSON output
33
- * - Convert `Decimal128` fields to strings
34
- * - Remove the `__v` version key
34
+ * @remarks
35
+ * Mutates the schema's `toJSON` configuration while preserving its other options. The transform removes `__v`,
36
+ * normalizes `_id` according to the plugin options, removes schema paths marked `private`, and converts
37
+ * truthy serialized values at registered `Decimal128` paths to strings.
35
38
  *
36
- * @template S - The type of the schema.
39
+ * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
40
+ * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
41
+ * That transform can change the normalized output, and its errors propagate during serialization.
42
+ * This plugin does not configure `toObject` or recursively register itself on child schemas.
37
43
  *
38
- * @param schema - The Mongoose schema to apply the plugin to.
44
+ * @param schema - The schema whose JSON serialization configuration is modified.
45
+ * @param pluginOptions - The identifier normalization options; omitted options use their documented defaults.
39
46
  */
40
47
  export function mongooseNormalizePlugin<S extends Schema>(
41
48
  schema: S,
@@ -87,7 +94,8 @@ export function mongooseNormalizePlugin<S extends Schema>(
87
94
 
88
95
  // Run original toJSON transform
89
96
  if (toJsonTransform && typeof toJsonTransform !== 'boolean') {
90
- return toJsonTransform(doc as any, copiedRet as any, options as any);
97
+ const transformed = toJsonTransform(doc as any, copiedRet as any, options as any);
98
+ return transformed === undefined ? copiedRet : transformed;
91
99
  }
92
100
 
93
101
  // Return normalized object
@@ -5,7 +5,12 @@ type BaseSchemaType =
5
5
  | DateConstructor
6
6
  | NumberConstructor
7
7
  | Schema.Types.ObjectId['constructor']
8
- | StringConstructor;
8
+ | StringConstructor
9
+ | typeof Schema.Types.BigInt
10
+ | typeof Schema.Types.Double
11
+ | typeof Schema.Types.Int32
12
+ | typeof Schema.Types.Mixed
13
+ | typeof Schema.Types.UUID;
9
14
 
10
15
  // Constants/Variables
11
16
  const isFunctionKeys = new Set([
@@ -0,0 +1,134 @@
1
+ import { Schema } from 'mongoose';
2
+ import type {
3
+ DefaultType,
4
+ IndexDirection,
5
+ IndexOptions,
6
+ } from 'mongoose';
7
+ import type { Merge } from 'type-fest';
8
+
9
+ import type { Readonlyable } from '../types/_internals';
10
+
11
+ import { createBaseSchemaBuilderFactory } from './base';
12
+
13
+ type BigIntLimit = bigint;
14
+ type ExtendSchemaBuilder<
15
+ Props extends BaseProps,
16
+ ExtraOmitFields extends string,
17
+ > = Omit<
18
+ BigIntSchemaBuilder<Props, ExtraOmitFields>,
19
+ ExtraOmitFields | keyof Props
20
+ >;
21
+
22
+ interface BaseProps {
23
+ type: typeof Schema.Types.BigInt;
24
+ }
25
+
26
+ interface BigIntLimitValidator {
27
+ max?: bigint;
28
+ message: string;
29
+ min?: bigint;
30
+ type: 'max' | 'min';
31
+ validator: (value: bigint | null | undefined) => boolean;
32
+ }
33
+
34
+ export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
35
+ default: <
36
+ T extends ((this: any, doc: any) => DefaultType<D> | null | undefined) | DefaultType<D> | null | undefined,
37
+ D extends bigint,
38
+ >(value: T) => ExtendSchemaBuilder<
39
+ Merge<Props, { default: T }>,
40
+ ExtraOmitFields
41
+ >;
42
+
43
+ immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;
44
+ index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<
45
+ Merge<Props, { index: T }>,
46
+ ExtraOmitFields
47
+ >;
48
+
49
+ max: <
50
+ T extends L | Readonlyable<[L, S]>,
51
+ L extends BigIntLimit,
52
+ S extends string,
53
+ >(value: T) => ExtendSchemaBuilder<
54
+ Merge<Props, BigIntValidationSchema>,
55
+ 'max' | ExtraOmitFields
56
+ >;
57
+
58
+ min: <
59
+ T extends L | Readonlyable<[L, S]>,
60
+ L extends BigIntLimit,
61
+ S extends string,
62
+ >(value: T) => ExtendSchemaBuilder<
63
+ Merge<Props, BigIntValidationSchema>,
64
+ 'min' | ExtraOmitFields
65
+ >;
66
+
67
+ nonRequired: Props;
68
+ private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;
69
+ required: Merge<Props, { required: true }>;
70
+ sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;
71
+ unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;
72
+ }
73
+
74
+ interface BigIntValidationSchema {
75
+ validate: BigIntLimitValidator[];
76
+ }
77
+
78
+ // Constants/Variables
79
+ const defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';
80
+ const defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';
81
+
82
+ // Functions
83
+ const baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.BigInt);
84
+
85
+ export function bigintSchemaBuilder() {
86
+ const schema: Record<string, any> = {};
87
+ const baseBuilder = baseBuilderFactory(schema);
88
+ return new Proxy(
89
+ baseBuilder,
90
+ {
91
+ get(target, key, receiver) {
92
+ if (key === 'max' || key === 'min') {
93
+ return (value: BigIntLimit | Readonlyable<[BigIntLimit, string]>) => {
94
+ const validator = createLimitValidator(key, value);
95
+ const validators = Array.isArray(schema.validate) ? schema.validate : [];
96
+ schema.validate = [
97
+ ...validators.filter(({ type }) => type !== key),
98
+ validator,
99
+ ];
100
+
101
+ return receiver;
102
+ };
103
+ }
104
+
105
+ return Reflect.get(target, key, receiver);
106
+ },
107
+ },
108
+ ) as BigIntSchemaBuilder;
109
+ }
110
+
111
+ function createLimitValidator(
112
+ type: 'max' | 'min',
113
+ value: BigIntLimit | Readonlyable<[BigIntLimit, string]>,
114
+ ): BigIntLimitValidator {
115
+ const [limit, message] = Array.isArray(value)
116
+ ? value as Readonly<[BigIntLimit, string]>
117
+ : [
118
+ value as BigIntLimit,
119
+ undefined,
120
+ ];
121
+
122
+ if (typeof limit !== 'bigint') throw new TypeError(`BigInt ${type} limit must be a bigint`);
123
+
124
+ return {
125
+ message: message ?? (type === 'min' ? defaultMinValidateMessage : defaultMaxValidateMessage),
126
+ [type]: limit,
127
+ type,
128
+ validator: (value) => {
129
+ if (value === null || value === undefined) return true;
130
+
131
+ return type === 'min' ? value >= limit : value <= limit;
132
+ },
133
+ };
134
+ }
@@ -20,10 +20,7 @@ interface BaseProps {
20
20
  type: BooleanSchemaDefinition;
21
21
  }
22
22
 
23
- export interface BooleanSchemaBuilder<
24
- Props extends BaseProps = BaseProps,
25
- ExtraOmitFields extends string = never,
26
- > {
23
+ export interface BooleanSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
27
24
  default: <
28
25
  T extends ((this: any, doc: any) => DefaultType<D>) | DefaultType<D> | null,
29
26
  D extends boolean,
@@ -86,14 +86,18 @@ export interface Decimal128SchemaBuilder<
86
86
  required: Merge<Props, { required: true }>;
87
87
 
88
88
  /**
89
- * Sets the rounding and toFixed behavior for Decimal128 fields.
90
- * This method allows specifying the number of decimal places and the rounding strategy to be used when
91
- * saving the field to the database.
89
+ * Configures a setter that rounds decimal values and formats them with a fixed number of decimal places.
92
90
  *
93
- * @param places - The number of decimal places to round to (default is 2).
94
- * @param rounding - The rounding strategy from the Decimal.js library (default is Decimal.ROUND_DOWN).
91
+ * @remarks
92
+ * Replaces the configured setter on this builder. The setter converts non-nullish values through Decimal.js
93
+ * and returns a decimal string for Mongoose to cast to `Decimal128`. It returns `undefined` for `null` or
94
+ * `undefined`. Decimal.js validates conversion and formatting when the setter processes a value,
95
+ * not when the setter is configured.
95
96
  *
96
- * @returns A schema builder with the rounding and toFixed behavior applied to the `set` option in Mongoose.
97
+ * @param places - The non-negative integer number of decimal places. Defaults to `2`.
98
+ * @param rounding - The Decimal.js rounding mode. Defaults to `Decimal.ROUND_DOWN`, which rounds toward zero.
99
+ *
100
+ * @returns This instance for chaining.
97
101
  */
98
102
  setRoundAndToFixedSetter: (places?: number, rounding?: Decimal.Rounding) => ExtendSchemaBuilder<
99
103
  Merge<Props, ToStringSetterSchema>,
@@ -101,13 +105,13 @@ export interface Decimal128SchemaBuilder<
101
105
  >;
102
106
 
103
107
  /**
104
- * Sets the toString behavior for Decimal128 fields.
105
- * This method defines how the Decimal128 field should be converted to a string when processing or
106
- * retrieving the value in the application (e.g., via getters), while still storing the value as Decimal128
107
- * in the database.
108
+ * Configures a getter that converts decimal values to strings.
109
+ *
110
+ * @remarks
111
+ * Replaces the configured getter on this builder. The getter returns the value's string representation,
112
+ * or `undefined` for `null` or `undefined`. It changes the read representation, not the stored BSON type.
108
113
  *
109
- * @returns A schema builder with the custom `get` behavior applied to convert the Decimal128 field to a string
110
- * when accessed in the application.
114
+ * @returns This instance for chaining.
111
115
  */
112
116
  setToStringGetter: ExtendSchemaBuilder<Merge<Props, ToStringGetterSchema>, 'setToStringGetter' | ExtraOmitFields>;
113
117
  sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;
@@ -0,0 +1,135 @@
1
+ import { Schema } from 'mongoose';
2
+ import type {
3
+ IndexDirection,
4
+ IndexOptions,
5
+ Types,
6
+ } from 'mongoose';
7
+ import type { Merge } from 'type-fest';
8
+
9
+ import type { Readonlyable } from '../types/_internals';
10
+
11
+ import { createBaseSchemaBuilderFactory } from './base';
12
+
13
+ type DoubleLimit = number | Types.Double;
14
+ type ExtendSchemaBuilder<
15
+ Props extends BaseProps,
16
+ ExtraOmitFields extends string,
17
+ > = Omit<
18
+ DoubleSchemaBuilder<Props, ExtraOmitFields>,
19
+ ExtraOmitFields | keyof Props
20
+ >;
21
+
22
+ interface BaseProps {
23
+ type: typeof Schema.Types.Double;
24
+ }
25
+
26
+ interface DoubleLimitValidator {
27
+ max?: number;
28
+ message: string;
29
+ min?: number;
30
+ type: 'max' | 'min';
31
+ validator: (value: null | Types.Double | undefined) => boolean;
32
+ }
33
+
34
+ export interface DoubleSchemaBuilder<Props extends BaseProps = BaseProps, ExtraOmitFields extends string = never> {
35
+ default: <
36
+ T extends ((this: any, doc: any) => D | null | undefined) | D | null | undefined,
37
+ D extends Types.Double,
38
+ >(value: T) => ExtendSchemaBuilder<
39
+ Merge<Props, { default: T }>,
40
+ ExtraOmitFields
41
+ >;
42
+
43
+ immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;
44
+ index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<
45
+ Merge<Props, { index: T }>,
46
+ ExtraOmitFields
47
+ >;
48
+
49
+ max: <
50
+ T extends L | Readonlyable<[L, S]>,
51
+ L extends DoubleLimit,
52
+ S extends string,
53
+ >(value: T) => ExtendSchemaBuilder<
54
+ Merge<Props, DoubleValidationSchema>,
55
+ 'max' | ExtraOmitFields
56
+ >;
57
+
58
+ min: <
59
+ T extends L | Readonlyable<[L, S]>,
60
+ L extends DoubleLimit,
61
+ S extends string,
62
+ >(value: T) => ExtendSchemaBuilder<
63
+ Merge<Props, DoubleValidationSchema>,
64
+ 'min' | ExtraOmitFields
65
+ >;
66
+
67
+ nonRequired: Props;
68
+ private: ExtendSchemaBuilder<Merge<Props, { private: true }>, ExtraOmitFields>;
69
+ required: Merge<Props, { required: true }>;
70
+ sparse: ExtendSchemaBuilder<Merge<Props, { sparse: true }>, ExtraOmitFields>;
71
+ unique: ExtendSchemaBuilder<Merge<Props, { unique: true }>, ExtraOmitFields>;
72
+ }
73
+
74
+ interface DoubleValidationSchema {
75
+ validate: DoubleLimitValidator[];
76
+ }
77
+
78
+ // Constants/Variables
79
+ const defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';
80
+ const defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';
81
+
82
+ // Functions
83
+ const baseBuilderFactory = createBaseSchemaBuilderFactory(Schema.Types.Double);
84
+
85
+ function createLimitValidator(
86
+ type: 'max' | 'min',
87
+ value: DoubleLimit | Readonlyable<[DoubleLimit, string]>,
88
+ ): DoubleLimitValidator {
89
+ const [limit, message] = Array.isArray(value)
90
+ ? value as Readonly<[DoubleLimit, string]>
91
+ : [
92
+ value as DoubleLimit,
93
+ undefined,
94
+ ];
95
+
96
+ const numericLimit = typeof limit === 'number' ? limit : limit.valueOf();
97
+ if (!Number.isFinite(numericLimit)) throw new RangeError(`Double ${type} limit must be finite`);
98
+
99
+ return {
100
+ message: message ?? (type === 'min' ? defaultMinValidateMessage : defaultMaxValidateMessage),
101
+ [type]: numericLimit,
102
+ type,
103
+ validator: (value) => {
104
+ if (value === null || value === undefined) return true;
105
+
106
+ return type === 'min' ? value.valueOf() >= numericLimit : value.valueOf() <= numericLimit;
107
+ },
108
+ };
109
+ }
110
+
111
+ export function doubleSchemaBuilder() {
112
+ const schema: Record<string, any> = {};
113
+ const baseBuilder = baseBuilderFactory(schema);
114
+ return new Proxy(
115
+ baseBuilder,
116
+ {
117
+ get(target, key, receiver) {
118
+ if (key === 'max' || key === 'min') {
119
+ return (value: DoubleLimit | Readonlyable<[DoubleLimit, string]>) => {
120
+ const validator = createLimitValidator(key, value);
121
+ const validators = Array.isArray(schema.validate) ? schema.validate : [];
122
+ schema.validate = [
123
+ ...validators.filter(({ type }) => type !== key),
124
+ validator,
125
+ ];
126
+
127
+ return receiver;
128
+ };
129
+ }
130
+
131
+ return Reflect.get(target, key, receiver);
132
+ },
133
+ },
134
+ ) as DoubleSchemaBuilder;
135
+ }
@@ -1,3 +1,6 @@
1
+ export { bigintSchemaBuilder as bigint } from './bigint';
2
+ export * from './bigint';
3
+
1
4
  export { booleanSchemaBuilder as boolean } from './boolean';
2
5
  export * from './boolean';
3
6
 
@@ -7,6 +10,15 @@ export * from './date';
7
10
  export { decimal128SchemaBuilder as decimal128 } from './decimal128';
8
11
  export * from './decimal128';
9
12
 
13
+ export { doubleSchemaBuilder as double } from './double';
14
+ export * from './double';
15
+
16
+ export { int32SchemaBuilder as int32 } from './int32';
17
+ export * from './int32';
18
+
19
+ export { mixedSchemaBuilder as mixed } from './mixed';
20
+ export * from './mixed';
21
+
10
22
  export { numberSchemaBuilder as number } from './number';
11
23
  export * from './number';
12
24
 
@@ -18,3 +30,6 @@ export * from './ref';
18
30
 
19
31
  export { stringSchemaBuilder as string } from './string';
20
32
  export * from './string';
33
+
34
+ export { uuidSchemaBuilder as uuid } from './uuid';
35
+ export * from './uuid';