@palmares/schemas 0.0.1 → 0.1.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 (174) hide show
  1. package/.turbo/turbo-build$colon$watch.log +12 -410
  2. package/CHANGELOG.md +17 -0
  3. package/__tests__/.drizzle/migrations/0000_skinny_harrier.sql +22 -0
  4. package/__tests__/.drizzle/migrations/meta/0000_snapshot.json +156 -0
  5. package/__tests__/.drizzle/migrations/meta/_journal.json +13 -0
  6. package/__tests__/.drizzle/schema.ts +35 -0
  7. package/__tests__/drizzle.config.ts +11 -0
  8. package/__tests__/eslint.config.js +10 -0
  9. package/__tests__/manage.ts +5 -0
  10. package/__tests__/node_modules/.bin/drizzle-kit +17 -0
  11. package/__tests__/node_modules/.bin/esbuild +14 -0
  12. package/__tests__/node_modules/.bin/tsc +17 -0
  13. package/__tests__/node_modules/.bin/tsserver +17 -0
  14. package/__tests__/node_modules/.bin/tsx +17 -0
  15. package/__tests__/package.json +36 -0
  16. package/__tests__/sqlite.db +0 -0
  17. package/__tests__/src/core/array.test.ts +130 -0
  18. package/__tests__/src/core/boolean.test.ts +66 -0
  19. package/__tests__/src/core/datetime.test.ts +102 -0
  20. package/__tests__/src/core/index.ts +35 -0
  21. package/__tests__/src/core/model.test.ts +260 -0
  22. package/__tests__/src/core/models.ts +50 -0
  23. package/__tests__/src/core/numbers.test.ts +177 -0
  24. package/__tests__/src/core/object.test.ts +198 -0
  25. package/__tests__/src/core/string.test.ts +222 -0
  26. package/__tests__/src/core/test.test.ts +59 -0
  27. package/__tests__/src/core/types.test.ts +97 -0
  28. package/__tests__/src/core/union.test.ts +99 -0
  29. package/__tests__/src/settings.ts +71 -0
  30. package/__tests__/tsconfig.json +11 -0
  31. package/dist/cjs/src/adapter/fields/index.js +2 -2
  32. package/dist/cjs/src/adapter/fields/object.js +9 -0
  33. package/dist/cjs/src/adapter/index.js +1 -0
  34. package/dist/cjs/src/constants.js +1 -7
  35. package/dist/cjs/src/domain.js +146 -1
  36. package/dist/cjs/src/index.js +69 -74
  37. package/dist/cjs/src/model.js +206 -206
  38. package/dist/cjs/src/schema/array.js +185 -58
  39. package/dist/cjs/src/schema/boolean.js +105 -44
  40. package/dist/cjs/src/schema/datetime.js +104 -38
  41. package/dist/cjs/src/schema/number.js +134 -114
  42. package/dist/cjs/src/schema/object.js +106 -43
  43. package/dist/cjs/src/schema/schema.js +123 -75
  44. package/dist/cjs/src/schema/string.js +152 -58
  45. package/dist/cjs/src/schema/union.js +412 -290
  46. package/dist/cjs/src/utils.js +42 -15
  47. package/dist/cjs/src/validators/array.js +6 -1
  48. package/dist/cjs/src/validators/boolean.js +2 -0
  49. package/dist/cjs/src/validators/datetime.js +4 -0
  50. package/dist/cjs/src/validators/number.js +12 -40
  51. package/dist/cjs/src/validators/object.js +1 -0
  52. package/dist/cjs/src/validators/schema.js +5 -1
  53. package/dist/cjs/src/validators/string.js +30 -2
  54. package/dist/cjs/src/validators/union.js +5 -4
  55. package/dist/cjs/src/validators/utils.js +99 -27
  56. package/dist/cjs/tsconfig.types.tsbuildinfo +1 -1
  57. package/dist/cjs/types/adapter/fields/array.d.ts +2 -2
  58. package/dist/cjs/types/adapter/fields/array.d.ts.map +1 -1
  59. package/dist/cjs/types/adapter/fields/boolean.d.ts.map +1 -1
  60. package/dist/cjs/types/adapter/fields/datetime.d.ts.map +1 -1
  61. package/dist/cjs/types/adapter/fields/index.d.ts +2 -2
  62. package/dist/cjs/types/adapter/fields/index.d.ts.map +1 -1
  63. package/dist/cjs/types/adapter/fields/number.d.ts.map +1 -1
  64. package/dist/cjs/types/adapter/fields/object.d.ts +2 -1
  65. package/dist/cjs/types/adapter/fields/object.d.ts.map +1 -1
  66. package/dist/cjs/types/adapter/fields/string.d.ts.map +1 -1
  67. package/dist/cjs/types/adapter/fields/union.d.ts.map +1 -1
  68. package/dist/cjs/types/adapter/index.d.ts +1 -0
  69. package/dist/cjs/types/adapter/index.d.ts.map +1 -1
  70. package/dist/cjs/types/adapter/types.d.ts +28 -18
  71. package/dist/cjs/types/adapter/types.d.ts.map +1 -1
  72. package/dist/cjs/types/constants.d.ts +0 -1
  73. package/dist/cjs/types/constants.d.ts.map +1 -1
  74. package/dist/cjs/types/domain.d.ts +5 -4
  75. package/dist/cjs/types/domain.d.ts.map +1 -1
  76. package/dist/cjs/types/index.d.ts +78 -55
  77. package/dist/cjs/types/index.d.ts.map +1 -1
  78. package/dist/cjs/types/model.d.ts +17 -17
  79. package/dist/cjs/types/model.d.ts.map +1 -1
  80. package/dist/cjs/types/schema/array.d.ts +168 -47
  81. package/dist/cjs/types/schema/array.d.ts.map +1 -1
  82. package/dist/cjs/types/schema/boolean.d.ts +103 -44
  83. package/dist/cjs/types/schema/boolean.d.ts.map +1 -1
  84. package/dist/cjs/types/schema/datetime.d.ts +90 -30
  85. package/dist/cjs/types/schema/datetime.d.ts.map +1 -1
  86. package/dist/cjs/types/schema/number.d.ts +133 -125
  87. package/dist/cjs/types/schema/number.d.ts.map +1 -1
  88. package/dist/cjs/types/schema/object.d.ts +104 -35
  89. package/dist/cjs/types/schema/object.d.ts.map +1 -1
  90. package/dist/cjs/types/schema/schema.d.ts +62 -44
  91. package/dist/cjs/types/schema/schema.d.ts.map +1 -1
  92. package/dist/cjs/types/schema/string.d.ts +152 -65
  93. package/dist/cjs/types/schema/string.d.ts.map +1 -1
  94. package/dist/cjs/types/schema/types.d.ts +11 -2
  95. package/dist/cjs/types/schema/types.d.ts.map +1 -1
  96. package/dist/cjs/types/schema/union.d.ts +133 -40
  97. package/dist/cjs/types/schema/union.d.ts.map +1 -1
  98. package/dist/cjs/types/types.d.ts +35 -0
  99. package/dist/cjs/types/types.d.ts.map +1 -1
  100. package/dist/cjs/types/utils.d.ts +41 -27
  101. package/dist/cjs/types/utils.d.ts.map +1 -1
  102. package/dist/cjs/types/validators/array.d.ts.map +1 -1
  103. package/dist/cjs/types/validators/boolean.d.ts.map +1 -1
  104. package/dist/cjs/types/validators/datetime.d.ts.map +1 -1
  105. package/dist/cjs/types/validators/number.d.ts +5 -6
  106. package/dist/cjs/types/validators/number.d.ts.map +1 -1
  107. package/dist/cjs/types/validators/object.d.ts.map +1 -1
  108. package/dist/cjs/types/validators/schema.d.ts +2 -2
  109. package/dist/cjs/types/validators/schema.d.ts.map +1 -1
  110. package/dist/cjs/types/validators/string.d.ts +9 -9
  111. package/dist/cjs/types/validators/string.d.ts.map +1 -1
  112. package/dist/cjs/types/validators/utils.d.ts +44 -27
  113. package/dist/cjs/types/validators/utils.d.ts.map +1 -1
  114. package/dist/esm/src/adapter/fields/index.js +2 -2
  115. package/dist/esm/src/adapter/fields/object.js +6 -0
  116. package/dist/esm/src/adapter/index.js +1 -0
  117. package/dist/esm/src/constants.js +1 -2
  118. package/dist/esm/src/domain.js +11 -1
  119. package/dist/esm/src/index.js +38 -73
  120. package/dist/esm/src/model.js +83 -78
  121. package/dist/esm/src/schema/array.js +136 -54
  122. package/dist/esm/src/schema/boolean.js +98 -44
  123. package/dist/esm/src/schema/datetime.js +91 -38
  124. package/dist/esm/src/schema/number.js +127 -110
  125. package/dist/esm/src/schema/object.js +98 -43
  126. package/dist/esm/src/schema/schema.js +102 -67
  127. package/dist/esm/src/schema/string.js +147 -59
  128. package/dist/esm/src/schema/union.js +119 -40
  129. package/dist/esm/src/types.js +14 -1
  130. package/dist/esm/src/utils.js +56 -27
  131. package/dist/esm/src/validators/array.js +6 -1
  132. package/dist/esm/src/validators/boolean.js +2 -0
  133. package/dist/esm/src/validators/datetime.js +4 -0
  134. package/dist/esm/src/validators/number.js +9 -23
  135. package/dist/esm/src/validators/object.js +1 -0
  136. package/dist/esm/src/validators/schema.js +5 -1
  137. package/dist/esm/src/validators/string.js +30 -2
  138. package/dist/esm/src/validators/union.js +5 -4
  139. package/dist/esm/src/validators/utils.js +62 -36
  140. package/package.json +3 -3
  141. package/src/adapter/fields/array.ts +2 -2
  142. package/src/adapter/fields/boolean.ts +3 -8
  143. package/src/adapter/fields/datetime.ts +3 -9
  144. package/src/adapter/fields/index.ts +11 -11
  145. package/src/adapter/fields/number.ts +3 -9
  146. package/src/adapter/fields/object.ts +13 -10
  147. package/src/adapter/fields/string.ts +3 -9
  148. package/src/adapter/fields/union.ts +3 -9
  149. package/src/adapter/index.ts +1 -0
  150. package/src/adapter/types.ts +60 -45
  151. package/src/constants.ts +1 -3
  152. package/src/domain.ts +15 -1
  153. package/src/index.ts +189 -211
  154. package/src/model.ts +119 -115
  155. package/src/schema/array.ts +274 -90
  156. package/src/schema/boolean.ts +145 -60
  157. package/src/schema/datetime.ts +133 -49
  158. package/src/schema/number.ts +210 -173
  159. package/src/schema/object.ts +167 -74
  160. package/src/schema/schema.ts +205 -126
  161. package/src/schema/string.ts +221 -94
  162. package/src/schema/types.ts +44 -16
  163. package/src/schema/union.ts +193 -68
  164. package/src/types.ts +53 -0
  165. package/src/utils.ts +115 -57
  166. package/src/validators/array.ts +46 -27
  167. package/src/validators/boolean.ts +13 -7
  168. package/src/validators/datetime.ts +24 -16
  169. package/src/validators/number.ts +53 -63
  170. package/src/validators/object.ts +6 -5
  171. package/src/validators/schema.ts +33 -25
  172. package/src/validators/string.ts +122 -59
  173. package/src/validators/union.ts +8 -8
  174. package/src/validators/utils.ts +67 -42
@@ -3,24 +3,30 @@ import type { ErrorCodes } from '../adapter/types';
3
3
  import type Schema from '../schema/schema';
4
4
  import type { ValidationFallbackCallbackReturnType, ValidationFallbackCallbackType, ValidationFallbackReturnType } from '../schema/types';
5
5
  /**
6
- * Okay, so what is this? This is a validator class, it represents a Node on a linked list. The linked list has lower priority validators on the end of the list and higher
7
- * priority validators on the start of the list. Maybe in the future we can change that to a binary tree, but for now this is enough.
6
+ * Okay, so what is this? This is a validator class, it represents a Node on a linked list. The linked list
7
+ * has lower priority validators on the end of the list and higher priority validators on the start of the
8
+ * list. Maybe in the future we can change that to a binary tree, but for now this is enough.
8
9
  *
9
- * Why did we choose this approach? Because what i was doing was that i saw myself repeating the same code 3 times on the schema in order to make the validation work. Each validator had
10
- * a different return type, i didn't like that. I wanted to add more power and control on the validator, not on the schema. So i created this class. So pretty much, over here and
11
- * on each validator we can define the type it is. It can actually be three: `low`, `medium` and `high`. The `low` validators are the ones that are going to be executed last, the `high` validators
12
- * are the ones that are going to be executed first. High validators validate if the value is null or undefined, if it allows that. It can stop the execution of the other validators if it wants to.
10
+ * Why did we choose this approach? Because what i was doing was that i saw myself repeating the same code 3
11
+ * times on the schema in order to make the validation work. Each validator had a different return type, i
12
+ * didn't like that. I wanted to add more power and control on the validator, not on the schema. So i created
13
+ * this class. So pretty much, over here and on each validator we can define the type it is. It can actually
14
+ * be three: `low`, `medium` and `high`. The `low` validators are the ones that are going to be executed last,
15
+ * The `high` validators are the ones that are going to be executed first. High validators validate if the value
16
+ * is null or undefined, if it allows that. It can stop the execution of the other validators if it wants to.
13
17
  *
14
- * Example: Let's say that the value is null, if the value is null, is there a reason to check if it's a number? No, right? So the high validator can stop the execution of the other validators.
15
- * Same as before, if the value is not a number, is there a reason to check if it's value is greater than the `max` allowed 10? No, right? So the medium validator can stop the execution of
16
- * the other validators.
18
+ * Example: Let's say that the value is null, if the value is null, is there a reason to check if it's a number?
19
+ * No, right? So the high validator can stop the execution of the other validators.
20
+ * Same as before, if the value is not a number, is there a reason to check if it's value is greater than the
21
+ * `max` allowed 10? No, right? So the medium validator can stop the execution of the other validators.
17
22
  *
18
- * That's what this solve, it's a better approach than repeating the same code 3 times on the schema. It's also more powerful, because if we need to add any extra priorities we can do that easily
19
- * without changing the schema.
23
+ * That's what this solve, it's a better approach than repeating the same code 3 times on the schema. It's also
24
+ * more powerful, because if we need to add any extra priorities we can do that easily without changing the schema.
20
25
  */
21
26
  export default class Validator {
22
27
  child?: Validator;
23
28
  parent?: Validator;
29
+ fallbackNamesAdded: Set<unknown>;
24
30
  priority: number;
25
31
  fallbacks: ((value: any, path: (string | number)[], options: Parameters<Schema['__transformToAdapter']>[0]) => Promise<{
26
32
  parsed: any;
@@ -34,15 +40,21 @@ export default class Validator {
34
40
  }>)[];
35
41
  constructor(type: ValidatorTypes);
36
42
  /**
37
- * We create all of the validators on the schema in order, i actually didn't want to go on that route but i found it easier to do so.
43
+ * We create all of the validators on the schema in order, i actually didn't want to go on that route but i
44
+ * found it easier to do so.
38
45
  *
39
- * The logic here is simple, if it's not the same priority we will walk on the linked list until we find a validator that matches the priority we are expecting. If we can't walk anymore, we create
40
- * the next priority validator and append it to the linked list. Be aware that it's a double linked list, so we can walk both ways, from the end to the start and from the start to the end.
41
- * So you don't really need to start from the root, the linked list can start from anywhere and it will find it's way through.
46
+ * The logic here is simple, if it's not the same priority we will walk on the linked list until we find
47
+ * a validator that matches the priority we are expecting. If we can't walk anymore, we create the next
48
+ * priority validator and append it to the linked list. Be aware that it's a double linked list, so we
49
+ * can walk both ways, from the end to the start and from the start to the end.
50
+ * So you don't really need to start from the root, the linked list can start from anywhere and it will
51
+ * find it's way through.
42
52
  *
43
- * I know there are better ways to do this instead of walking through the linked list, but like i explained before, this is enough for now.
53
+ * I know there are better ways to do this instead of walking through the linked list, but like i explained
54
+ * before, this is enough for now.
44
55
  *
45
- * If the priority is higher than the current priority saved on the schema, we should substitute the rootValidator on the schema with the new one.
56
+ * If the priority is higher than the current priority saved on the schema, we should substitute the
57
+ * rootValidator on the schema with the new one.
46
58
  *
47
59
  * @param schema - The schema that we are working on right now, all fallbacks are tied to that specific schema.
48
60
  * @param type - The type of the fallback that we are adding.
@@ -51,12 +63,14 @@ export default class Validator {
51
63
  * @param options - The options that we are passing to the fallback.
52
64
  */
53
65
  private checkAppendOrCreate;
54
- addFallback(schema: Schema, type: ValidatorTypes, fallback: ValidationFallbackCallbackType, options?: Parameters<(typeof Validator)['createAndAppendFallback']>[2]): void;
66
+ addFallback(schema: Schema, type: ValidatorTypes, fallbackName: string, fallback: ValidationFallbackCallbackType, options?: Parameters<(typeof Validator)['createAndAppendFallback']>[2]): void;
55
67
  /**
56
- * Validates the value against all of the fallbacks, the fallbacks are executed in order, from the highest priority to the lowest priority.
57
- * A validator can stop the execution of the other validators if it feels like so. Like on the example of a value being null or undefined.
68
+ * Validates the value against all of the fallbacks, the fallbacks are executed in order, from the highest
69
+ * priority to the lowest priority. A validator can stop the execution of the other validators if it feels
70
+ * like so. Like on the example of a value being null or undefined.
58
71
  *
59
- * @param errorsAsHashedSet - This is a set that contains all of the errors that we already found, this is used to avoid duplicated errors.
72
+ * @param errorsAsHashedSet - This is a set that contains all of the errors that we already found, this is
73
+ * used to avoid duplicated errors.
60
74
  * @param path - The path that we are validating right now.
61
75
  * @param parseResult - The result of the parsing, it contains the parsed value and the errors that we found.
62
76
  * @param options - The options that we are passing to the fallback.
@@ -66,13 +80,16 @@ export default class Validator {
66
80
  parsed: any;
67
81
  }, options: Parameters<Schema['__transformToAdapter']>[0]): Promise<ValidationFallbackCallbackReturnType>;
68
82
  /**
69
- * This static method takes care of everything for you. This means that you should only call this method for appending new fallbacks, it takes care of creating the root validator
70
- * and making sure that the rootValidator on the schema is the highest priority one.
83
+ * This static method takes care of everything for you. This means that you should only call this method
84
+ * for appending new fallbacks, it takes care of creating the root validator and making sure that the
85
+ * rootValidator on the schema is the highest priority one.
71
86
  *
72
- * @param schema - The schema that we are working on right now, all fallbacks are tied to that specific schema. We automatically define the rootValidator on the schema
73
- * so you don't need to worry about that.
74
- * @param fallback - The fallback that we are adding. This is an object that contains the type of the fallback and the callback that we are adding.
75
- * @param options - The options that we are passing to the fallback. Options like `at` and `removeCurrent` are passed to the `addFallback` method.
87
+ * @param schema - The schema that we are working on right now, all fallbacks are tied to that specific
88
+ * schema. We automatically define the rootValidator on the schema so you don't need to worry about that.
89
+ * @param fallback - The fallback that we are adding. This is an object that contains the type of the
90
+ * fallback and the callback that we are adding.
91
+ * @param options - The options that we are passing to the fallback. Options like `at` and `removeCurrent`
92
+ * are passed to the `addFallback` method.
76
93
  */
77
94
  static createAndAppendFallback(schema: Schema<any, any>, fallback: ValidationFallbackReturnType, options?: {
78
95
  at?: number;
@@ -1 +1 @@
1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AM,CAAC,GAAG,EAAE,GAAG,CAAC,EACxB,QAAQ,EAAE,4BAA4B,EACtC,OAAO,CAAC,EAAE;QACR,EAAE,CAAC,EAAE,MAAM,CAAC;QACZ,aAAa,CAAC,EAAE,OAAO,CAAC;KACzB;IAcH,QAAQ,CAAC,KAAK,SAAI,GAAG,MAAM;CAK5B"}
@@ -15,7 +15,7 @@ export default class FieldAdapter {
15
15
  functionName: 'translate'
16
16
  });
17
17
  }
18
- parse(_adapter, _fieldAdapter, _result, _value, _args) {
18
+ parse(_adapter, _fieldAdapter, _schema, _value, _args) {
19
19
  throw new SchemaAdapterNotImplementedError({
20
20
  className: this.constructor.name,
21
21
  functionName: 'parse'
@@ -28,7 +28,7 @@ export default class FieldAdapter {
28
28
  });
29
29
  }
30
30
  // eslint-disable-next-line ts/require-await
31
- async formatError(_adapter, _fieldAdapter, _error, _metadata) {
31
+ async formatError(_adapter, _fieldAdapter, _schema, _error, _metadata) {
32
32
  throw new SchemaAdapterNotImplementedError({
33
33
  className: this.constructor.name,
34
34
  functionName: 'formatError'
@@ -17,4 +17,10 @@ export default class ObjectFieldAdapter extends FieldAdapter {
17
17
  functionName: 'parse'
18
18
  });
19
19
  }
20
+ toString(_adapter, _fieldAdapter, _args, _base) {
21
+ throw new SchemaAdapterNotImplementedError({
22
+ className: this.constructor.name,
23
+ functionName: 'toString'
24
+ });
25
+ }
20
26
  }
@@ -8,6 +8,7 @@ export default class SchemaAdapter {
8
8
  array;
9
9
  boolean;
10
10
  datetime;
11
+ adapterInstance;
11
12
  // eslint-disable-next-line ts/require-await
12
13
  async formatError(_error, _metadata) {
13
14
  throw new SchemaAdapterNotImplementedError({
@@ -1,5 +1,4 @@
1
1
  export const DEFAULT_NUMBER_MAX_EXCEPTION = (max, inclusive)=>`The number is greater than the allowed ${max}.${inclusive ? ` The value ${max} is accepted as well.` : ''}`;
2
2
  export const DEFAULT_NUMBER_MIN_EXCEPTION = (min, inclusive)=>`The number is less than the allowed ${min}.${inclusive ? ` The value ${min} is accepted as well.` : ''}`;
3
- export const DEFAULT_NUMBER_NEGATIVE_EXCEPTION = (allowZero)=>`The number should be negative.${allowZero ? ` The value 0 is accepted as well.` : ''}`;
4
3
  export const DEFAULT_NUMBER_POSITIVE_EXCEPTION = (allowZero)=>`The number should be positive.${allowZero ? ` The value 0 is accepted as well.` : ''}`;
5
- export const DEFAULT_NUMBER_INTEGER_EXCEPTION = ()=>`THe number should be an integer.`;
4
+ export const DEFAULT_NUMBER_INTEGER_EXCEPTION = ()=>`The number should be an integer.`;
@@ -1,2 +1,12 @@
1
1
  import { domain } from '@palmares/core';
2
- export default domain('@palmares/schemas', __dirname, {});
2
+ import { getDefaultAdapter, setDefaultAdapter } from './conf';
3
+ const schemasDomain = domain('@palmares/schemas', __dirname, {
4
+ commands: {},
5
+ // eslint-disable-next-line ts/require-await
6
+ load: async (settings)=>{
7
+ setDefaultAdapter(new settings.schemaAdapter());
8
+ const schemaAdapter = getDefaultAdapter();
9
+ return undefined;
10
+ }
11
+ });
12
+ export default schemasDomain;
@@ -1,4 +1,5 @@
1
1
  import SchemaAdapter from './adapter';
2
+ import SchemaDomain from './domain';
2
3
  import { modelSchema } from './model';
3
4
  import ArraySchema, { array } from './schema/array';
4
5
  import BooleanSchema, { boolean } from './schema/boolean';
@@ -8,22 +9,23 @@ import ObjectSchema, { object } from './schema/object';
8
9
  import Schema, { schema } from './schema/schema';
9
10
  import StringSchema, { string } from './schema/string';
10
11
  import UnionSchema, { union } from './schema/union';
11
- export { default as default } from './domain';
12
- export { default as FieldAdapter } from './adapter/fields';
13
- export { default as NumberAdapter } from './adapter/fields/number';
14
- export { default as ObjectFieldAdapter } from './adapter/fields/object';
15
- export { default as UnionFieldAdapter } from './adapter/fields/union';
16
- export { default as StringFieldAdapter } from './adapter/fields/string';
17
- export { default as ArrayFieldAdapter } from './adapter/fields/array';
18
- export { default as BooleanFieldAdapter } from './adapter/fields/boolean';
19
- export { default as DatetimeFieldAdapter } from './adapter/fields/datetime';
20
- export { setDefaultAdapter } from './conf';
12
+ export { default as FieldAdapter, fieldAdapter } from './adapter/fields';
13
+ export { default as NumberFieldAdapter, numberFieldAdapter } from './adapter/fields/number';
14
+ export { default as ObjectFieldAdapter, objectFieldAdapter } from './adapter/fields/object';
15
+ export { default as UnionFieldAdapter, unionFieldAdapter } from './adapter/fields/union';
16
+ export { default as StringFieldAdapter, stringFieldAdapter } from './adapter/fields/string';
17
+ export { default as ArrayFieldAdapter, arrayFieldAdapter } from './adapter/fields/array';
18
+ export { default as BooleanFieldAdapter, booleanFieldAdapter } from './adapter/fields/boolean';
19
+ export { default as DatetimeFieldAdapter, datetimeFieldAdapter } from './adapter/fields/datetime';
20
+ export { Infer as infer } from './types';
21
+ export { setDefaultAdapter, getDefaultAdapter } from './conf';
21
22
  export * from './adapter/types';
22
23
  export * from './schema';
23
24
  export { SchemaAdapter, NumberSchema, ObjectSchema, UnionSchema, StringSchema, ArraySchema, BooleanSchema, DatetimeSchema, Schema };
24
25
  export { schema, number, object, union, string, array, datetime, boolean };
25
26
  export { default as compile } from './compile';
26
27
  export { modelSchema };
28
+ export default SchemaDomain;
27
29
  export function getSchemasWithDefaultAdapter() {
28
30
  return {
29
31
  number: ()=>NumberSchema.new(),
@@ -34,22 +36,23 @@ export function getSchemasWithDefaultAdapter() {
34
36
  union: (...schemas)=>UnionSchema.new(schemas),
35
37
  datetime: ()=>DatetimeSchema.new(),
36
38
  /**
37
- * Different from other models, this function is a factory function that returns either an ObjectSchema or an ArraySchema.
39
+ * Different from other models, this function is a factory function that returns either an ObjectSchema or
40
+ * an ArraySchema.
38
41
  * The idea is to build the schema of a model dynamically based on its fields.
39
42
  *
40
- * Another feature is that it can automatically add the foreign key relation to the schema, but for that you need to define
41
- * the fields of the related model in the fields object.
43
+ * Another feature is that it can automatically add the foreign key relation to the schema,
44
+ * but for that you need to define the fields of the related model in the fields object.
42
45
  *
43
- * For example: A User model have a field `companyId` that is a ForeignKeyField to the Company model. The `relationName`
44
- * is the direct relation from the User model to the Company model, and the `relatedName` is the reverse relation from the
45
- * Company model to the User model. If you define the fieldName as either the relatedName or the relationName it will fetch
46
- * the data automatically.
46
+ * For example: A User model have a field `companyId` that is a ForeignKeyField to the Company model.
47
+ * The `relationName` is the direct relation from the User model to the Company model, and the `relatedName`
48
+ * is the reverse relation from the Company model to the User model. If you define the fieldName as either
49
+ * the relatedName or the relationName it will fetch the data automatically.
47
50
  *
48
- * **Important**: We build the schema dynamically but also lazily, if you don't try to parse or validate the schema, it won't be built.
49
- * After the first time it's built, it's cached and never built again.
51
+ * **Important**: We build the schema dynamically but also lazily, if you don't try to parse or validate the
52
+ * schema, it won't be built. After the first time it's built, it's cached and never built again.
50
53
  *
51
- * **Important 2**: If you want to use the automatic relation feature, you need to define guarantee that the foreignKey field fieldName
52
- * exists on `show` array, or that it doesn't exist on `omit` array.
54
+ * **Important 2**: If you want to use the automatic relation feature, you need to define guarantee that the
55
+ * foreignKey field fieldName exists on `show` array, or that it doesn't exist on `omit` array.
53
56
  *
54
57
  * Like: `{ options: { show: ['id', 'name', 'companyId'] }}` or `{ options: { omit: ['id'] }}` it **will work**.
55
58
  *
@@ -104,57 +107,19 @@ export function getSchemasWithDefaultAdapter() {
104
107
  * show: ['id', 'type']
105
108
  * });
106
109
  *```
107
- * @param model - The model that you want to build the schema from.
108
- * @param options - The options to build the schema.
109
- * @param options.ignoreExtraneousFields - If you want to ignore extraneous fields set this to true.
110
- * @param options.engineInstance - What engine instance you want to use to fetch the data. Defaults to the first one.
111
- * @param options.fields - Extra fields that you want to add to the schema. If it has the same name as the model field,
112
- * We will not create a schema for that field and use the one you have defined here.
113
- * @param options.omit - Fields that you want to omit from the schema. If that is defined, we ignore `show` option.
114
- * @param options.show - Fields that you want to show on the schema. If that is defined, we ignore `omit` option.
115
- * @param options.many - If you want to return an array instead of an object, set this to true. With that we create
116
- * an ArraySchema instead of an ObjectSchema.
117
- *
118
- * @returns - If you pass the `many` option as true, we return an ArraySchema, otherwise we return an ObjectSchema.
119
- */ modelSchema: (model, options)=>modelSchema(model, options)
110
+ * @param model - The model that you want to build the schema from.
111
+ * @param options - The options to build the schema.
112
+ * @param options.ignoreExtraneousFields - If you want to ignore extraneous fields set this to true.
113
+ * @param options.engineInstance - What engine instance you want to use to fetch the data.
114
+ * Defaults to the first one.
115
+ * @param options.fields - Extra fields that you want to add to the schema. If it has the same name as the
116
+ * model field, We will not create a schema for that field and use the one you have defined here.
117
+ * @param options.omit - Fields that you want to omit from the schema. If that is defined, we ignore `show` option.
118
+ * @param options.show - Fields that you want to show on the schema. If that is defined, we ignore `omit` option.
119
+ * @param options.many - If you want to return an array instead of an object, set this to true. With that we create
120
+ * an ArraySchema instead of an ObjectSchema.
121
+ *
122
+ * @returns - If you pass the `many` option as true, we return an ArraySchema, otherwise we return an ObjectSchema.
123
+ */ modelSchema: (model, options)=>modelSchema(model, options)
120
124
  };
121
- } /*
122
- export class User extends Model<User>() {
123
- fields = {
124
- id: AutoField.new(),
125
- uuid: UuidField.new({
126
- autoGenerate: true
127
- }),
128
- name: CharField.new({ maxLength: 255, dbIndex: true, allowNull: true }),
129
- age: IntegerField.new({ dbIndex: true }),
130
- userType: EnumField.new({ choices: ['admin', 'user'], defaultValue: 'admin' }),
131
- price: DecimalField.new({ maxDigits: 5, decimalPlaces: 2, allowNull: true }),
132
- isActive: BooleanField.new({ defaultValue: true }),
133
- companyId: ForeignKeyField.new({
134
- onDelete: ON_DELETE.CASCADE,
135
- relatedName: 'usersOfCompany',
136
- relationName: 'company',
137
- toField: 'id',
138
- relatedTo: Company
139
- }),
140
- updatedAt: DateField.new({ autoNow: true }),
141
- createdAt: DateField.new({ autoNowAdd: true }),
142
- }
143
-
144
- options: ModelOptionsType<User> = {
145
- tableName: 'users',
146
- }
147
- }
148
-
149
- export class Company extends Model<Company>() {
150
- fields = {
151
- id: AutoField.new(),
152
- name: CharField.new({ maxLength: 255 }),
153
- address: CharField.new({ maxLength: 255, allowNull: true }),
154
- }
155
-
156
- options: ModelOptionsType<Company> = {
157
- tableName: 'companies',
158
- }
159
125
  }
160
- */
@@ -84,22 +84,22 @@ async function getSchemaFromModelField(model, field, parent, definedFields, engi
84
84
  return schema || string();
85
85
  }
86
86
  /**
87
- * Different from other schemas, this function is a factory function that returns either an ObjectSchema or an ArraySchema.
88
- * The idea is to build the schema of a model dynamically based on its fields.
87
+ * Different from other schemas, this function is a factory function that returns either an ObjectSchema or an
88
+ * ArraySchema. The idea is to build the schema of a model dynamically based on its fields.
89
89
  *
90
- * Another feature is that it can automatically add the foreign key relation to the schema, but for that you need to define
91
- * the fields of the related model in the fields object.
90
+ * Another feature is that it can automatically add the foreign key relation to the schema, but for that you need to
91
+ * define the fields of the related model in the fields object.
92
92
  *
93
93
  * For example: A User model have a field `companyId` that is a ForeignKeyField to the Company model. The `relationName`
94
- * is the direct relation from the User model to the Company model, and the `relatedName` is the reverse relation from the
95
- * Company model to the User model. If you define the fieldName as either the relatedName or the relationName it will fetch
96
- * the data automatically.
94
+ * is the direct relation from the User model to the Company model, and the `relatedName` is the reverse relation from
95
+ * the Company model to the User model. If you define the fieldName as either the relatedName or the relationName it
96
+ * will fetch the data automatically.
97
97
  *
98
- * **Important**: We build the schema dynamically but also lazily, if you don't try to parse or validate the schema, it won't be built.
99
- * After the first time it's built, it's cached and never built again.
98
+ * **Important**: We build the schema dynamically but also lazily, if you don't try to parse or validate the schema, it
99
+ * won't be built. After the first time it's built, it's cached and never built again.
100
100
  *
101
- * **Important 2**: If you want to use the automatic relation feature, you need to define guarantee that the foreignKey field fieldName
102
- * exists on `show` array, or that it doesn't exist on `omit` array.
101
+ * **Important 2**: If you want to use the automatic relation feature, you need to define guarantee that the foreignKey
102
+ * field fieldName exists on `show` array, or that it doesn't exist on `omit` array.
103
103
  *
104
104
  * Like: `{ options: { show: ['id', 'name', 'companyId'] }}` or `{ options: { omit: ['id'] }}` it **will work**.
105
105
  *
@@ -152,16 +152,16 @@ async function getSchemaFromModelField(model, field, parent, definedFields, engi
152
152
  * fields: {
153
153
  * usersOfCompany: p.modelSchema(User, { many: true }).optional({ outputOnly: true });
154
154
  * },
155
- * show: ['id', 'type'] // The `companyId` field on the 'User' model is tied to the `id` field on the 'Company' model so 'id' is required.
156
- * });
155
+ * // The `companyId` field on the 'User' model is tied to the `id` field on the 'Company' model so 'id' is required.
156
+ * show: ['id', 'type'] * });
157
157
  *```
158
158
  * @param model - The model that you want to build the schema from.
159
159
  * @param options - The options to build the schema.
160
160
  * @param options.ignoreExtraneousFields - If you want to ignore extraneous fields set this to true.
161
161
  * @param options.engineInstance - What engine instance you want to use to fetch the data. Defaults to the first one.
162
- * @param options.omitRelation - Fields that you want to omit from the relation. For example, on the example above, on the
163
- * `userSchema` you can omit the `companyId` field from the relation by just passing `['company']`, on the `companySchema`
164
- * you can omit the `id` field from company by passing `['usersOfCompany']`.
162
+ * @param options.omitRelation - Fields that you want to omit from the relation. For example, on the example above, on
163
+ * the `userSchema` you can omit the `companyId` field from the relation by just passing `['company']`, on the
164
+ * `companySchema` you can omit the `id` field from company by passing `['usersOfCompany']`.
165
165
  *
166
166
  * @param options.fields - Extra fields that you want to add to the schema. If it has the same name as the model field,
167
167
  * We will not create a schema for that field and use the one you have defined here.
@@ -187,68 +187,73 @@ async function getSchemaFromModelField(model, field, parent, definedFields, engi
187
187
  lazyModelSchema.__model = model;
188
188
  // Add this callback to transform the model fields
189
189
  parentSchema.__runBeforeParseAndData = async ()=>{
190
- if (parentSchema.__alreadyAppliedModel) return;
191
- parentSchema.__alreadyAppliedModel = true;
192
- const fieldsOfModels = model._fields();
193
- const fieldsAsEntries = Object.entries(fieldsOfModels);
194
- const fieldsWithAutomaticRelations = new Map();
195
- const fields = await fieldsAsEntries.reduce(async (accumulatorAsPromise, [key, value])=>{
196
- if (omitAsSet.has(key)) return accumulatorAsPromise;
197
- if (showAsSet.size > 0 && !showAsSet.has(key)) return accumulatorAsPromise;
198
- let schema = fieldsAsObject[key];
199
- const optionsForForeignKeyRelation = {};
200
- if (!schema || value instanceof ForeignKeyField) {
201
- const newSchema = await getSchemaFromModelField(model, value, parentSchema?.__getParent?.(), options?.fields, options?.engineInstance, optionsForForeignKeyRelation);
202
- if (!schema) schema = newSchema;
203
- }
204
- // Appends the foreign key relation to the schema automatically.
205
- if (optionsForForeignKeyRelation.foreignKeyRelation) {
206
- const rootSchema = optionsForForeignKeyRelation?.foreignKeyRelation?.schema || lazyModelSchema;
207
- const existingRelations = fieldsWithAutomaticRelations.get(rootSchema) || [];
208
- existingRelations.push({
209
- relationOrRelatedName: optionsForForeignKeyRelation.foreignKeyRelation.relationOrRelatedName,
210
- isArray: optionsForForeignKeyRelation.foreignKeyRelation.isArray,
211
- model: optionsForForeignKeyRelation.foreignKeyRelation.model,
212
- fieldToSearchOnModel: optionsForForeignKeyRelation.foreignKeyRelation.fieldToSearchOnModel,
213
- fieldToGetFromData: optionsForForeignKeyRelation.foreignKeyRelation.fieldToGetFromData
214
- });
215
- fieldsWithAutomaticRelations.set(rootSchema, existingRelations);
216
- }
217
- const accumulator = await accumulatorAsPromise;
218
- accumulator[key] = schema;
219
- return accumulator;
220
- }, Promise.resolve(fieldsAsObject));
221
- if (fieldsWithAutomaticRelations.size > 0) {
222
- // This way we can get all of the relations concurrently with Promise.all
223
- for (const [schema, relations] of fieldsWithAutomaticRelations.entries()){
224
- schema.toRepresentation(async (data)=>{
225
- const allData = Array.isArray(data) ? data : [
226
- data
227
- ];
228
- // since we are changing the data by reference, just return the data itself.
229
- await Promise.all(allData.map(async (data)=>Promise.all(relations.map(async (relation)=>{
230
- // Ignore if the data of the relation already exists
231
- if (relation.relationOrRelatedName in data) return;
232
- let relationData = await relation.model.default.get({
233
- search: {
234
- [relation.fieldToSearchOnModel]: data[relation.fieldToGetFromData]
235
- }
236
- });
237
- if (relation.isArray !== true) relationData = relationData[0];
238
- data[relation.relationOrRelatedName] = relationData;
239
- if (schema.__omitRelation.has(relation.relationOrRelatedName)) delete data[relation.fieldToGetFromData];
240
- }))));
241
- return data;
242
- }, {
243
- after: true
244
- });
245
- }
246
- }
247
- lazyModelSchema.__data = fields;
248
- await Promise.all(customFieldValues.map(async (schema)=>{
249
- schema['__getParent'] = ()=>lazyModelSchema;
250
- if (schema['__runBeforeParseAndData']) await schema['__runBeforeParseAndData'](schema);
251
- }));
190
+ const promise = new Promise((resolve)=>{
191
+ const fieldsOfModels = model._fields();
192
+ const fieldsAsEntries = Object.entries(fieldsOfModels);
193
+ const fieldsWithAutomaticRelations = new Map();
194
+ const fields = fieldsAsObject;
195
+ Promise.all(fieldsAsEntries.map(async ([key, value])=>{
196
+ if (omitAsSet.has(key)) return;
197
+ if (showAsSet.size > 0 && !showAsSet.has(key)) return;
198
+ let schema = fieldsAsObject[key];
199
+ const optionsForForeignKeyRelation = {};
200
+ if (!schema || value instanceof ForeignKeyField) {
201
+ const newSchema = await getSchemaFromModelField(model, value, parentSchema?.__getParent?.(), options?.fields, options?.engineInstance, optionsForForeignKeyRelation);
202
+ if (!schema) schema = newSchema;
203
+ }
204
+ // Appends the foreign key relation to the schema automatically.
205
+ if (optionsForForeignKeyRelation.foreignKeyRelation) {
206
+ const rootSchema = optionsForForeignKeyRelation?.foreignKeyRelation?.schema || lazyModelSchema;
207
+ const existingRelations = fieldsWithAutomaticRelations.get(rootSchema) || [];
208
+ existingRelations.push({
209
+ relationOrRelatedName: optionsForForeignKeyRelation.foreignKeyRelation.relationOrRelatedName,
210
+ isArray: optionsForForeignKeyRelation.foreignKeyRelation.isArray,
211
+ model: optionsForForeignKeyRelation.foreignKeyRelation.model,
212
+ fieldToSearchOnModel: optionsForForeignKeyRelation.foreignKeyRelation.fieldToSearchOnModel,
213
+ fieldToGetFromData: optionsForForeignKeyRelation.foreignKeyRelation.fieldToGetFromData
214
+ });
215
+ fieldsWithAutomaticRelations.set(rootSchema, existingRelations);
216
+ }
217
+ fieldsAsObject[key] = schema;
218
+ return fieldsAsObject;
219
+ })).then(async ()=>{
220
+ if (fieldsWithAutomaticRelations.size > 0) {
221
+ // This way we can get all of the relations concurrently with Promise.all
222
+ for (const [schema, relations] of fieldsWithAutomaticRelations.entries()){
223
+ schema.toRepresentation(async (data)=>{
224
+ const allData = Array.isArray(data) ? data : [
225
+ data
226
+ ];
227
+ // since we are changing the data by reference, just return the data itself.
228
+ await Promise.all(allData.map(async (data)=>Promise.all(relations.map(async (relation)=>{
229
+ // Ignore if the data of the relation already exists
230
+ if (relation.relationOrRelatedName in data) return;
231
+ let relationData = await relation.model.default.get({
232
+ search: {
233
+ [relation.fieldToSearchOnModel]: data[relation.fieldToGetFromData]
234
+ }
235
+ });
236
+ if (relation.isArray !== true) relationData = relationData[0];
237
+ data[relation.relationOrRelatedName] = relationData;
238
+ if (schema.__omitRelation.has(relation.relationOrRelatedName)) delete data[relation.fieldToGetFromData];
239
+ }))));
240
+ return data;
241
+ }, {
242
+ after: true
243
+ });
244
+ }
245
+ }
246
+ lazyModelSchema.__data = fields;
247
+ await Promise.all(customFieldValues.map(async (schema)=>{
248
+ schema['__getParent'] = ()=>lazyModelSchema;
249
+ if (schema['__runBeforeParseAndData']) await schema['__runBeforeParseAndData'](schema);
250
+ }));
251
+ resolve(undefined);
252
+ });
253
+ });
254
+ if (parentSchema.__alreadyAppliedModel) return parentSchema.__alreadyAppliedModel;
255
+ parentSchema.__alreadyAppliedModel = promise;
256
+ return promise;
252
257
  };
253
258
  if (options?.ignoreExtraneousFields !== true) lazyModelSchema.removeExtraneous();
254
259
  return parentSchema;