@kikiutils/mongoose 8.0.0 → 9.0.1

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 (65) hide show
  1. package/dist/builders.d.ts +1 -3
  2. package/dist/builders.d.ts.map +1 -1
  3. package/dist/builders.js +6 -6
  4. package/dist/builders.js.map +1 -1
  5. package/dist/plugins/lean-decimal128-to-string.d.ts +26 -0
  6. package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -0
  7. package/dist/plugins/lean-decimal128-to-string.js +85 -0
  8. package/dist/plugins/lean-decimal128-to-string.js.map +1 -0
  9. package/dist/plugins/normalize.d.ts +5 -2
  10. package/dist/plugins/normalize.d.ts.map +1 -1
  11. package/dist/plugins/normalize.js +7 -2
  12. package/dist/plugins/normalize.js.map +1 -1
  13. package/dist/schema-builders/bigint.d.ts +13 -1
  14. package/dist/schema-builders/bigint.d.ts.map +1 -1
  15. package/dist/schema-builders/bigint.js +22 -0
  16. package/dist/schema-builders/bigint.js.map +1 -1
  17. package/dist/schema-builders/date.d.ts +2 -2
  18. package/dist/schema-builders/date.d.ts.map +1 -1
  19. package/dist/schema-builders/date.js.map +1 -1
  20. package/dist/schema-builders/decimal128.d.ts +4 -2
  21. package/dist/schema-builders/decimal128.d.ts.map +1 -1
  22. package/dist/schema-builders/decimal128.js +1 -0
  23. package/dist/schema-builders/decimal128.js.map +1 -1
  24. package/dist/schema-builders/double.d.ts +13 -1
  25. package/dist/schema-builders/double.d.ts.map +1 -1
  26. package/dist/schema-builders/double.js +25 -0
  27. package/dist/schema-builders/double.js.map +1 -1
  28. package/dist/schema-builders/int32.d.ts +13 -1
  29. package/dist/schema-builders/int32.d.ts.map +1 -1
  30. package/dist/schema-builders/int32.js +22 -0
  31. package/dist/schema-builders/int32.js.map +1 -1
  32. package/dist/schema-builders/number.d.ts +2 -2
  33. package/dist/schema-builders/number.d.ts.map +1 -1
  34. package/dist/schema-builders/number.js.map +1 -1
  35. package/dist/schema-builders/object-id.d.ts +2 -2
  36. package/dist/schema-builders/object-id.d.ts.map +1 -1
  37. package/dist/schema-builders/object-id.js.map +1 -1
  38. package/dist/schema-builders/ref.d.ts +2 -2
  39. package/dist/schema-builders/ref.d.ts.map +1 -1
  40. package/dist/schema-builders/ref.js.map +1 -1
  41. package/dist/schema-builders/string.d.ts +2 -2
  42. package/dist/schema-builders/string.d.ts.map +1 -1
  43. package/dist/schema-builders/string.js.map +1 -1
  44. package/dist/types/data.d.ts +2 -1
  45. package/dist/types/data.d.ts.map +1 -1
  46. package/dist/types/index.d.ts +7 -3
  47. package/dist/types/index.d.ts.map +1 -1
  48. package/dist/types/options.d.ts +7 -3
  49. package/dist/types/options.d.ts.map +1 -1
  50. package/package.json +4 -3
  51. package/src/builders.ts +16 -23
  52. package/src/plugins/lean-decimal128-to-string.ts +149 -0
  53. package/src/plugins/normalize.ts +18 -2
  54. package/src/schema-builders/bigint.ts +57 -1
  55. package/src/schema-builders/date.ts +2 -2
  56. package/src/schema-builders/decimal128.ts +5 -2
  57. package/src/schema-builders/double.ts +64 -1
  58. package/src/schema-builders/int32.ts +57 -1
  59. package/src/schema-builders/number.ts +2 -2
  60. package/src/schema-builders/object-id.ts +2 -2
  61. package/src/schema-builders/ref.ts +2 -2
  62. package/src/schema-builders/string.ts +2 -2
  63. package/src/types/data.ts +4 -1
  64. package/src/types/index.ts +16 -2
  65. package/src/types/options.ts +9 -3
@@ -0,0 +1,149 @@
1
+ import type {
2
+ Query,
3
+ Schema,
4
+ SchemaType,
5
+ } from 'mongoose';
6
+
7
+ declare module 'mongoose' {
8
+ interface LeanOptions {
9
+ /** Override conversion of marked Decimal128 fields. Defaults to the plugin's enabledByDefault setting. */
10
+ decimal128ToString?: boolean;
11
+ }
12
+ }
13
+
14
+ type QueryWithOptionalMap = Query<unknown, unknown> & { map?: (transform: (result: unknown) => unknown) => unknown };
15
+
16
+ export interface MongooseLeanDecimal128ToStringPluginOptions {
17
+ /** Whether marked fields are converted on lean queries by default. Defaults to true. */
18
+ enabledByDefault?: boolean;
19
+ }
20
+
21
+ // Constants/Variables
22
+ const registeredSchemas = new WeakSet<Schema>();
23
+
24
+ // Functions
25
+ const isNonNullObject = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object';
26
+
27
+ function convertDocument(schema: Schema, value: unknown) {
28
+ if (!isNonNullObject(value)) return;
29
+ const discriminatorKey = schema.get('discriminatorKey') ?? '__t';
30
+ const discriminatorSchema = Object.values(schema.discriminators ?? {}).find(
31
+ (childSchema) => childSchema.get('discriminatorKey') === discriminatorKey
32
+ && (childSchema as Schema & { discriminatorMapping?: { value: unknown } }).discriminatorMapping?.value
33
+ === value[discriminatorKey],
34
+ );
35
+
36
+ const documentSchema = discriminatorSchema ?? schema;
37
+ documentSchema.eachPath((path, schemaType) => {
38
+ // Maps are handled through their embedded schema type, not their synthetic $* path.
39
+ const pathSegments = path.split('.');
40
+ if (pathSegments.includes('$*')) return;
41
+ convertPath(value, pathSegments, schemaType);
42
+ });
43
+ }
44
+
45
+ function convertPath(value: unknown, pathSegments: string[], schemaType: SchemaType) {
46
+ if (Array.isArray(value)) {
47
+ value.forEach((item) => convertPath(item, pathSegments, schemaType));
48
+ return;
49
+ }
50
+
51
+ if (!isNonNullObject(value)) return;
52
+ const [key, ...remainingPathSegments] = pathSegments;
53
+ if (key === undefined || !Object.hasOwn(value, key)) return;
54
+ if (remainingPathSegments.length) convertPath(value[key], remainingPathSegments, schemaType);
55
+ else value[key] = convertValue(value[key], schemaType);
56
+ }
57
+
58
+ function convertValue(value: unknown, schemaType: SchemaType): unknown {
59
+ if (value === null || value === undefined) return value;
60
+ const embeddedSchemaType = schemaType.getEmbeddedSchemaType();
61
+ if (embeddedSchemaType && Array.isArray(value)) {
62
+ for (let i = 0; i < value.length; i++) {
63
+ if (Object.hasOwn(value, i)) value[i] = convertValue(value[i], embeddedSchemaType);
64
+ }
65
+
66
+ return value;
67
+ }
68
+
69
+ if (embeddedSchemaType && schemaType.instance === 'Map') {
70
+ if (value instanceof Map) value.forEach((item, key) => value.set(key, convertValue(item, embeddedSchemaType)));
71
+ else if (isNonNullObject(value)) {
72
+ for (const key of Object.keys(value)) value[key] = convertValue(value[key], embeddedSchemaType);
73
+ }
74
+
75
+ return value;
76
+ }
77
+
78
+ if (schemaType.schema) {
79
+ convertDocument(schemaType.schema, value);
80
+ return value;
81
+ }
82
+
83
+ if (
84
+ schemaType.instance === 'Decimal128'
85
+ && schemaType.options.leanDecimal128ToString === true
86
+ && isNonNullObject(value)
87
+ && value._bsontype === 'Decimal128'
88
+ && typeof value.toString === 'function'
89
+ ) return value.toString();
90
+
91
+ return value;
92
+ }
93
+
94
+ /**
95
+ * Converts marked Decimal128 fields to strings on lean queries without invoking getters.
96
+ *
97
+ * @remarks
98
+ * `decimal128().setToStringGetter` sets the `leanDecimal128ToString` schema-path option.
99
+ * Query-level `lean({ decimal128ToString: false })` disables this plugin only, not other plugins.
100
+ * Existing strings and nullish values are preserved. Missing/projected-out fields are not added.
101
+ * Supports nested schemas, arrays and maps. Aggregate results are intentionally not transformed.
102
+ * Registration is idempotent; the first registration's default options take precedence.
103
+ * Runtime conversion does not override Mongoose's inferred lean result types.
104
+ */
105
+ export function mongooseLeanDecimal128ToStringPlugin(
106
+ schema: Schema,
107
+ pluginOptions?: MongooseLeanDecimal128ToStringPluginOptions,
108
+ ) {
109
+ if (registeredSchemas.has(schema)) return;
110
+ registeredSchemas.add(schema);
111
+
112
+ function convertResult(query: QueryWithOptionalMap, result: unknown) {
113
+ const leanOptions = query.mongooseOptions().lean;
114
+ if (!leanOptions) return result;
115
+ const conversionEnabled = typeof leanOptions === 'object'
116
+ ? leanOptions.decimal128ToString ?? pluginOptions?.enabledByDefault ?? true
117
+ : pluginOptions?.enabledByDefault ?? true;
118
+
119
+ if (!conversionEnabled) return result;
120
+ const document = query.getOptions().includeResultMetadata && isNonNullObject(result) ? result.value : result;
121
+ const querySchema = query.model.schema;
122
+ if (Array.isArray(document)) document.forEach((value) => convertDocument(querySchema, value));
123
+ else convertDocument(querySchema, document);
124
+ return result;
125
+ }
126
+
127
+ // Find cursors do not run post('find'); match Mongoose's query/cursor transform surfaces.
128
+ schema.pre(
129
+ 'find',
130
+ function (this: QueryWithOptionalMap) {
131
+ const transform = (result: unknown) => convertResult(this, result);
132
+ if (typeof this.map === 'function') this.map(transform);
133
+ else if (typeof this.transform === 'function') this.transform(transform);
134
+ else this.setOptions({ transform });
135
+ },
136
+ );
137
+
138
+ schema.post(
139
+ [
140
+ 'findOne',
141
+ 'findOneAndUpdate',
142
+ 'findOneAndDelete',
143
+ 'findOneAndReplace',
144
+ ],
145
+ function (this: QueryWithOptionalMap, result: unknown) {
146
+ convertResult(this, result);
147
+ },
148
+ );
149
+ }
@@ -17,6 +17,9 @@ export interface MongooseNormalizePluginOptions {
17
17
  */
18
18
  convertIdField?: boolean;
19
19
 
20
+ /** Register normalization on child schemas too. Defaults to true. */
21
+ recursive?: boolean;
22
+
20
23
  /**
21
24
  * Whether to convert a serialized `ObjectId` identifier to its hexadecimal string.
22
25
  *
@@ -28,6 +31,11 @@ export interface MongooseNormalizePluginOptions {
28
31
  toHexIdIfObjectId?: boolean;
29
32
  }
30
33
 
34
+ // Constants/Variables
35
+ const registeredSchemas = new WeakSet<Schema>();
36
+
37
+ // Functions
38
+
31
39
  /**
32
40
  * Registers JSON normalization on a Mongoose schema.
33
41
  *
@@ -39,15 +47,19 @@ export interface MongooseNormalizePluginOptions {
39
47
  * If an existing transform is a function, invokes it after normalization. If it returns `undefined`,
40
48
  * preserves the normalized output and any mutations made by that transform; otherwise, uses its return value.
41
49
  * 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.
50
+ * Registers itself on child schemas unless `recursive` is false. Does not configure `toObject`.
51
+ * Registration is idempotent per schema; the first registration's options take precedence.
43
52
  *
44
53
  * @param schema - The schema whose JSON serialization configuration is modified.
45
- * @param pluginOptions - The identifier normalization options; omitted options use their documented defaults.
54
+ * @param pluginOptions - The normalization and registration options; omitted options use their documented defaults.
46
55
  */
47
56
  export function mongooseNormalizePlugin<S extends Schema>(
48
57
  schema: S,
49
58
  pluginOptions?: MongooseNormalizePluginOptions,
50
59
  ) {
60
+ if (registeredSchemas.has(schema)) return;
61
+ registeredSchemas.add(schema);
62
+
51
63
  // Collect special paths (Decimal128 & private)
52
64
  const decimalPaths: string[] = [];
53
65
  const privatePaths: string[] = [];
@@ -103,4 +115,8 @@ export function mongooseNormalizePlugin<S extends Schema>(
103
115
  },
104
116
  },
105
117
  );
118
+
119
+ if (pluginOptions?.recursive !== false) {
120
+ schema.childSchemas.forEach(({ schema: child }) => child.plugin(mongooseNormalizePlugin, pluginOptions));
121
+ }
106
122
  }
@@ -23,6 +23,13 @@ interface BaseProps {
23
23
  type: typeof Schema.Types.BigInt;
24
24
  }
25
25
 
26
+ interface BigIntEnumValidator {
27
+ enumValues: (bigint | null)[];
28
+ message: string;
29
+ type: 'enum';
30
+ validator: (value: bigint | null | undefined) => boolean;
31
+ }
32
+
26
33
  interface BigIntLimitValidator {
27
34
  max?: bigint;
28
35
  message: string;
@@ -40,6 +47,18 @@ export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
40
47
  ExtraOmitFields
41
48
  >;
42
49
 
50
+ enum: <
51
+ T extends
52
+ | Readonlyable<(N | null)[]>
53
+ | { [path: string]: N | null }
54
+ | { message?: M; values: Readonlyable<(N | null)[]> },
55
+ M extends string,
56
+ N extends bigint,
57
+ >(value: T) => ExtendSchemaBuilder<
58
+ Merge<Props, BigIntValidationSchema>,
59
+ 'enum' | ExtraOmitFields
60
+ >;
61
+
43
62
  immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;
44
63
  index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<
45
64
  Merge<Props, { index: T }>,
@@ -72,10 +91,11 @@ export interface BigIntSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
72
91
  }
73
92
 
74
93
  interface BigIntValidationSchema {
75
- validate: BigIntLimitValidator[];
94
+ validate: (BigIntEnumValidator | BigIntLimitValidator)[];
76
95
  }
77
96
 
78
97
  // Constants/Variables
98
+ const defaultEnumValidateMessage = 'Path `{PATH}` ({VALUE}) is not a valid enum value.';
79
99
  const defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';
80
100
  const defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';
81
101
 
@@ -89,6 +109,42 @@ export function bigintSchemaBuilder() {
89
109
  baseBuilder,
90
110
  {
91
111
  get(target, key, receiver) {
112
+ if (key === 'enum') {
113
+ if (schema.validate?.some(({ type }: { type: string }) => type === 'enum')) {
114
+ throw new Error('Duplicate schema attribute: enum');
115
+ }
116
+
117
+ return (
118
+ value: Readonlyable<(bigint | null)[]>
119
+ | { [path: string]: bigint | null }
120
+ | { message?: string; values: Readonlyable<(bigint | null)[]> },
121
+ ) => {
122
+ let enumValues: (bigint | null)[];
123
+ let message: string | undefined;
124
+
125
+ if (Array.isArray(value)) enumValues = [...value];
126
+ else if ('values' in value && Array.isArray(value.values)) {
127
+ enumValues = [...value.values];
128
+ if ('message' in value && typeof value.message === 'string') message = value.message;
129
+ } else enumValues = Object.values(value);
130
+
131
+ const allowedValues = new Set(enumValues);
132
+ const validator: BigIntEnumValidator = {
133
+ enumValues,
134
+ message: message ?? defaultEnumValidateMessage,
135
+ type: 'enum',
136
+ validator: (value) => value === null || value === undefined || allowedValues.has(value),
137
+ };
138
+
139
+ schema.validate = [
140
+ ...schema.validate ?? [],
141
+ validator,
142
+ ];
143
+
144
+ return receiver;
145
+ };
146
+ }
147
+
92
148
  if (key === 'max' || key === 'min') {
93
149
  return (value: BigIntLimit | Readonlyable<[BigIntLimit, string]>) => {
94
150
  const validator = createLimitValidator(key, value);
@@ -36,9 +36,9 @@ export interface DateSchemaBuilder<
36
36
 
37
37
  enum: <
38
38
  T extends
39
- | Readonlyable<Array<D | null>>
39
+ | Readonlyable<(D | null)[]>
40
40
  | { [path: string]: D | null }
41
- | { message?: M; values: Readonlyable<Array<D | null>> },
41
+ | { message?: M; values: Readonlyable<(D | null)[]> },
42
42
  D extends NativeDate,
43
43
  M extends string,
44
44
  >(value: T) => ExtendSchemaBuilder<
@@ -47,9 +47,9 @@ export interface Decimal128SchemaBuilder<
47
47
 
48
48
  enum: <
49
49
  T extends
50
- | Readonlyable<Array<D | null>>
50
+ | Readonlyable<(D | null)[]>
51
51
  | { [path: string]: D | null }
52
- | { message?: M; values: Readonlyable<Array<D | null>> },
52
+ | { message?: M; values: Readonlyable<(D | null)[]> },
53
53
  D extends Types.Decimal128,
54
54
  M extends string,
55
55
  >(value: T) => ExtendSchemaBuilder<
@@ -110,6 +110,7 @@ export interface Decimal128SchemaBuilder<
110
110
  * @remarks
111
111
  * Replaces the configured getter on this builder. The getter returns the value's string representation,
112
112
  * or `undefined` for `null` or `undefined`. It changes the read representation, not the stored BSON type.
113
+ * Marks this path for the lean Decimal128-to-string plugin; the plugin does not invoke this getter.
113
114
  *
114
115
  * @returns This instance for chaining.
115
116
  */
@@ -124,6 +125,7 @@ interface Decimal128ValidationSchema {
124
125
 
125
126
  interface ToStringGetterSchema {
126
127
  get: (value?: Types.Decimal128) => string | undefined;
128
+ leanDecimal128ToString: true;
127
129
  }
128
130
 
129
131
  interface ToStringSetterSchema {
@@ -199,6 +201,7 @@ export function decimal128SchemaBuilder() {
199
201
 
200
202
  if (key === 'setToStringGetter') {
201
203
  schema.get = (value?: Types.Decimal128) => value?.toString();
204
+ schema.leanDecimal128ToString = true;
202
205
  return receiver;
203
206
  }
204
207
 
@@ -23,6 +23,13 @@ interface BaseProps {
23
23
  type: typeof Schema.Types.Double;
24
24
  }
25
25
 
26
+ interface DoubleEnumValidator {
27
+ enumValues: (null | number | Types.Double)[];
28
+ message: string;
29
+ type: 'enum';
30
+ validator: (value: null | Types.Double | undefined) => boolean;
31
+ }
32
+
26
33
  interface DoubleLimitValidator {
27
34
  max?: number;
28
35
  message: string;
@@ -40,6 +47,18 @@ export interface DoubleSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
40
47
  ExtraOmitFields
41
48
  >;
42
49
 
50
+ enum: <
51
+ T extends
52
+ | Readonlyable<(N | null)[]>
53
+ | { [path: string]: N | null }
54
+ | { message?: M; values: Readonlyable<(N | null)[]> },
55
+ M extends string,
56
+ N extends number | Types.Double,
57
+ >(value: T) => ExtendSchemaBuilder<
58
+ Merge<Props, DoubleValidationSchema>,
59
+ 'enum' | ExtraOmitFields
60
+ >;
61
+
43
62
  immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;
44
63
  index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<
45
64
  Merge<Props, { index: T }>,
@@ -72,10 +91,11 @@ export interface DoubleSchemaBuilder<Props extends BaseProps = BaseProps, ExtraO
72
91
  }
73
92
 
74
93
  interface DoubleValidationSchema {
75
- validate: DoubleLimitValidator[];
94
+ validate: (DoubleEnumValidator | DoubleLimitValidator)[];
76
95
  }
77
96
 
78
97
  // Constants/Variables
98
+ const defaultEnumValidateMessage = 'Path `{PATH}` ({VALUE}) is not a valid enum value.';
79
99
  const defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';
80
100
  const defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';
81
101
 
@@ -115,6 +135,49 @@ export function doubleSchemaBuilder() {
115
135
  baseBuilder,
116
136
  {
117
137
  get(target, key, receiver) {
138
+ if (key === 'enum') {
139
+ if (schema.validate?.some(({ type }: { type: string }) => type === 'enum')) {
140
+ throw new Error('Duplicate schema attribute: enum');
141
+ }
142
+
143
+ return (
144
+ value: Readonlyable<(null | number | Types.Double)[]>
145
+ | { [path: string]: null | number | Types.Double }
146
+ | { message?: string; values: Readonlyable<(null | number | Types.Double)[]> },
147
+ ) => {
148
+ let enumValues: (null | number | Types.Double)[];
149
+ let message: string | undefined;
150
+
151
+ if (Array.isArray(value)) enumValues = [...value];
152
+ else if ('values' in value && Array.isArray(value.values)) {
153
+ enumValues = [...value.values];
154
+ if ('message' in value && typeof value.message === 'string') message = value.message;
155
+ } else enumValues = Object.values(value);
156
+
157
+ const allowedValues = new Set(
158
+ enumValues.map((value) => value === null ? null : value.valueOf()),
159
+ );
160
+
161
+ const validator: DoubleEnumValidator = {
162
+ enumValues,
163
+ message: message ?? defaultEnumValidateMessage,
164
+ type: 'enum',
165
+ validator: (value) => {
166
+ if (value === null || value === undefined) return true;
167
+
168
+ return allowedValues.has(value.valueOf());
169
+ },
170
+ };
171
+
172
+ schema.validate = [
173
+ ...schema.validate ?? [],
174
+ validator,
175
+ ];
176
+
177
+ return receiver;
178
+ };
179
+ }
180
+
118
181
  if (key === 'max' || key === 'min') {
119
182
  return (value: DoubleLimit | Readonlyable<[DoubleLimit, string]>) => {
120
183
  const validator = createLimitValidator(key, value);
@@ -24,6 +24,13 @@ interface BaseProps {
24
24
  type: typeof Schema.Types.Int32;
25
25
  }
26
26
 
27
+ interface Int32EnumValidator {
28
+ enumValues: (null | number)[];
29
+ message: string;
30
+ type: 'enum';
31
+ validator: (value: null | number | undefined) => boolean;
32
+ }
33
+
27
34
  interface Int32LimitValidator {
28
35
  max?: number;
29
36
  message: string;
@@ -41,6 +48,18 @@ export interface Int32SchemaBuilder<Props extends BaseProps = BaseProps, ExtraOm
41
48
  ExtraOmitFields
42
49
  >;
43
50
 
51
+ enum: <
52
+ T extends
53
+ | Readonlyable<(N | null)[]>
54
+ | { [path: string]: N | null }
55
+ | { message?: M; values: Readonlyable<(N | null)[]> },
56
+ M extends string,
57
+ N extends number,
58
+ >(value: T) => ExtendSchemaBuilder<
59
+ Merge<Props, Int32ValidationSchema>,
60
+ 'enum' | ExtraOmitFields
61
+ >;
62
+
44
63
  immutable: ExtendSchemaBuilder<Merge<Props, { immutable: true }>, ExtraOmitFields>;
45
64
  index: <T extends boolean | IndexDirection | IndexOptions>(value: T) => ExtendSchemaBuilder<
46
65
  Merge<Props, { index: T }>,
@@ -73,10 +92,11 @@ export interface Int32SchemaBuilder<Props extends BaseProps = BaseProps, ExtraOm
73
92
  }
74
93
 
75
94
  interface Int32ValidationSchema {
76
- validate: Int32LimitValidator[];
95
+ validate: (Int32EnumValidator | Int32LimitValidator)[];
77
96
  }
78
97
 
79
98
  // Constants/Variables
99
+ const defaultEnumValidateMessage = 'Path `{PATH}` ({VALUE}) is not a valid enum value.';
80
100
  const defaultMinValidateMessage = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';
81
101
  const defaultMaxValidateMessage = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';
82
102
 
@@ -115,6 +135,42 @@ export function int32SchemaBuilder() {
115
135
  baseBuilder,
116
136
  {
117
137
  get(target, key, receiver) {
138
+ if (key === 'enum') {
139
+ if (schema.validate?.some(({ type }: { type: string }) => type === 'enum')) {
140
+ throw new Error('Duplicate schema attribute: enum');
141
+ }
142
+
143
+ return (
144
+ value: Readonlyable<(null | number)[]>
145
+ | { [path: string]: null | number }
146
+ | { message?: string; values: Readonlyable<(null | number)[]> },
147
+ ) => {
148
+ let enumValues: (null | number)[];
149
+ let message: string | undefined;
150
+
151
+ if (Array.isArray(value)) enumValues = [...value];
152
+ else if ('values' in value && Array.isArray(value.values)) {
153
+ enumValues = [...value.values];
154
+ if ('message' in value && typeof value.message === 'string') message = value.message;
155
+ } else enumValues = Object.values(value);
156
+
157
+ const allowedValues = new Set(enumValues);
158
+ const validator: Int32EnumValidator = {
159
+ enumValues,
160
+ message: message ?? defaultEnumValidateMessage,
161
+ type: 'enum',
162
+ validator: (value) => value === null || value === undefined || allowedValues.has(value),
163
+ };
164
+
165
+ schema.validate = [
166
+ ...schema.validate ?? [],
167
+ validator,
168
+ ];
169
+
170
+ return receiver;
171
+ };
172
+ }
173
+
118
174
  if (key === 'max' || key === 'min') {
119
175
  return (value: Int32Limit | Readonlyable<[Int32Limit, string]>) => {
120
176
  const validator = createLimitValidator(key, value);
@@ -36,9 +36,9 @@ export interface NumberSchemaBuilder<
36
36
 
37
37
  enum: <
38
38
  T extends
39
- | Readonlyable<Array<N | null>>
39
+ | Readonlyable<(N | null)[]>
40
40
  | { [path: string]: N | null }
41
- | { message?: M; values: Readonlyable<Array<N | null>> },
41
+ | { message?: M; values: Readonlyable<(N | null)[]> },
42
42
  M extends string,
43
43
  N extends number,
44
44
  >(value: T) => ExtendSchemaBuilder<
@@ -37,9 +37,9 @@ export interface ObjectIdSchemaBuilder<
37
37
 
38
38
  enum: <
39
39
  T extends
40
- | Readonlyable<Array<null | O>>
40
+ | Readonlyable<(null | O)[]>
41
41
  | { [path: string]: null | O }
42
- | { message?: M; values: Readonlyable<Array<null | O>> },
42
+ | { message?: M; values: Readonlyable<(null | O)[]> },
43
43
  M extends string,
44
44
  O extends Types.ObjectId,
45
45
  >(value: T) => ExtendSchemaBuilder<
@@ -38,9 +38,9 @@ export interface RefSchemaBuilder<
38
38
 
39
39
  enum: <
40
40
  T extends
41
- | Readonlyable<Array<null | O>>
41
+ | Readonlyable<(null | O)[]>
42
42
  | { [path: string]: null | O }
43
- | { message?: M; values: Readonlyable<Array<null | O>> },
43
+ | { message?: M; values: Readonlyable<(null | O)[]> },
44
44
  M extends string,
45
45
  O extends Types.ObjectId,
46
46
  >(value: T) => ExtendSchemaBuilder<
@@ -46,9 +46,9 @@ export interface StringSchemaBuilder<
46
46
 
47
47
  enum: <
48
48
  T extends
49
- | Readonlyable<Array<null | S>>
49
+ | Readonlyable<(null | S)[]>
50
50
  | { [path: string]: null | S }
51
- | { message?: M; values: Readonlyable<Array<null | S>> },
51
+ | { message?: M; values: Readonlyable<(null | S)[]> },
52
52
  M extends string,
53
53
  S extends string,
54
54
  >(value: T) => ExtendSchemaBuilder<
package/src/types/data.ts CHANGED
@@ -10,14 +10,17 @@ export type BaseMongooseModelData<CreatedAtField extends boolean = true, Updated
10
10
  & (UpdatedAtField extends true ? { updatedAt: string } : unknown)
11
11
  & { id: string };
12
12
 
13
+ /** Converts data fields to document fields using the same `_id` rules as BaseMongooseDocType. */
13
14
  export type DataToBaseMongooseDocType<
14
15
  T,
15
16
  ObjectIdFields extends keyof T = never,
16
17
  DateFields extends Exclude<keyof T, ObjectIdFields> = never,
17
18
  CreatedAtField extends boolean = true,
18
19
  UpdatedAtField extends boolean = true,
20
+ IdField extends boolean = true,
19
21
  > = BaseMongooseDocType<
20
22
  SetFieldsToObjectId<SetFieldType<T, DateFields, Date>, ObjectIdFields>,
21
23
  CreatedAtField,
22
- UpdatedAtField
24
+ UpdatedAtField,
25
+ IdField
23
26
  >;
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  HydratedDocument,
3
3
  QueryWithHelpers,
4
+ Require_id,
4
5
  Types,
5
6
  } from 'mongoose';
6
7
  import type { SetFieldType } from 'type-fest';
@@ -8,9 +9,22 @@ import type { SetFieldType } from 'type-fest';
8
9
  import type { AggregatePaginateModel } from './aggregate-paginate';
9
10
  import type { PaginateModel } from './paginate';
10
11
 
11
- export type BaseMongooseDocType<T, CreatedAtField extends boolean = true, UpdatedAtField extends boolean = true> =
12
+ /**
13
+ * Raw document type with an ObjectId by default, or the `_id` type declared in T.
14
+ * Set IdField to false for schemas with `_id: false`. Nested fields are left unchanged.
15
+ */
16
+ export type BaseMongooseDocType<
17
+ T,
18
+ CreatedAtField extends boolean = true,
19
+ UpdatedAtField extends boolean = true,
20
+ IdField extends boolean = true,
21
+ > =
12
22
  & (CreatedAtField extends true ? { createdAt: Date } : unknown)
13
- & Omit<T, 'createdAt' | 'id' | 'updatedAt'>
23
+ & (
24
+ IdField extends true
25
+ ? Require_id<Omit<T, 'createdAt' | 'id' | 'updatedAt'>>
26
+ : Omit<T, '_id' | 'createdAt' | 'id' | 'updatedAt'>
27
+ )
14
28
  & (UpdatedAtField extends true ? { updatedAt: Date } : unknown);
15
29
 
16
30
  export type BaseMongoosePaginateModel<RawDocType, InstanceMethodsAndOverrides = object, QueryHelpers = object> =
@@ -5,15 +5,21 @@ import type {
5
5
  SchemaTimestampsConfig,
6
6
  } from 'mongoose';
7
7
 
8
+ import type { MongooseLeanDecimal128ToStringPluginOptions } from '../plugins/lean-decimal128-to-string';
8
9
  import type { MongooseNormalizePluginOptions } from '../plugins/normalize';
9
10
 
10
11
  import type { BaseMongoosePaginateModel } from './';
11
12
 
12
13
  export interface BuildMongooseModelOptions {
13
14
  connection?: Connection;
14
- enableNormalizePlugin?: boolean;
15
- normalizePluginOptions?: MongooseNormalizePluginOptions;
16
- normalizePluginRecursive?: boolean;
15
+ plugins?: {
16
+ /** Register lean conversion for marked Decimal128 fields. Defaults to true. */
17
+ leanDecimal128ToString?: boolean | MongooseLeanDecimal128ToStringPluginOptions;
18
+
19
+ /** Register JSON normalization. Defaults to true; an object enables it with custom options. */
20
+ normalize?: boolean | MongooseNormalizePluginOptions;
21
+ };
22
+
17
23
  timestamps?: boolean | SchemaTimestampsConfig;
18
24
  }
19
25