rads-db 0.1.78 → 0.1.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -33,7 +33,7 @@ function fillDefaultValues(schema, typeName, value) {
33
33
  return;
34
34
  for (const fName in type.fields) {
35
35
  const field = type.fields[fName];
36
- if (field.defaultValueCopyFrom) {
36
+ if (field.defaultValueCopyFrom && !value[fName]) {
37
37
  value[fName] = ___default.cloneDeep(value[field.defaultValueCopyFrom]);
38
38
  }
39
39
  }
@@ -70,6 +70,12 @@ function getFieldZodSchema(zodSchemas, schema, field, shouldBeLazy) {
70
70
  return fieldSchema;
71
71
  }
72
72
  function getFieldZodSchemaBase(zodSchemas, schema, field, shouldBeLazy) {
73
+ if (field.isChange) {
74
+ const zodSchema = getZodSchema(zodSchemas, schema, field.type);
75
+ if (!zodSchema)
76
+ throw new Error(`Cannot find zod schema for type: ${field.type}`);
77
+ return zodSchema.deepPartial().omit({ id: true });
78
+ }
73
79
  if (field.type === "string")
74
80
  return zod.z.string();
75
81
  if (field.type === "boolean")
@@ -78,13 +84,6 @@ function getFieldZodSchemaBase(zodSchemas, schema, field, shouldBeLazy) {
78
84
  return zod.z.number();
79
85
  if (field.type === "Record<string, any>")
80
86
  return zod.z.record(zod.z.string(), zod.z.any());
81
- if (field.type.startsWith("Change<")) {
82
- const changeType = field.type.slice(7, -1);
83
- const zodSchema = getZodSchema(zodSchemas, schema, changeType);
84
- if (!zodSchema)
85
- throw new Error(`Cannot find zod schema for type: ${changeType}`);
86
- return zodSchema.deepPartial().omit({ id: true });
87
- }
88
87
  if (schema[field.type]) {
89
88
  const getSchema = () => {
90
89
  let zodSchema = getZodSchema(zodSchemas, schema, field.type);
@@ -546,7 +545,7 @@ function validateEventSourcingSetup(schema, entityName, eventEntityName, aggrega
546
545
  const expectedFields = {
547
546
  id: "string",
548
547
  type: "enum",
549
- change: `Change<${entityName}>`,
548
+ change: entityName,
550
549
  [aggregateRelationField]: entityName,
551
550
  date: "string"
552
551
  };
@@ -560,6 +559,9 @@ function validateEventSourcingSetup(schema, entityName, eventEntityName, aggrega
560
559
  } else {
561
560
  if (field.type !== expectedFields[f])
562
561
  throw new Error(`"${eventEntityName}.${f}" must have type "${expectedFields[f]}"`);
562
+ if (f === "change" && !field.isChange) {
563
+ throw new Error(`"${eventEntityName}.${f}" must have type "Change<${expectedFields[f]}>"`);
564
+ }
563
565
  }
564
566
  }
565
567
  }
package/dist/index.d.ts CHANGED
@@ -63,29 +63,26 @@ type GetResponseNoInclude<E, EN extends keyof EntityMeta> = {
63
63
  [K in keyof E]: K extends keyof EntityMeta[EN]['relations'] ? Pick<EntityMeta[EN]['relations'][K]['entity'], EntityMeta[EN]['relations'][K]['denormFields']> : E[K];
64
64
  };
65
65
  type DeepPartial<T> = {
66
- [K in keyof T]?: DeepPartial<T[K]>;
67
- };
68
- type DeepPartialNullable<T> = {
69
- [K in keyof T]?: DeepPartialNullable<T[K]> | null;
66
+ [K in keyof T]?: NonNullable<T[K]> extends Record<string, any> ? DeepPartial<T[K]> : T[K] | null;
70
67
  };
71
68
  type Relation<T extends {
72
69
  id: any;
73
70
  }, K extends Exclude<keyof T, 'id'> = never> = Pick<T, K | 'id'> & DeepPartial<T>;
74
71
  type PutArgs<T> = {
75
72
  id: string;
76
- } & DeepPartialNullable<T>;
73
+ } & DeepPartial<T>;
77
74
  interface EntityMethods<E, EN extends keyof EntityMeta, W> {
78
75
  createObject(defaultValues: Partial<E>): E;
79
76
  /** Used to access underlying mechanism of storage directly.
80
77
  * Warning: bypasses all rads features - schema won't be validated, default values won't be filled, etc. */
81
78
  driver: Driver;
82
- get<A extends GetArgs<E, EN, W>>(args: A): MaybePromise$1<GetResponse<E, EN, A>>;
83
- getMany<A extends GetManyArgs<E, EN, W>>(args?: A): MaybePromise$1<GetManyResponse<E, EN, A>>;
84
- getAgg<A extends GetAggArgs<EN, W>>(args: A): MaybePromise$1<GetAggResponse<EN, A>>;
85
- getAll<A extends GetManyArgs<E, EN, W>>(args?: A): MaybePromise$1<GetManyResponse<E, EN, A>['nodes']>;
86
- put(data: PutArgs<E>): MaybePromise$1<GetResponseNoInclude<E, EN>>;
87
- putMany(data: PutArgs<E>[]): MaybePromise$1<GetResponseNoInclude<E, EN>[]>;
88
- verifyMany<A extends VerifyManyArgs<E, EN, W>>(args?: A): MaybePromise$1<VerifyManyResponse>;
79
+ get<A extends GetArgs<E, EN, W>>(args: A, ctx?: RadsRequestContext): MaybePromise$1<GetResponse<E, EN, A>>;
80
+ getMany<A extends GetManyArgs<E, EN, W>>(args?: A, ctx?: RadsRequestContext): MaybePromise$1<GetManyResponse<E, EN, A>>;
81
+ getAgg<A extends GetAggArgs<EN, W>>(args: A, ctx?: RadsRequestContext): MaybePromise$1<GetAggResponse<EN, A>>;
82
+ getAll<A extends GetManyArgs<E, EN, W>>(args?: A, ctx?: RadsRequestContext): MaybePromise$1<GetManyResponse<E, EN, A>['nodes']>;
83
+ put(data: PutArgs<E>, ctx?: RadsRequestContext): MaybePromise$1<GetResponseNoInclude<E, EN>>;
84
+ putMany(data: PutArgs<E>[], ctx?: RadsRequestContext): MaybePromise$1<GetResponseNoInclude<E, EN>[]>;
85
+ verifyMany<A extends VerifyManyArgs<E, EN, W>>(args?: A, ctx?: RadsRequestContext): MaybePromise$1<VerifyManyResponse>;
89
86
  }
90
87
 
91
88
  type MaybePromise<T> = Promise<T> | T;
@@ -225,6 +222,7 @@ interface FieldDefinition {
225
222
  isRequired?: boolean;
226
223
  isArray?: boolean;
227
224
  isRelation?: boolean;
225
+ isChange?: boolean;
228
226
  relationDenormFields?: string[];
229
227
  comment?: string;
230
228
  decorators?: Record<string, Record<string, any>>;
@@ -320,4 +318,4 @@ declare function computed(meta?: ComputedDecoratorArgs): (a: any, b?: ClassField
320
318
 
321
319
  declare function createRads(args?: CreateRadsArgs): RadsDb;
322
320
 
323
- export { Change, ComputedContext, ComputedDecoratorArgs, CreateRadsArgs, DeepPartial, DeepPartialNullable, Driver, DriverConstructor, EntityDecoratorArgs, EntityMethods, FieldDecoratorArgs, FieldDefinition, FileUploadArgs, FileUploadDriver, GenerateClientNormalizedOptions, GenerateClientOptions, GetAggArgs, GetAggArgsAgg, GetAggArgsAny, GetAggResponse, GetArgs, GetArgsAny, GetArgsInclude, GetManyArgs, GetManyArgsAny, GetManyResponse, GetResponse, GetResponseInclude, GetResponseIncludeSelect, GetResponseNoInclude, GetRestRoutesArgs, GetRestRoutesOptions, GetRestRoutesResponse, GithubTreeItem, GithubTreeResponse, MinimalDriver, PutArgs, PutEffect, RadsFeature, RadsRequestContext, RadsVitePluginOptions, Relation, RestFileUploadDriverOptions, Schema, SchemaValidators, TypeDefinition, UiDecoratorArgs, UiFieldDecoratorArgs, ValidateEntityDecoratorArgs, ValidateFieldDecoratorArgs, ValidateStringDecoratorArgs, VerifyManyArgs, VerifyManyArgsAny, VerifyManyResponse, computed, createRads, entity, field, precomputed, ui, validate };
321
+ export { Change, ComputedContext, ComputedDecoratorArgs, CreateRadsArgs, DeepPartial, Driver, DriverConstructor, EntityDecoratorArgs, EntityMethods, FieldDecoratorArgs, FieldDefinition, FileUploadArgs, FileUploadDriver, GenerateClientNormalizedOptions, GenerateClientOptions, GetAggArgs, GetAggArgsAgg, GetAggArgsAny, GetAggResponse, GetArgs, GetArgsAny, GetArgsInclude, GetManyArgs, GetManyArgsAny, GetManyResponse, GetResponse, GetResponseInclude, GetResponseIncludeSelect, GetResponseNoInclude, GetRestRoutesArgs, GetRestRoutesOptions, GetRestRoutesResponse, GithubTreeItem, GithubTreeResponse, MinimalDriver, PutArgs, PutEffect, RadsFeature, RadsRequestContext, RadsVitePluginOptions, Relation, RestFileUploadDriverOptions, Schema, SchemaValidators, TypeDefinition, UiDecoratorArgs, UiFieldDecoratorArgs, ValidateEntityDecoratorArgs, ValidateFieldDecoratorArgs, ValidateStringDecoratorArgs, VerifyManyArgs, VerifyManyArgsAny, VerifyManyResponse, computed, createRads, entity, field, precomputed, ui, validate };
package/dist/index.mjs CHANGED
@@ -26,7 +26,7 @@ function fillDefaultValues(schema, typeName, value) {
26
26
  return;
27
27
  for (const fName in type.fields) {
28
28
  const field = type.fields[fName];
29
- if (field.defaultValueCopyFrom) {
29
+ if (field.defaultValueCopyFrom && !value[fName]) {
30
30
  value[fName] = _.cloneDeep(value[field.defaultValueCopyFrom]);
31
31
  }
32
32
  }
@@ -63,6 +63,12 @@ function getFieldZodSchema(zodSchemas, schema, field, shouldBeLazy) {
63
63
  return fieldSchema;
64
64
  }
65
65
  function getFieldZodSchemaBase(zodSchemas, schema, field, shouldBeLazy) {
66
+ if (field.isChange) {
67
+ const zodSchema = getZodSchema(zodSchemas, schema, field.type);
68
+ if (!zodSchema)
69
+ throw new Error(`Cannot find zod schema for type: ${field.type}`);
70
+ return zodSchema.deepPartial().omit({ id: true });
71
+ }
66
72
  if (field.type === "string")
67
73
  return z.string();
68
74
  if (field.type === "boolean")
@@ -71,13 +77,6 @@ function getFieldZodSchemaBase(zodSchemas, schema, field, shouldBeLazy) {
71
77
  return z.number();
72
78
  if (field.type === "Record<string, any>")
73
79
  return z.record(z.string(), z.any());
74
- if (field.type.startsWith("Change<")) {
75
- const changeType = field.type.slice(7, -1);
76
- const zodSchema = getZodSchema(zodSchemas, schema, changeType);
77
- if (!zodSchema)
78
- throw new Error(`Cannot find zod schema for type: ${changeType}`);
79
- return zodSchema.deepPartial().omit({ id: true });
80
- }
81
80
  if (schema[field.type]) {
82
81
  const getSchema = () => {
83
82
  let zodSchema = getZodSchema(zodSchemas, schema, field.type);
@@ -539,7 +538,7 @@ function validateEventSourcingSetup(schema, entityName, eventEntityName, aggrega
539
538
  const expectedFields = {
540
539
  id: "string",
541
540
  type: "enum",
542
- change: `Change<${entityName}>`,
541
+ change: entityName,
543
542
  [aggregateRelationField]: entityName,
544
543
  date: "string"
545
544
  };
@@ -553,6 +552,9 @@ function validateEventSourcingSetup(schema, entityName, eventEntityName, aggrega
553
552
  } else {
554
553
  if (field.type !== expectedFields[f])
555
554
  throw new Error(`"${eventEntityName}.${f}" must have type "${expectedFields[f]}"`);
555
+ if (f === "change" && !field.isChange) {
556
+ throw new Error(`"${eventEntityName}.${f}" must have type "Change<${expectedFields[f]}>"`);
557
+ }
556
558
  }
557
559
  }
558
560
  }
@@ -22,7 +22,8 @@ var _default = options => (schema, entity) => {
22
22
  const response = await fetch(url, fetchOptions);
23
23
  const responseJson = response.status === 204 ? null : await response.json();
24
24
  if (!response.ok) {
25
- const err = new Error(response.statusText);
25
+ const msg = responseJson?.message || responseJson?.statusMessage || response.statusText || "Server error.";
26
+ const err = new Error(msg);
26
27
  if (responseJson?.code) err.code = responseJson?.code;
27
28
  err.fetchResponseJson = responseJson;
28
29
  throw err;
@@ -15,7 +15,8 @@ export default (options) => (schema, entity) => {
15
15
  const response = await fetch(url, fetchOptions);
16
16
  const responseJson = response.status === 204 ? null : await response.json();
17
17
  if (!response.ok) {
18
- const err = new Error(response.statusText);
18
+ const msg = responseJson?.message || responseJson?.statusMessage || response.statusText || "Server error.";
19
+ const err = new Error(msg);
19
20
  if (responseJson?.code)
20
21
  err.code = responseJson?.code;
21
22
  err.fetchResponseJson = responseJson;
@@ -207,6 +207,7 @@ function parseClassMember(node, parentName, ctx) {
207
207
  const {
208
208
  isArray,
209
209
  isRelation,
210
+ isChange,
210
211
  relationDenormFields,
211
212
  type
212
213
  } = parseFieldType(ctx, parentName, name, node, defaultValueDescription);
@@ -218,6 +219,7 @@ function parseClassMember(node, parentName, ctx) {
218
219
  isRequired,
219
220
  isArray,
220
221
  isRelation,
222
+ isChange,
221
223
  relationDenormFields,
222
224
  comment
223
225
  };
@@ -251,6 +253,7 @@ function parseFieldType(ctx, parentName, fieldName, node, defaultValueDescriptio
251
253
  }
252
254
  }
253
255
  }
256
+ let type;
254
257
  if (nodeType?.kind === _typescript.SyntaxKind.UnionType) {
255
258
  const newTypeName = `${parentName}_${_lodash.default.upperFirst(fieldName)}`;
256
259
  ctx.result[newTypeName] = {
@@ -258,20 +261,17 @@ function parseFieldType(ctx, parentName, fieldName, node, defaultValueDescriptio
258
261
  decorators: {},
259
262
  enumValues: getEnumValues(nodeType, node, ctx)
260
263
  };
261
- return {
262
- isArray,
263
- isRelation,
264
- relationDenormFields,
265
- type: newTypeName
266
- };
264
+ type = newTypeName;
267
265
  }
268
- const type = nodeType?.getText(ctx.sourceFile) ?? defaultValueDescription?.type;
266
+ type = type ?? nodeType?.getText(ctx.sourceFile) ?? defaultValueDescription?.type;
269
267
  if (!type) throw new Error(`Cannot detect property type: '${node.getText(ctx.sourceFile)}'`);
268
+ let isChange;
270
269
  if (type.startsWith("Change<")) {
271
- const subType = type.slice(7, -1);
272
- if (!ctx.typesMap[subType]) throw new Error(`Unexpected property type: '${type}'`);
270
+ type = type.slice(7, -1);
271
+ if (!ctx.typesMap[type]) throw new Error(`Unexpected property type: '${type}'`);
272
+ isChange = true;
273
273
  } else {
274
- if (!supportedPrimitiveTypes.includes(type) && !ctx.typesMap[type] && type !== "thisReference") {
274
+ if (!supportedPrimitiveTypes.includes(type) && !ctx.typesMap[type] && !ctx.result[type] && type !== "thisReference") {
275
275
  throw new Error(`Unexpected property type: '${type}'`);
276
276
  }
277
277
  }
@@ -281,6 +281,7 @@ function parseFieldType(ctx, parentName, fieldName, node, defaultValueDescriptio
281
281
  return {
282
282
  isArray,
283
283
  isRelation,
284
+ isChange,
284
285
  relationDenormFields,
285
286
  type
286
287
  };
@@ -182,7 +182,7 @@ function parseClassMember(node, parentName, ctx) {
182
182
  const isRequired = !node.questionToken;
183
183
  const comment = node.jsDoc?.[0]?.comment;
184
184
  const decorators = parseDecorators(node.modifiers, ctx);
185
- const { isArray, isRelation, relationDenormFields, type } = parseFieldType(
185
+ const { isArray, isRelation, isChange, relationDenormFields, type } = parseFieldType(
186
186
  ctx,
187
187
  parentName,
188
188
  name,
@@ -197,6 +197,7 @@ function parseClassMember(node, parentName, ctx) {
197
197
  isRequired,
198
198
  isArray,
199
199
  isRelation,
200
+ isChange,
200
201
  relationDenormFields,
201
202
  comment
202
203
  };
@@ -232,6 +233,7 @@ function parseFieldType(ctx, parentName, fieldName, node, defaultValueDescriptio
232
233
  }
233
234
  }
234
235
  }
236
+ let type;
235
237
  if (nodeType?.kind === SyntaxKind.UnionType) {
236
238
  const newTypeName = `${parentName}_${_.upperFirst(fieldName)}`;
237
239
  ctx.result[newTypeName] = {
@@ -239,24 +241,26 @@ function parseFieldType(ctx, parentName, fieldName, node, defaultValueDescriptio
239
241
  decorators: {},
240
242
  enumValues: getEnumValues(nodeType, node, ctx)
241
243
  };
242
- return { isArray, isRelation, relationDenormFields, type: newTypeName };
244
+ type = newTypeName;
243
245
  }
244
- const type = nodeType?.getText(ctx.sourceFile) ?? defaultValueDescription?.type;
246
+ type = type ?? nodeType?.getText(ctx.sourceFile) ?? defaultValueDescription?.type;
245
247
  if (!type)
246
248
  throw new Error(`Cannot detect property type: '${node.getText(ctx.sourceFile)}'`);
249
+ let isChange;
247
250
  if (type.startsWith("Change<")) {
248
- const subType = type.slice(7, -1);
249
- if (!ctx.typesMap[subType])
251
+ type = type.slice(7, -1);
252
+ if (!ctx.typesMap[type])
250
253
  throw new Error(`Unexpected property type: '${type}'`);
254
+ isChange = true;
251
255
  } else {
252
- if (!supportedPrimitiveTypes.includes(type) && !ctx.typesMap[type] && type !== "thisReference") {
256
+ if (!supportedPrimitiveTypes.includes(type) && !ctx.typesMap[type] && !ctx.result[type] && type !== "thisReference") {
253
257
  throw new Error(`Unexpected property type: '${type}'`);
254
258
  }
255
259
  }
256
260
  if (defaultValueDescription && defaultValueDescription.type !== "thisReference") {
257
261
  verifyDefaultValueType(isArray, defaultValueDescription, type, supportedPrimitiveTypes, ctx);
258
262
  }
259
- return { isArray, isRelation, relationDenormFields, type };
263
+ return { isArray, isRelation, isChange, relationDenormFields, type };
260
264
  }
261
265
  function getRelationDenormFields(ctx, node) {
262
266
  if (node.kind === SyntaxKind.LiteralType) {
@@ -128,38 +128,62 @@ function getWhereFieldsFor(schema, type, fieldKey) {
128
128
  name
129
129
  } = field;
130
130
  const fieldTypeName = field.type;
131
- let whereTypeName = fieldTypeName;
132
131
  const fieldType = schema[fieldTypeName];
133
- let result = getWhereFieldsForInner(schema, type, fieldKey);
134
- if (fieldType) {
135
- if (fieldType?.decorators?.entity) {
136
- whereTypeName = `{ id?: string, id_in?: string[] }`;
132
+ const isPrimitive = !fieldType;
133
+ const isEnum = !!fieldType?.enumValues;
134
+ const isObject = !!fieldType?.fields;
135
+ const isRelation = field.isRelation;
136
+ const isRequired = field.isRequired;
137
+ const isArray = field.isArray;
138
+ if (isArray) {
139
+ const arrayWhereFields = [`${name}_isEmpty?: boolean`];
140
+ if (!isRequired) arrayWhereFields.push(`${name}_isNull?: boolean`);
141
+ if (isPrimitive || isEnum) {
142
+ return [`${name}_contains?: ${fieldTypeName}`, ...arrayWhereFields];
137
143
  }
138
- if (fieldType.fields) whereTypeName = `Partial<${whereTypeName}>`;
139
- } else {
140
- result.unshift(`${name}_in?: ${whereTypeName}[]`);
144
+ if (isRelation) {
145
+ return [`${name}_some?: ${getRelationWhereType()}`, ...arrayWhereFields];
146
+ }
147
+ if (isObject) {
148
+ return [`${name}_some?: ${fieldTypeName}_Where`, ...arrayWhereFields];
149
+ }
150
+ throw new Error(`Unknown array type: ${fieldTypeName}`);
141
151
  }
142
- if (field.isArray) {
143
- result = [];
144
- result.unshift(`${name}_contains?: ${whereTypeName}`);
145
- result.unshift(`${name}_isEmpty?: boolean`);
152
+ const commonWhereFields = [];
153
+ if (isRequired) commonWhereFields.push(`${name}_isNull?: boolean`);
154
+ if (isRelation) {
155
+ return [`${name}?: ${getRelationWhereType()}`, ...commonWhereFields];
146
156
  }
147
- if (!field.isRequired) {
148
- result.unshift(`${name}_isNull?: boolean`);
157
+ if (isObject) {
158
+ return [`${name}?: ${fieldTypeName}_Where`, ...commonWhereFields];
149
159
  }
150
- result.unshift(`${name}?: ${whereTypeName}`);
151
- return result;
160
+ if (isEnum) {
161
+ return [`${name}?: ${fieldTypeName}`, ...getWhereFieldsForString(fieldKey), ...commonWhereFields];
162
+ }
163
+ if (isPrimitive) {
164
+ return [`${name}?: ${fieldTypeName}`, ...getWhereFieldsForPrimitive(schema, type, fieldKey), ...commonWhereFields];
165
+ }
166
+ throw new Error(`Unknown type: ${fieldTypeName}`);
167
+ }
168
+ function getRelationWhereType() {
169
+ return "{ id?: string; id_in?: string[] }";
152
170
  }
153
- function getWhereFieldsForInner(schema, type, fieldKey) {
171
+ function getWhereFieldsForPrimitive(schema, type, fieldKey) {
154
172
  const field = type.fields[fieldKey];
155
173
  const {
156
174
  name
157
175
  } = field;
158
176
  if (field.type === "string") {
159
- return [`${name}_istartsWith?: string`, `${name}_startsWith?: string`, `${name}_icontains?: string`, `${name}_contains?: string`, `${name}_iendsWith?: string`, `${name}_endsWith?: string`, `${name}_gt?: string`, `${name}_gte?: string`, `${name}_lt?: string`, `${name}_lte?: string`];
177
+ return getWhereFieldsForString(name);
160
178
  }
161
179
  if (field.type === "number") {
162
180
  return [`${name}_gt?: number`, `${name}_gte?: number`, `${name}_lt?: string`, `${name}_lte?: string`];
163
181
  }
164
- return [];
182
+ if (field.type === "boolean") {
183
+ return [];
184
+ }
185
+ throw new Error(`Unknown primitive type: ${field.type}`);
186
+ }
187
+ function getWhereFieldsForString(name) {
188
+ return [`${name}_istartsWith?: string`, `${name}_startsWith?: string`, `${name}_icontains?: string`, `${name}_contains?: string`, `${name}_iendsWith?: string`, `${name}_endsWith?: string`, `${name}_gt?: string`, `${name}_gte?: string`, `${name}_lt?: string`, `${name}_lte?: string`];
165
189
  }
@@ -133,48 +133,73 @@ function getWhereFieldsFor(schema, type, fieldKey) {
133
133
  const field = type.fields[fieldKey];
134
134
  const { name } = field;
135
135
  const fieldTypeName = field.type;
136
- let whereTypeName = fieldTypeName;
137
136
  const fieldType = schema[fieldTypeName];
138
- let result = getWhereFieldsForInner(schema, type, fieldKey);
139
- if (fieldType) {
140
- if (fieldType?.decorators?.entity) {
141
- whereTypeName = `{ id?: string, id_in?: string[] }`;
137
+ const isPrimitive = !fieldType;
138
+ const isEnum = !!fieldType?.enumValues;
139
+ const isObject = !!fieldType?.fields;
140
+ const isRelation = field.isRelation;
141
+ const isRequired = field.isRequired;
142
+ const isArray = field.isArray;
143
+ if (isArray) {
144
+ const arrayWhereFields = [`${name}_isEmpty?: boolean`];
145
+ if (!isRequired)
146
+ arrayWhereFields.push(`${name}_isNull?: boolean`);
147
+ if (isPrimitive || isEnum) {
148
+ return [`${name}_contains?: ${fieldTypeName}`, ...arrayWhereFields];
142
149
  }
143
- if (fieldType.fields)
144
- whereTypeName = `Partial<${whereTypeName}>`;
145
- } else {
146
- result.unshift(`${name}_in?: ${whereTypeName}[]`);
150
+ if (isRelation) {
151
+ return [`${name}_some?: ${getRelationWhereType()}`, ...arrayWhereFields];
152
+ }
153
+ if (isObject) {
154
+ return [`${name}_some?: ${fieldTypeName}_Where`, ...arrayWhereFields];
155
+ }
156
+ throw new Error(`Unknown array type: ${fieldTypeName}`);
147
157
  }
148
- if (field.isArray) {
149
- result = [];
150
- result.unshift(`${name}_contains?: ${whereTypeName}`);
151
- result.unshift(`${name}_isEmpty?: boolean`);
158
+ const commonWhereFields = [];
159
+ if (isRequired)
160
+ commonWhereFields.push(`${name}_isNull?: boolean`);
161
+ if (isRelation) {
162
+ return [`${name}?: ${getRelationWhereType()}`, ...commonWhereFields];
152
163
  }
153
- if (!field.isRequired) {
154
- result.unshift(`${name}_isNull?: boolean`);
164
+ if (isObject) {
165
+ return [`${name}?: ${fieldTypeName}_Where`, ...commonWhereFields];
155
166
  }
156
- result.unshift(`${name}?: ${whereTypeName}`);
157
- return result;
167
+ if (isEnum) {
168
+ return [`${name}?: ${fieldTypeName}`, ...getWhereFieldsForString(fieldKey), ...commonWhereFields];
169
+ }
170
+ if (isPrimitive) {
171
+ return [`${name}?: ${fieldTypeName}`, ...getWhereFieldsForPrimitive(schema, type, fieldKey), ...commonWhereFields];
172
+ }
173
+ throw new Error(`Unknown type: ${fieldTypeName}`);
174
+ }
175
+ function getRelationWhereType() {
176
+ return "{ id?: string; id_in?: string[] }";
158
177
  }
159
- function getWhereFieldsForInner(schema, type, fieldKey) {
178
+ function getWhereFieldsForPrimitive(schema, type, fieldKey) {
160
179
  const field = type.fields[fieldKey];
161
180
  const { name } = field;
162
181
  if (field.type === "string") {
163
- return [
164
- `${name}_istartsWith?: string`,
165
- `${name}_startsWith?: string`,
166
- `${name}_icontains?: string`,
167
- `${name}_contains?: string`,
168
- `${name}_iendsWith?: string`,
169
- `${name}_endsWith?: string`,
170
- `${name}_gt?: string`,
171
- `${name}_gte?: string`,
172
- `${name}_lt?: string`,
173
- `${name}_lte?: string`
174
- ];
182
+ return getWhereFieldsForString(name);
175
183
  }
176
184
  if (field.type === "number") {
177
185
  return [`${name}_gt?: number`, `${name}_gte?: number`, `${name}_lt?: string`, `${name}_lte?: string`];
178
186
  }
179
- return [];
187
+ if (field.type === "boolean") {
188
+ return [];
189
+ }
190
+ throw new Error(`Unknown primitive type: ${field.type}`);
191
+ }
192
+ function getWhereFieldsForString(name) {
193
+ return [
194
+ `${name}_istartsWith?: string`,
195
+ `${name}_startsWith?: string`,
196
+ `${name}_icontains?: string`,
197
+ `${name}_contains?: string`,
198
+ `${name}_iendsWith?: string`,
199
+ `${name}_endsWith?: string`,
200
+ `${name}_gt?: string`,
201
+ `${name}_gte?: string`,
202
+ `${name}_lt?: string`,
203
+ `${name}_lte?: string`
204
+ ];
180
205
  }
package/package.json CHANGED
@@ -40,7 +40,7 @@
40
40
  "require": "./features/*.cjs"
41
41
  }
42
42
  },
43
- "version": "0.1.78",
43
+ "version": "0.1.80",
44
44
  "description": "Say goodbye to boilerplate code and hello to efficient and elegant syntax.",
45
45
  "keywords": [],
46
46
  "author": "",
@@ -97,7 +97,7 @@
97
97
  "generate-test-schema": "rads-db",
98
98
  "dev": "pnpm install && pnpm build && pnpm generate-test-schema && pnpm link-rads-db && vitest --ui",
99
99
  "lint": "cross-env NODE_ENV=production eslint src/**/*.* test/**/*.*",
100
- "dev-typecheck": "vitest typecheck --ui",
100
+ "dev-typecheck": "pnpm install && pnpm build && pnpm generate-test-schema && pnpm link-rads-db && vitest typecheck --ui",
101
101
  "build": "unbuild"
102
102
  }
103
103
  }