@palmares/schemas 0.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 (219) hide show
  1. package/.turbo/turbo-build$colon$watch.log +424 -0
  2. package/.turbo/turbo-build.log +13 -0
  3. package/.turbo/turbo-build:watch.log +26 -0
  4. package/CHANGELOG.md +11 -0
  5. package/LICENSE +21 -0
  6. package/dist/cjs/src/adapter/fields/array.js +157 -0
  7. package/dist/cjs/src/adapter/fields/boolean.js +167 -0
  8. package/dist/cjs/src/adapter/fields/datetime.js +167 -0
  9. package/dist/cjs/src/adapter/fields/index.js +311 -0
  10. package/dist/cjs/src/adapter/fields/number.js +167 -0
  11. package/dist/cjs/src/adapter/fields/object.js +167 -0
  12. package/dist/cjs/src/adapter/fields/string.js +167 -0
  13. package/dist/cjs/src/adapter/fields/union.js +167 -0
  14. package/dist/cjs/src/adapter/index.js +198 -0
  15. package/dist/cjs/src/adapter/types.js +4 -0
  16. package/dist/cjs/src/compile.js +262 -0
  17. package/dist/cjs/src/conf.js +27 -0
  18. package/dist/cjs/src/constants.js +42 -0
  19. package/dist/cjs/src/domain.js +12 -0
  20. package/dist/cjs/src/exceptions.js +168 -0
  21. package/dist/cjs/src/index.js +365 -0
  22. package/dist/cjs/src/model.js +628 -0
  23. package/dist/cjs/src/parsers/convert-from-number.js +20 -0
  24. package/dist/cjs/src/parsers/convert-from-string.js +24 -0
  25. package/dist/cjs/src/parsers/index.js +25 -0
  26. package/dist/cjs/src/schema/array.js +890 -0
  27. package/dist/cjs/src/schema/boolean.js +826 -0
  28. package/dist/cjs/src/schema/datetime.js +778 -0
  29. package/dist/cjs/src/schema/index.js +17 -0
  30. package/dist/cjs/src/schema/number.js +960 -0
  31. package/dist/cjs/src/schema/object.js +999 -0
  32. package/dist/cjs/src/schema/schema.js +1788 -0
  33. package/dist/cjs/src/schema/string.js +948 -0
  34. package/dist/cjs/src/schema/types.js +4 -0
  35. package/dist/cjs/src/schema/union.js +952 -0
  36. package/dist/cjs/src/types.js +4 -0
  37. package/dist/cjs/src/utils.js +627 -0
  38. package/dist/cjs/src/validators/array.js +457 -0
  39. package/dist/cjs/src/validators/boolean.js +199 -0
  40. package/dist/cjs/src/validators/datetime.js +287 -0
  41. package/dist/cjs/src/validators/number.js +403 -0
  42. package/dist/cjs/src/validators/object.js +290 -0
  43. package/dist/cjs/src/validators/schema.js +318 -0
  44. package/dist/cjs/src/validators/string.js +439 -0
  45. package/dist/cjs/src/validators/types.js +4 -0
  46. package/dist/cjs/src/validators/union.js +232 -0
  47. package/dist/cjs/src/validators/utils.js +426 -0
  48. package/dist/cjs/tsconfig.types.tsbuildinfo +1 -0
  49. package/dist/cjs/types/adapter/fields/array.d.ts +20 -0
  50. package/dist/cjs/types/adapter/fields/array.d.ts.map +1 -0
  51. package/dist/cjs/types/adapter/fields/boolean.d.ts +25 -0
  52. package/dist/cjs/types/adapter/fields/boolean.d.ts.map +1 -0
  53. package/dist/cjs/types/adapter/fields/datetime.d.ts +25 -0
  54. package/dist/cjs/types/adapter/fields/datetime.d.ts.map +1 -0
  55. package/dist/cjs/types/adapter/fields/index.d.ts +31 -0
  56. package/dist/cjs/types/adapter/fields/index.d.ts.map +1 -0
  57. package/dist/cjs/types/adapter/fields/number.d.ts +25 -0
  58. package/dist/cjs/types/adapter/fields/number.d.ts.map +1 -0
  59. package/dist/cjs/types/adapter/fields/object.d.ts +25 -0
  60. package/dist/cjs/types/adapter/fields/object.d.ts.map +1 -0
  61. package/dist/cjs/types/adapter/fields/string.d.ts +25 -0
  62. package/dist/cjs/types/adapter/fields/string.d.ts.map +1 -0
  63. package/dist/cjs/types/adapter/fields/union.d.ts +25 -0
  64. package/dist/cjs/types/adapter/fields/union.d.ts.map +1 -0
  65. package/dist/cjs/types/adapter/index.d.ts +25 -0
  66. package/dist/cjs/types/adapter/index.d.ts.map +1 -0
  67. package/dist/cjs/types/adapter/types.d.ts +144 -0
  68. package/dist/cjs/types/adapter/types.d.ts.map +1 -0
  69. package/dist/cjs/types/compile.d.ts +3 -0
  70. package/dist/cjs/types/compile.d.ts.map +1 -0
  71. package/dist/cjs/types/conf.d.ts +16 -0
  72. package/dist/cjs/types/conf.d.ts.map +1 -0
  73. package/dist/cjs/types/constants.d.ts +6 -0
  74. package/dist/cjs/types/constants.d.ts.map +1 -0
  75. package/dist/cjs/types/domain.d.ts +21 -0
  76. package/dist/cjs/types/domain.d.ts.map +1 -0
  77. package/dist/cjs/types/exceptions.d.ts +13 -0
  78. package/dist/cjs/types/exceptions.d.ts.map +1 -0
  79. package/dist/cjs/types/index.d.ts +240 -0
  80. package/dist/cjs/types/index.d.ts.map +1 -0
  81. package/dist/cjs/types/model.d.ts +136 -0
  82. package/dist/cjs/types/model.d.ts.map +1 -0
  83. package/dist/cjs/types/parsers/convert-from-number.d.ts +15 -0
  84. package/dist/cjs/types/parsers/convert-from-number.d.ts.map +1 -0
  85. package/dist/cjs/types/parsers/convert-from-string.d.ts +9 -0
  86. package/dist/cjs/types/parsers/convert-from-string.d.ts.map +1 -0
  87. package/dist/cjs/types/parsers/index.d.ts +3 -0
  88. package/dist/cjs/types/parsers/index.d.ts.map +1 -0
  89. package/dist/cjs/types/schema/array.d.ts +429 -0
  90. package/dist/cjs/types/schema/array.d.ts.map +1 -0
  91. package/dist/cjs/types/schema/boolean.d.ts +501 -0
  92. package/dist/cjs/types/schema/boolean.d.ts.map +1 -0
  93. package/dist/cjs/types/schema/datetime.d.ts +474 -0
  94. package/dist/cjs/types/schema/datetime.d.ts.map +1 -0
  95. package/dist/cjs/types/schema/index.d.ts +4 -0
  96. package/dist/cjs/types/schema/index.d.ts.map +1 -0
  97. package/dist/cjs/types/schema/number.d.ts +667 -0
  98. package/dist/cjs/types/schema/number.d.ts.map +1 -0
  99. package/dist/cjs/types/schema/object.d.ts +450 -0
  100. package/dist/cjs/types/schema/object.d.ts.map +1 -0
  101. package/dist/cjs/types/schema/schema.d.ts +646 -0
  102. package/dist/cjs/types/schema/schema.d.ts.map +1 -0
  103. package/dist/cjs/types/schema/string.d.ts +606 -0
  104. package/dist/cjs/types/schema/string.d.ts.map +1 -0
  105. package/dist/cjs/types/schema/types.d.ts +70 -0
  106. package/dist/cjs/types/schema/types.d.ts.map +1 -0
  107. package/dist/cjs/types/schema/union.d.ts +388 -0
  108. package/dist/cjs/types/schema/union.d.ts.map +1 -0
  109. package/dist/cjs/types/types.d.ts +11 -0
  110. package/dist/cjs/types/types.d.ts.map +1 -0
  111. package/dist/cjs/types/utils.d.ts +79 -0
  112. package/dist/cjs/types/utils.d.ts.map +1 -0
  113. package/dist/cjs/types/validators/array.d.ts +8 -0
  114. package/dist/cjs/types/validators/array.d.ts.map +1 -0
  115. package/dist/cjs/types/validators/boolean.d.ts +4 -0
  116. package/dist/cjs/types/validators/boolean.d.ts.map +1 -0
  117. package/dist/cjs/types/validators/datetime.d.ts +7 -0
  118. package/dist/cjs/types/validators/datetime.d.ts.map +1 -0
  119. package/dist/cjs/types/validators/number.d.ts +10 -0
  120. package/dist/cjs/types/validators/number.d.ts.map +1 -0
  121. package/dist/cjs/types/validators/object.d.ts +6 -0
  122. package/dist/cjs/types/validators/object.d.ts.map +1 -0
  123. package/dist/cjs/types/validators/schema.d.ts +10 -0
  124. package/dist/cjs/types/validators/schema.d.ts.map +1 -0
  125. package/dist/cjs/types/validators/string.d.ts +12 -0
  126. package/dist/cjs/types/validators/string.d.ts.map +1 -0
  127. package/dist/cjs/types/validators/types.d.ts +2 -0
  128. package/dist/cjs/types/validators/types.d.ts.map +1 -0
  129. package/dist/cjs/types/validators/union.d.ts +4 -0
  130. package/dist/cjs/types/validators/union.d.ts.map +1 -0
  131. package/dist/cjs/types/validators/utils.d.ts +83 -0
  132. package/dist/cjs/types/validators/utils.d.ts.map +1 -0
  133. package/dist/esm/src/adapter/fields/array.js +13 -0
  134. package/dist/esm/src/adapter/fields/boolean.js +20 -0
  135. package/dist/esm/src/adapter/fields/datetime.js +20 -0
  136. package/dist/esm/src/adapter/fields/index.js +37 -0
  137. package/dist/esm/src/adapter/fields/number.js +20 -0
  138. package/dist/esm/src/adapter/fields/object.js +20 -0
  139. package/dist/esm/src/adapter/fields/string.js +20 -0
  140. package/dist/esm/src/adapter/fields/union.js +20 -0
  141. package/dist/esm/src/adapter/index.js +18 -0
  142. package/dist/esm/src/adapter/types.js +1 -0
  143. package/dist/esm/src/compile.js +10 -0
  144. package/dist/esm/src/conf.js +19 -0
  145. package/dist/esm/src/constants.js +5 -0
  146. package/dist/esm/src/domain.js +2 -0
  147. package/dist/esm/src/exceptions.js +15 -0
  148. package/dist/esm/src/index.js +160 -0
  149. package/dist/esm/src/model.js +255 -0
  150. package/dist/esm/src/parsers/convert-from-number.js +8 -0
  151. package/dist/esm/src/parsers/convert-from-string.js +14 -0
  152. package/dist/esm/src/parsers/index.js +2 -0
  153. package/dist/esm/src/schema/array.js +403 -0
  154. package/dist/esm/src/schema/boolean.js +465 -0
  155. package/dist/esm/src/schema/datetime.js +423 -0
  156. package/dist/esm/src/schema/index.js +3 -0
  157. package/dist/esm/src/schema/number.js +592 -0
  158. package/dist/esm/src/schema/object.js +464 -0
  159. package/dist/esm/src/schema/schema.js +728 -0
  160. package/dist/esm/src/schema/string.js +579 -0
  161. package/dist/esm/src/schema/types.js +1 -0
  162. package/dist/esm/src/schema/union.js +388 -0
  163. package/dist/esm/src/types.js +1 -0
  164. package/dist/esm/src/utils.js +175 -0
  165. package/dist/esm/src/validators/array.js +135 -0
  166. package/dist/esm/src/validators/boolean.js +35 -0
  167. package/dist/esm/src/validators/datetime.js +85 -0
  168. package/dist/esm/src/validators/number.js +162 -0
  169. package/dist/esm/src/validators/object.js +38 -0
  170. package/dist/esm/src/validators/schema.js +114 -0
  171. package/dist/esm/src/validators/string.js +174 -0
  172. package/dist/esm/src/validators/types.js +1 -0
  173. package/dist/esm/src/validators/union.js +38 -0
  174. package/dist/esm/src/validators/utils.js +120 -0
  175. package/package.json +48 -0
  176. package/src/adapter/fields/array.ts +31 -0
  177. package/src/adapter/fields/boolean.ts +48 -0
  178. package/src/adapter/fields/datetime.ts +49 -0
  179. package/src/adapter/fields/index.ts +72 -0
  180. package/src/adapter/fields/number.ts +49 -0
  181. package/src/adapter/fields/object.ts +49 -0
  182. package/src/adapter/fields/string.ts +49 -0
  183. package/src/adapter/fields/union.ts +49 -0
  184. package/src/adapter/index.ts +34 -0
  185. package/src/adapter/types.ts +261 -0
  186. package/src/compile.ts +14 -0
  187. package/src/conf.ts +27 -0
  188. package/src/constants.ts +9 -0
  189. package/src/domain.ts +3 -0
  190. package/src/exceptions.ts +17 -0
  191. package/src/index.ts +338 -0
  192. package/src/model.ts +501 -0
  193. package/src/parsers/convert-from-number.ts +13 -0
  194. package/src/parsers/convert-from-string.ts +19 -0
  195. package/src/parsers/index.ts +2 -0
  196. package/src/schema/array.ts +633 -0
  197. package/src/schema/boolean.ts +700 -0
  198. package/src/schema/datetime.ts +613 -0
  199. package/src/schema/index.ts +5 -0
  200. package/src/schema/number.ts +885 -0
  201. package/src/schema/object.ts +699 -0
  202. package/src/schema/schema.ts +1093 -0
  203. package/src/schema/string.ts +807 -0
  204. package/src/schema/types.ts +126 -0
  205. package/src/schema/union.ts +596 -0
  206. package/src/types.ts +13 -0
  207. package/src/utils.ts +322 -0
  208. package/src/validators/array.ts +164 -0
  209. package/src/validators/boolean.ts +46 -0
  210. package/src/validators/datetime.ts +113 -0
  211. package/src/validators/number.ts +188 -0
  212. package/src/validators/object.ts +55 -0
  213. package/src/validators/schema.ts +134 -0
  214. package/src/validators/string.ts +215 -0
  215. package/src/validators/types.ts +1 -0
  216. package/src/validators/union.ts +52 -0
  217. package/src/validators/utils.ts +200 -0
  218. package/tsconfig.json +9 -0
  219. package/tsconfig.types.json +10 -0
@@ -0,0 +1,255 @@
1
+ import { AutoField, BigAutoField, BooleanField, CharField, DateField, DecimalField, EnumField, ForeignKeyField, IntegerField, TextField, TranslatableField, UuidField } from '@palmares/databases';
2
+ import { TranslatableFieldNotImplementedError } from './exceptions';
3
+ import { number } from './schema';
4
+ import ArraySchema from './schema/array';
5
+ import { boolean } from './schema/boolean';
6
+ import { datetime } from './schema/datetime';
7
+ import ObjectSchema from './schema/object';
8
+ import Schema from './schema/schema';
9
+ import { string } from './schema/string';
10
+ import { union } from './schema/union';
11
+ async function getSchemaFromModelField(model, field, parent, definedFields, engineInstanceName, options) {
12
+ let schema = undefined;
13
+ if (field instanceof AutoField || field instanceof BigAutoField) schema = number().integer().optional();
14
+ else if (field instanceof DecimalField) schema = number().decimalPlaces(field.decimalPlaces).maxDigits(field.maxDigits);
15
+ else if (field instanceof IntegerField) schema = number().integer();
16
+ else if (field instanceof BooleanField) schema = boolean();
17
+ else if (field instanceof TextField || field instanceof CharField || field instanceof UuidField) {
18
+ schema = string();
19
+ if (field.allowBlank === false) schema = schema.minLength(1);
20
+ if (field instanceof CharField && typeof field.maxLength === 'number') schema = schema.maxLength(field.maxLength);
21
+ if (field instanceof UuidField) {
22
+ schema = schema.uuid();
23
+ if (field.autoGenerate) schema = schema.optional();
24
+ }
25
+ } else if (field instanceof DateField) {
26
+ schema = datetime().allowString();
27
+ if (field.autoNow || field.autoNowAdd) schema = schema.optional();
28
+ } else if (field instanceof EnumField) {
29
+ const allChoicesOfTypeStrings = field.choices.filter((choice)=>typeof choice === 'string');
30
+ const allChoicesOfTypeNumbers = field.choices.filter((choice)=>typeof choice === 'number');
31
+ let schemaForChoicesAsStrings = undefined;
32
+ let schemaForChoicesAsNumbers = undefined;
33
+ if (allChoicesOfTypeStrings.length > 0) schemaForChoicesAsStrings = string().is([
34
+ ...allChoicesOfTypeStrings
35
+ ]);
36
+ if (allChoicesOfTypeNumbers.length > 0) schemaForChoicesAsNumbers = number().is([
37
+ ...allChoicesOfTypeNumbers
38
+ ]);
39
+ if (schemaForChoicesAsStrings && schemaForChoicesAsNumbers) schema = union([
40
+ schemaForChoicesAsStrings,
41
+ schemaForChoicesAsNumbers
42
+ ]);
43
+ else if (schemaForChoicesAsStrings) schema = schemaForChoicesAsStrings;
44
+ else if (schemaForChoicesAsNumbers) schema = schemaForChoicesAsNumbers;
45
+ } else if (field instanceof ForeignKeyField) {
46
+ const doesADefinedFieldExistWithRelatedName = parent && field.relatedName && parent.__data?.[field.relatedName];
47
+ const doesADefinedFieldExistWithRelationName = definedFields && field.relationName && definedFields[field.relationName];
48
+ const fieldWithRelatedName = doesADefinedFieldExistWithRelatedName ? parent.__data?.[field.relatedName] : undefined;
49
+ const fieldWithRelationName = doesADefinedFieldExistWithRelationName ? definedFields[field.relationName] : undefined;
50
+ const isFieldWithRelatedNameAModelField = fieldWithRelatedName instanceof Schema && fieldWithRelatedName.__model !== undefined;
51
+ const isFieldWithRelationNameAModelField = fieldWithRelationName instanceof Schema && fieldWithRelationName.__model !== undefined;
52
+ const relatedToModel = field.relatedTo;
53
+ const toField = field.toField;
54
+ const engineInstance = await model.default.getEngineInstance(engineInstanceName);
55
+ const relatedToModelInstance = engineInstance.__modelsOfEngine[relatedToModel];
56
+ const modelFieldsOfRelatedModel = relatedToModelInstance.__cachedFields[toField];
57
+ if (isFieldWithRelatedNameAModelField) {
58
+ if (typeof options !== 'object') options = {};
59
+ options.foreignKeyRelation = {
60
+ schema: parent,
61
+ isArray: fieldWithRelatedName instanceof ArraySchema,
62
+ model: fieldWithRelatedName.__model,
63
+ fieldToSearchOnModel: field.fieldName,
64
+ fieldToGetFromData: field.toField,
65
+ relationOrRelatedName: field.relatedName
66
+ };
67
+ } else if (isFieldWithRelationNameAModelField) {
68
+ if (typeof options !== 'object') options = {};
69
+ options.foreignKeyRelation = {
70
+ isArray: fieldWithRelationName instanceof ArraySchema,
71
+ model: fieldWithRelationName.__model,
72
+ fieldToSearchOnModel: field.toField,
73
+ fieldToGetFromData: field.fieldName,
74
+ relationOrRelatedName: field.relationName
75
+ };
76
+ }
77
+ return getSchemaFromModelField(relatedToModelInstance, modelFieldsOfRelatedModel, parent, definedFields, engineInstanceName, options);
78
+ } else if (field instanceof TranslatableField && field.customAttributes.schema) {
79
+ if (field.customAttributes.schema instanceof Schema === false) throw new TranslatableFieldNotImplementedError(field.fieldName);
80
+ schema = field.customAttributes.schema;
81
+ }
82
+ if (field.allowNull && schema) schema = schema.nullable().optional();
83
+ if (field.defaultValue && schema) schema = schema.default(field.defaultValue);
84
+ return schema || string();
85
+ }
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.
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.
92
+ *
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.
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.
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.
103
+ *
104
+ * Like: `{ options: { show: ['id', 'name', 'companyId'] }}` or `{ options: { omit: ['id'] }}` it **will work**.
105
+ *
106
+ * If you do `{ options: { show: ['id', 'name'] }}` or `{ options: { omit: ['companyId']} }` it **won't work**.
107
+ *
108
+ * **Important 3**: If you want to return an array instead of an object, you need to pass the `many` option as true.
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * import { auto, choice, foreignKey, Model, define } from '@palmares/databases';
113
+ * import * as p from '@palmares/schemas';
114
+ *
115
+ * const Company = define('Company', {
116
+ * fields: {
117
+ * id: auto(),
118
+ * name: text(),
119
+ * },
120
+ * options: {
121
+ * tableName: 'company',
122
+ * }
123
+ * });
124
+ *
125
+ * class User extends Model<User>() {
126
+ * fields = {
127
+ * id: auto(),
128
+ * type: choice({ choices: ['user', 'admin'] }),
129
+ * companyId: foreignKey({
130
+ * relatedTo: Company,
131
+ * relationName: 'company',
132
+ * relatedName: 'usersOfCompany',
133
+ * toField: 'id',
134
+ * onDelete: 'CASCADE',
135
+ * }),
136
+ * }
137
+ *
138
+ * options = {
139
+ * tableName: 'user',
140
+ * }
141
+ * }
142
+ *
143
+ * const userSchema = p.modelSchema(User, {
144
+ * fields: {
145
+ * company: p.modelSchema(Company).optional({ outputOnly: true });
146
+ * },
147
+ * show: ['type', 'companyId'], // 'companyId' is required for the automatic relation to work, otherwise it won't show
148
+ * omitRelation: ['company']
149
+ * });
150
+ *
151
+ * const companySchema = p.modelSchema(Company, {
152
+ * fields: {
153
+ * usersOfCompany: p.modelSchema(User, { many: true }).optional({ outputOnly: true });
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
+ * });
157
+ *```
158
+ * @param model - The model that you want to build the schema from.
159
+ * @param options - The options to build the schema.
160
+ * @param options.ignoreExtraneousFields - If you want to ignore extraneous fields set this to true.
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']`.
165
+ *
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
+ * We will not create a schema for that field and use the one you have defined here.
168
+ * @param options.omit - Fields that you want to omit from the schema. If that is defined, we ignore `show` option.
169
+ * @param options.show - Fields that you want to show on the schema. If that is defined, we ignore `omit` option.
170
+ * @param options.many - If you want to return an array instead of an object, set this to true. With that we create
171
+ * an ArraySchema instead of an ObjectSchema.
172
+ *
173
+ * @returns - If you pass the `many` option as true, we return an ArraySchema, otherwise we return an ObjectSchema.
174
+ */ export function modelSchema(model, options) {
175
+ const lazyModelSchema = ObjectSchema.new({});
176
+ const parentSchema = options?.many === true ? ArraySchema.new([
177
+ lazyModelSchema
178
+ ]) : lazyModelSchema;
179
+ const omitRelationAsSet = new Set(options?.omitRelation || []);
180
+ const omitAsSet = new Set(options?.omit || []);
181
+ const showAsSet = new Set(options?.show || []);
182
+ const fieldsAsObject = options?.fields || {};
183
+ const customFieldValues = Object.values(fieldsAsObject);
184
+ // We need to add it to the instance to be able to access it on the `toRepresentation` callback
185
+ lazyModelSchema.__omitRelation = omitRelationAsSet;
186
+ parentSchema.__model = model;
187
+ lazyModelSchema.__model = model;
188
+ // Add this callback to transform the model fields
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
+ }));
252
+ };
253
+ if (options?.ignoreExtraneousFields !== true) lazyModelSchema.removeExtraneous();
254
+ return parentSchema;
255
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * This will convert a value from a number to any other type.
3
+ *
4
+ * @param callback
5
+ * @returns
6
+ */ export default function convertFromNumberBuilder(callback) {
7
+ return (value)=>callback(value);
8
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * This will convert a value from a string to any other type.
3
+ *
4
+ * @param callback
5
+ * @returns
6
+ */ export default function convertFromStringBuilder(callback) {
7
+ return (value)=>{
8
+ if (typeof value === 'string') return callback(value);
9
+ return {
10
+ value,
11
+ preventNextParsers: false
12
+ };
13
+ };
14
+ }
@@ -0,0 +1,2 @@
1
+ export { default as convertFromNumberBuilder } from './convert-from-number';
2
+ export { default as convertFromStringBuilder } from './convert-from-string';
@@ -0,0 +1,403 @@
1
+ import Schema from './schema';
2
+ import { getDefaultAdapter } from '../conf';
3
+ import { defaultTransform, defaultTransformToAdapter, transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas } from '../utils';
4
+ import { arrayValidation, maxLength, minLength, nonEmpty } from '../validators/array';
5
+ import { nullable, optional } from '../validators/schema';
6
+ import Validator from '../validators/utils';
7
+ export default class ArraySchema extends Schema {
8
+ __schemas;
9
+ __minLength;
10
+ __maxLength;
11
+ __nonEmpty;
12
+ constructor(...schemas){
13
+ super();
14
+ this.__schemas = schemas;
15
+ }
16
+ async __transformToAdapter(options) {
17
+ return defaultTransformToAdapter(async (adapter)=>{
18
+ const schemas = Array.isArray(this.__schemas[0]) ? this.__schemas[0] : this.__schemas;
19
+ const transformedSchemasAsString = [];
20
+ const transformedSchemas = [];
21
+ let shouldBeHandledByFallback = false;
22
+ await Promise.all(schemas.map(async (schema)=>{
23
+ const [transformedData, shouldAddFallbackValidationForThisSchema] = await transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas(schema, options);
24
+ if (shouldAddFallbackValidationForThisSchema) shouldBeHandledByFallback = true;
25
+ for (const transformedSchema of transformedData){
26
+ transformedSchemasAsString.push(transformedSchema.asString);
27
+ transformedSchemas.push(transformedSchema.transformed);
28
+ }
29
+ }));
30
+ // eslint-disable-next-line ts/no-unnecessary-condition
31
+ if (shouldBeHandledByFallback) Validator.createAndAppendFallback(this, arrayValidation(Array.isArray(this.__schemas[0]) === false, Array.isArray(this.__schemas[0]) ? this.__schemas[0] : this.__schemas));
32
+ return defaultTransform('array', this, adapter, adapter.array, ()=>({
33
+ isTuple: Array.isArray(this.__schemas[0]) === false,
34
+ nullable: this.__nullable,
35
+ optional: this.__optional,
36
+ maxLength: this.__maxLength,
37
+ minLength: this.__minLength,
38
+ nonEmpty: this.__nonEmpty,
39
+ parsers: {
40
+ nullable: this.__nullable.allow,
41
+ optional: this.__optional.allow
42
+ }
43
+ }), {
44
+ optional,
45
+ nullable,
46
+ minLength,
47
+ maxLength,
48
+ nonEmpty
49
+ }, {
50
+ shouldAddStringVersion: options.shouldAddStringVersion,
51
+ // eslint-disable-next-line ts/require-await
52
+ fallbackIfNotSupported: async ()=>[]
53
+ });
54
+ }, this.__transformedSchemas, options, 'array');
55
+ }
56
+ /**
57
+ * This let's you refine the schema with custom validations. This is useful when you want to validate something that is not supported by default by the schema adapter.
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * import * as p from '@palmares/schemas';
62
+ *
63
+ * const numberSchema = p.number().refine((value) => {
64
+ * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
65
+ * });
66
+ *
67
+ * const { errors, parsed } = await numberSchema.parse(-1);
68
+ *
69
+ * console.log(errors); // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
70
+ * ```
71
+ *
72
+ * @param refinementCallback - The callback that will be called to validate the value.
73
+ * @param options - Options for the refinement.
74
+ * @param options.isAsync - Whether the callback is async or not. Defaults to true.
75
+ */ refine(refinementCallback) {
76
+ return super.refine(refinementCallback);
77
+ }
78
+ /**
79
+ * Allows the value to be either undefined or null. Different from the `optional` method on other schemas, You can pass `outputOnly` as `true` to this method.
80
+ * This will allow you to pass `null` or `undefined` as a value on the {@link Schema.data} method, but it will not allow the value to be `null` or `undefined`.
81
+ * This is useful for typing purposes.
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * import * as p from '@palmares/schemas';
86
+ *
87
+ * const numberSchema = p.number().optional();
88
+ *
89
+ * const { errors, parsed } = await numberSchema.parse(undefined);
90
+ *
91
+ * console.log(parsed); // undefined
92
+ *
93
+ * const { errors, parsed } = await numberSchema.parse(null);
94
+ *
95
+ * console.log(parsed); // null
96
+ *
97
+ * const { errors, parsed } = await numberSchema.parse(1);
98
+ *
99
+ * console.log(parsed); // 1
100
+ *
101
+ * const companySchema = p.object({ id: p.number(), name: p.string() });
102
+ * const userSchema = p.object({
103
+ * id: p.number(),
104
+ * name: p.string(),
105
+ * company: companySchema.optional({ outputOnly: true })
106
+ * });
107
+ *
108
+ * const { errors, parsed } = await userSchema.data({ id: 1, name: 'John Doe' }); // Will not allow the company to be null or undefined on a typing level.
109
+ * const value = await userSchema.data({ id: 1, name: 'John Doe' }); // Will allow the company to be null or undefined on a typing level
110
+ * ```
111
+ *
112
+ * @returns - The schema we are working with.
113
+ */ optional(options) {
114
+ return options?.outputOnly ? this : super.optional(options);
115
+ }
116
+ /**
117
+ * Allows the value to be null and ONLY null. You can also use this function to set a custom message when the value is NULL by setting
118
+ * the { message: 'Your custom message', allow: false } on the options.
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * import * as p from '@palmares/schemas';
123
+ *
124
+ * const numberSchema = p.number().nullable();
125
+ *
126
+ * const { errors, parsed } = await numberSchema.parse(null);
127
+ *
128
+ * console.log(parsed); // null
129
+ *
130
+ * const { errors, parsed } = await numberSchema.parse(undefined);
131
+ *
132
+ * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
133
+ * ```
134
+ *
135
+ * @param options - The options for the nullable function.
136
+ * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
137
+ * @param options.allow - Whether the value can be null or not. Defaults to true.
138
+ *
139
+ * @returns The schema.
140
+ */ nullable(options) {
141
+ return super.nullable(options);
142
+ }
143
+ /**
144
+ * This method will remove the value from the representation of the schema. If the value is undefined it will keep that way
145
+ * otherwise it will set the value to undefined after it's validated.
146
+ * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
147
+ * function. This will remove the value from the representation of the schema.
148
+ *
149
+ * By default, the value will be removed just from the representation, in other words, when you call the {@link data} function.
150
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal` as true.
151
+ * Then if you still want to remove the value from the representation, you will need to pass the argument `toRepresentation` as true as well.
152
+ *
153
+ * @example
154
+ * ```typescript
155
+ * import * as p from '@palmares/schemas';
156
+ *
157
+ * const userSchema = p.object({
158
+ * id: p.number().optional(),
159
+ * name: p.string(),
160
+ * password: p.string().omit()
161
+ * });
162
+ *
163
+ * const user = await userSchema.data({
164
+ * id: 1,
165
+ * name: 'John Doe',
166
+ * password: '123456'
167
+ * });
168
+ *
169
+ * console.log(user); // { id: 1, name: 'John Doe' }
170
+ * ```
171
+ *
172
+ *
173
+ * @param args - By default, the value will be removed just from the representation, in other words, when you call the {@link data} function.
174
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal` as true.
175
+ * Then if you still want to remove the value from the representation, you will need to pass the argument `toRepresentation` as true as well.
176
+ *
177
+ * @returns The schema.
178
+ */ omit(args) {
179
+ return super.omit(args);
180
+ }
181
+ /**
182
+ * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external source
183
+ * like a database. You should always return the schema after you save the value, that way we will always have the correct type
184
+ * of the schema after the save operation.
185
+ *
186
+ * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * import * as p from '@palmares/schemas';
191
+ *
192
+ * import { User } from './models';
193
+ *
194
+ * const userSchema = p.object({
195
+ * id: p.number().optional(),
196
+ * name: p.string(),
197
+ * email: p.string().email(),
198
+ * }).onSave(async (value) => {
199
+ * // Create or update the user on the database using palmares models or any other library of your choice.
200
+ * if (value.id)
201
+ * await User.default.set(value, { search: { id: value.id } });
202
+ * else
203
+ * await User.default.set(value);
204
+ *
205
+ * return value;
206
+ * });
207
+ *
208
+ *
209
+ * // Then, on your controller, do something like this:
210
+ * const { isValid, save, errors } = await userSchema.validate(req.body);
211
+ * if (isValid) {
212
+ * const savedValue = await save();
213
+ * return Response.json(savedValue, { status: 201 });
214
+ * }
215
+ *
216
+ * return Response.json({ errors }, { status: 400 });
217
+ * ```
218
+ *
219
+ * @param callback - The callback that will be called to save the value on an external source.
220
+ *
221
+ * @returns The schema.
222
+ */ onSave(callback) {
223
+ return super.onSave(callback);
224
+ }
225
+ /**
226
+ * This function is used to add a default value to the schema. If the value is either undefined or null, the default value will be used.
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * import * as p from '@palmares/schemas';
231
+ *
232
+ * const numberSchema = p.number().default(0);
233
+ *
234
+ * const { errors, parsed } = await numberSchema.parse(undefined);
235
+ *
236
+ * console.log(parsed); // 0
237
+ * ```
238
+ */ default(defaultValueOrFunction) {
239
+ return super.default(defaultValueOrFunction);
240
+ }
241
+ /**
242
+ * This function let's you customize the schema your own way. After we translate the schema on the adapter we call this function to let you customize
243
+ * the custom schema your own way. Our API does not support passthrough? No problem, you can use this function to customize the zod schema.
244
+ *
245
+ * @example
246
+ * ```typescript
247
+ * import * as p from '@palmares/schemas';
248
+ *
249
+ * const numberSchema = p.number().extends((schema) => {
250
+ * return schema.nonnegative();
251
+ * });
252
+ *
253
+ * const { errors, parsed } = await numberSchema.parse(-1);
254
+ *
255
+ * console.log(errors); // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
256
+ * ```
257
+ *
258
+ * @param callback - The callback that will be called to customize the schema.
259
+ * @param toStringCallback - The callback that will be called to transform the schema to a string when you want to compile the underlying schema
260
+ * to a string so you can save it for future runs.
261
+ *
262
+ * @returns The schema.
263
+ */ extends(callback, toStringCallback) {
264
+ return super.extends(callback, toStringCallback);
265
+ }
266
+ /**
267
+ * This function is used to transform the value to the representation of the schema. When using the {@link data} function. With this function you have full
268
+ * control to add data cleaning for example, transforming the data and whatever. Another use case is when you want to return deeply nested recursive data.
269
+ * The schema maps to itself.
270
+ *
271
+ * @example
272
+ * ```typescript
273
+ * import * as p from '@palmares/schemas';
274
+ *
275
+ * const recursiveSchema = p.object({
276
+ * id: p.number().optional(),
277
+ * name: p.string(),
278
+ * }).toRepresentation(async (value) => {
279
+ * return {
280
+ * id: value.id,
281
+ * name: value.name,
282
+ * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
283
+ * }
284
+ * });
285
+ *
286
+ * const data = await recursiveSchema.data({
287
+ * id: 1,
288
+ * name: 'John Doe',
289
+ * });
290
+ * ```
291
+ *
292
+ * @example
293
+ * ```
294
+ * import * as p from '@palmares/schemas';
295
+ *
296
+ * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
297
+ * switch (value) {
298
+ * case 'red': return { r: 255, g: 0, b: 0 };
299
+ * case 'green': return { r: 0, g: 255, b: 0 };
300
+ * case 'blue': return { r: 0, g: 0, b: 255 };
301
+ * default: return { r: 0, g: 0, b: 0 };
302
+ * }
303
+ * });
304
+ * ```
305
+ * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
306
+ *
307
+ * @returns The schema with a new return type
308
+ */ toRepresentation(toRepresentationCallback) {
309
+ return super.toRepresentation(toRepresentationCallback);
310
+ }
311
+ /**
312
+ * This function is used to transform the value to the internal representation of the schema. This is useful when you want to transform the value
313
+ * to a type that the schema adapter can understand. For example, you might want to transform a string to a date. This is the function you use.
314
+ *
315
+ * @example
316
+ * ```typescript
317
+ * import * as p from '@palmares/schemas';
318
+ *
319
+ * const dateSchema = p.string().toInternal((value) => {
320
+ * return new Date(value);
321
+ * });
322
+ *
323
+ * const date = await dateSchema.parse('2021-01-01');
324
+ *
325
+ * console.log(date); // Date object
326
+ *
327
+ * const rgbToColorSchema = p.object({
328
+ * r: p.number().min(0).max(255),
329
+ * g: p.number().min(0).max(255),
330
+ * b: p.number().min(0).max(255),
331
+ * }).toInternal(async (value) => {
332
+ * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
333
+ * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
334
+ * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
335
+ * return `rgb(${value.r}, ${value.g}, ${value.b})`;
336
+ * });
337
+ * ```
338
+ *
339
+ * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
340
+ *
341
+ * @returns The schema with a new return type.
342
+ */ toInternal(toInternalCallback) {
343
+ return super.toInternal(toInternalCallback);
344
+ }
345
+ /**
346
+ * Called before the validation of the schema. Let's say that you want to validate a date that might receive a string, you can convert that string to a date
347
+ * here BEFORE the validation. This pretty much transforms the value to a type that the schema adapter can understand.
348
+ *
349
+ * @example
350
+ * ```
351
+ * import * as p from '@palmares/schemas';
352
+ * import * as z from 'zod';
353
+ *
354
+ * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
355
+ * return new Map(value); // Before validating we transform the value to a map.
356
+ * });
357
+ *
358
+ * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
359
+ * ```
360
+ *
361
+ * @param toValidateCallback - The callback that will be called to validate the value.
362
+ *
363
+ * @returns The schema with a new return type.
364
+ */ toValidate(toValidateCallback) {
365
+ return super.toValidate(toValidateCallback);
366
+ }
367
+ minLength(value, inclusive = true, message) {
368
+ message = message || `The array must have a minimum length of ${value}`;
369
+ this.__minLength = {
370
+ value: value,
371
+ inclusive: inclusive,
372
+ message: message
373
+ };
374
+ return this;
375
+ }
376
+ maxLength(value, inclusive = true, message) {
377
+ message = message || `The array must have a maximum length of ${value}`;
378
+ this.__maxLength = {
379
+ value: value,
380
+ inclusive: inclusive,
381
+ message: message
382
+ };
383
+ return this;
384
+ }
385
+ nonEmpty(message) {
386
+ message = message || 'The array must not be empty';
387
+ this.__nonEmpty = {
388
+ message: message
389
+ };
390
+ return this;
391
+ }
392
+ static new(...schemas) {
393
+ const returnValue = new ArraySchema(...schemas);
394
+ const adapterInstance = getDefaultAdapter();
395
+ returnValue.__transformedSchemas[adapterInstance.constructor.name] = {
396
+ transformed: false,
397
+ adapter: adapterInstance,
398
+ schemas: []
399
+ };
400
+ return returnValue;
401
+ }
402
+ }
403
+ export const array = (...schemas)=>ArraySchema.new(...schemas);