appwrite-utils-cli 0.9.2 → 0.9.4

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.
@@ -1,473 +1,473 @@
1
- import { toCamelCase, toPascalCase } from "../utils/index.js";
2
- import { Databases } from "node-appwrite";
3
- import type {
4
- AppwriteConfig,
5
- Attribute,
6
- RelationshipAttribute,
7
- } from "appwrite-utils";
8
- import { z } from "zod";
9
- import fs from "fs";
10
- import path from "path";
11
- import { dump } from "js-yaml";
12
- // import { getClientFromConfig } from "./getClientFromConfig.js";
13
-
14
- interface RelationshipDetail {
15
- parentCollection: string;
16
- childCollection: string;
17
- parentKey: string;
18
- childKey: string;
19
- isArray: boolean;
20
- isChild: boolean;
21
- }
22
-
23
- export class SchemaGenerator {
24
- private relationshipMap = new Map<string, RelationshipDetail[]>();
25
- private config: AppwriteConfig;
26
- private appwriteFolderPath: string;
27
-
28
- constructor(config: AppwriteConfig, appwriteFolderPath: string) {
29
- this.config = config;
30
- this.appwriteFolderPath = appwriteFolderPath;
31
- this.extractRelationships();
32
- }
33
-
34
- public updateTsSchemas(): void {
35
- const collections = this.config.collections;
36
- delete this.config.collections;
37
-
38
- const configPath = path.join(this.appwriteFolderPath, "appwriteConfig.ts");
39
- const configContent = `import { type AppwriteConfig } from "appwrite-utils";
40
-
41
- const appwriteConfig: AppwriteConfig = {
42
- appwriteEndpoint: "${this.config.appwriteEndpoint}",
43
- appwriteProject: "${this.config.appwriteProject}",
44
- appwriteKey: "${this.config.appwriteKey}",
45
- enableBackups: ${this.config.enableBackups},
46
- backupInterval: ${this.config.backupInterval},
47
- backupRetention: ${this.config.backupRetention},
48
- enableBackupCleanup: ${this.config.enableBackupCleanup},
49
- enableMockData: ${this.config.enableMockData},
50
- documentBucketId: "${this.config.documentBucketId}",
51
- usersCollectionName: "${this.config.usersCollectionName}",
52
- databases: ${JSON.stringify(this.config.databases)},
53
- buckets: ${JSON.stringify(this.config.buckets)},
54
- };
55
-
56
- export default appwriteConfig;
57
- `;
58
- fs.writeFileSync(configPath, configContent, { encoding: "utf-8" });
59
-
60
- const collectionsFolderPath = path.join(
61
- this.appwriteFolderPath,
62
- "collections"
63
- );
64
- if (!fs.existsSync(collectionsFolderPath)) {
65
- fs.mkdirSync(collectionsFolderPath, { recursive: true });
66
- }
67
-
68
- collections?.forEach((collection) => {
69
- const { databaseId, ...collectionWithoutDbId } = collection; // Destructure to exclude databaseId
70
- const collectionFilePath = path.join(
71
- collectionsFolderPath,
72
- `${collection.name}.ts`
73
- );
74
- const collectionContent = `import { type CollectionCreate } from "appwrite-utils";
75
-
76
- const ${collection.name}Config: Partial<CollectionCreate> = {
77
- name: "${collection.name}",
78
- $id: "${collection.$id}",
79
- enabled: ${collection.enabled},
80
- documentSecurity: ${collection.documentSecurity},
81
- $permissions: [
82
- ${collection.$permissions
83
- .map(
84
- (permission) =>
85
- `{ permission: "${permission.permission}", target: "${permission.target}" }`
86
- )
87
- .join(",\n ")}
88
- ],
89
- attributes: [
90
- ${collection.attributes
91
- .map((attr) => {
92
- return `{ ${Object.entries(attr)
93
- .map(([key, value]) => {
94
- // Check the type of the value and format it accordingly
95
- if (typeof value === "string") {
96
- // If the value is a string, wrap it in quotes
97
- return `${key}: "${value.replace(/"/g, '\\"')}"`; // Escape existing quotes in the string
98
- } else if (Array.isArray(value)) {
99
- // If the value is an array, join it with commas
100
- if (value.length > 0) {
101
- return `${key}: [${value
102
- .map((item) => `"${item}"`)
103
- .join(", ")}]`;
104
- } else {
105
- return `${key}: []`;
106
- }
107
- } else {
108
- // If the value is not a string (e.g., boolean or number), output it directly
109
- return `${key}: ${value}`;
110
- }
111
- })
112
- .join(", ")} }`;
113
- })
114
- .join(",\n ")}
115
- ],
116
- indexes: [
117
- ${(
118
- collection.indexes?.map((index) => {
119
- // Map each attribute to ensure it is properly quoted
120
- const formattedAttributes =
121
- index.attributes.map((attr) => `"${attr}"`).join(", ") ?? "";
122
- return `{ key: "${index.key}", type: "${
123
- index.type
124
- }", attributes: [${formattedAttributes}], orders: [${
125
- index.orders
126
- ?.filter((order) => order !== null)
127
- .map((order) => `"${order}"`)
128
- .join(", ") ?? ""
129
- }] }`;
130
- }) ?? []
131
- ).join(",\n ")}
132
- ]
133
- };
134
-
135
- export default ${collection.name}Config;
136
- `;
137
- fs.writeFileSync(collectionFilePath, collectionContent, {
138
- encoding: "utf-8",
139
- });
140
- console.log(`Collection schema written to ${collectionFilePath}`);
141
- });
142
- }
143
-
144
- private extractRelationships(): void {
145
- if (!this.config.collections) {
146
- return;
147
- }
148
- this.config.collections.forEach((collection) => {
149
- collection.attributes.forEach((attr) => {
150
- if (attr.type === "relationship" && attr.twoWay && attr.twoWayKey) {
151
- const relationshipAttr = attr as RelationshipAttribute;
152
- let isArrayParent = false;
153
- let isArrayChild = false;
154
- switch (relationshipAttr.relationType) {
155
- case "oneToMany":
156
- isArrayParent = true;
157
- isArrayChild = false;
158
- break;
159
- case "manyToMany":
160
- isArrayParent = true;
161
- isArrayChild = true;
162
- break;
163
- case "oneToOne":
164
- isArrayParent = false;
165
- isArrayChild = false;
166
- break;
167
- case "manyToOne":
168
- isArrayParent = false;
169
- isArrayChild = true;
170
- break;
171
- default:
172
- break;
173
- }
174
- this.addRelationship(
175
- collection.name,
176
- relationshipAttr.relatedCollection,
177
- attr.key,
178
- relationshipAttr.twoWayKey,
179
- isArrayParent,
180
- isArrayChild
181
- );
182
- console.log(
183
- `Extracted relationship: ${attr.key}\n\t${collection.name} -> ${relationshipAttr.relatedCollection}, databaseId: ${collection.databaseId}`
184
- );
185
- }
186
- });
187
- });
188
- }
189
-
190
- private addRelationship(
191
- parentCollection: string,
192
- childCollection: string,
193
- parentKey: string,
194
- childKey: string,
195
- isArrayParent: boolean,
196
- isArrayChild: boolean
197
- ): void {
198
- const relationshipsChild = this.relationshipMap.get(childCollection) || [];
199
- const relationshipsParent =
200
- this.relationshipMap.get(parentCollection) || [];
201
- relationshipsParent.push({
202
- parentCollection,
203
- childCollection,
204
- parentKey,
205
- childKey,
206
- isArray: isArrayParent,
207
- isChild: false,
208
- });
209
- relationshipsChild.push({
210
- parentCollection,
211
- childCollection,
212
- parentKey,
213
- childKey,
214
- isArray: isArrayChild,
215
- isChild: true,
216
- });
217
- this.relationshipMap.set(childCollection, relationshipsChild);
218
- this.relationshipMap.set(parentCollection, relationshipsParent);
219
- }
220
-
221
- public generateSchemas(): void {
222
- if (!this.config.collections) {
223
- return;
224
- }
225
- this.config.collections.forEach((collection) => {
226
- const schemaString = this.createSchemaString(
227
- collection.name,
228
- collection.attributes
229
- );
230
- const camelCaseName = toCamelCase(collection.name);
231
- const schemaPath = path.join(
232
- this.appwriteFolderPath,
233
- "schemas",
234
- `${camelCaseName}.ts`
235
- );
236
- fs.writeFileSync(schemaPath, schemaString, { encoding: "utf-8" });
237
- console.log(`Schema written to ${schemaPath}`);
238
- });
239
- }
240
-
241
- createSchemaString = (name: string, attributes: Attribute[]): string => {
242
- const pascalName = toPascalCase(name);
243
- let imports = `import { z } from "zod";\n`;
244
- const hasDescription = attributes.some((attr) => attr.description);
245
- if (hasDescription) {
246
- imports += `import { extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi";\n`;
247
- imports += `extendZodWithOpenApi(z);\n`;
248
- }
249
-
250
- // Use the relationshipMap to find related collections
251
- const relationshipDetails = this.relationshipMap.get(name) || [];
252
- const relatedCollections = relationshipDetails
253
- .filter((detail, index, self) => {
254
- const uniqueKey = `${detail.parentCollection}-${detail.childCollection}-${detail.parentKey}-${detail.childKey}`;
255
- return (
256
- index ===
257
- self.findIndex(
258
- (obj) =>
259
- `${obj.parentCollection}-${obj.childCollection}-${obj.parentKey}-${obj.childKey}` ===
260
- uniqueKey
261
- )
262
- );
263
- })
264
- .map((detail) => {
265
- const relatedCollectionName = detail.isChild
266
- ? detail.parentCollection
267
- : detail.childCollection;
268
- const key = detail.isChild ? detail.childKey : detail.parentKey;
269
- const isArray = detail.isArray ? "array" : "";
270
- return [relatedCollectionName, key, isArray];
271
- });
272
-
273
- let relatedTypes = "";
274
- let relatedTypesLazy = "";
275
- let curNum = 0;
276
- let maxNum = relatedCollections.length;
277
- relatedCollections.forEach((relatedCollection) => {
278
- console.log(relatedCollection);
279
- let relatedPascalName = toPascalCase(relatedCollection[0]);
280
- let relatedCamelName = toCamelCase(relatedCollection[0]);
281
- curNum++;
282
- let endNameTypes = relatedPascalName;
283
- let endNameLazy = `${relatedPascalName}Schema`;
284
- if (relatedCollection[2] === "array") {
285
- endNameTypes += "[]";
286
- endNameLazy += ".array().default([])";
287
- } else if (!(relatedCollection[2] === "array")) {
288
- endNameTypes += " | null";
289
- endNameLazy += ".nullish()";
290
- }
291
- imports += `import { ${relatedPascalName}Schema, type ${relatedPascalName} } from "./${relatedCamelName}";\n`;
292
- relatedTypes += `${relatedCollection[1]}?: ${endNameTypes};\n`;
293
- if (relatedTypes.length > 0 && curNum !== maxNum) {
294
- relatedTypes += " ";
295
- }
296
- relatedTypesLazy += `${relatedCollection[1]}: z.lazy(() => ${endNameLazy}),\n`;
297
- if (relatedTypesLazy.length > 0 && curNum !== maxNum) {
298
- relatedTypesLazy += " ";
299
- }
300
- });
301
-
302
- let schemaString = `${imports}\n\n`;
303
- schemaString += `export const ${pascalName}SchemaBase = z.object({\n`;
304
- schemaString += ` $id: z.string().optional(),\n`;
305
- schemaString += ` $createdAt: z.date().or(z.string()).optional(),\n`;
306
- schemaString += ` $updatedAt: z.date().or(z.string()).optional(),\n`;
307
- for (const attribute of attributes) {
308
- if (attribute.type === "relationship") {
309
- continue;
310
- }
311
- schemaString += ` ${attribute.key}: ${this.typeToZod(attribute)},\n`;
312
- }
313
- schemaString += `});\n\n`;
314
- schemaString += `export type ${pascalName}Base = z.infer<typeof ${pascalName}SchemaBase>`;
315
- if (relatedTypes.length > 0) {
316
- schemaString += ` & {\n ${relatedTypes}};\n\n`;
317
- } else {
318
- schemaString += `;\n\n`;
319
- }
320
- schemaString += `export const ${pascalName}Schema: z.ZodType<${pascalName}Base> = ${pascalName}SchemaBase`;
321
- if (relatedTypes.length > 0) {
322
- schemaString += `.extend({\n ${relatedTypesLazy}});\n\n`;
323
- } else {
324
- schemaString += `;\n`;
325
- }
326
- schemaString += `export type ${pascalName} = z.infer<typeof ${pascalName}Schema>;\n\n`;
327
-
328
- return schemaString;
329
- };
330
-
331
- typeToZod = (attribute: Attribute) => {
332
- let baseSchemaCode = "";
333
- const finalAttribute: Attribute = (
334
- attribute.type === "string" &&
335
- attribute.format &&
336
- attribute.format === "enum" &&
337
- attribute.type === "string"
338
- ? { ...attribute, type: attribute.format }
339
- : attribute
340
- ) as Attribute;
341
- switch (finalAttribute.type) {
342
- case "string":
343
- baseSchemaCode = "z.string()";
344
- if (finalAttribute.size) {
345
- baseSchemaCode += `.max(${finalAttribute.size}, "Maximum length of ${finalAttribute.size} characters exceeded")`;
346
- }
347
- if (finalAttribute.xdefault !== undefined) {
348
- baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
349
- }
350
- if (!attribute.required && !attribute.array) {
351
- baseSchemaCode += ".nullish()";
352
- }
353
- break;
354
- case "integer":
355
- baseSchemaCode = "z.number().int()";
356
- if (finalAttribute.min !== undefined) {
357
- if (BigInt(finalAttribute.min) === BigInt(-9223372036854776000)) {
358
- delete finalAttribute.min;
359
- } else {
360
- baseSchemaCode += `.min(${finalAttribute.min}, "Minimum value of ${finalAttribute.min} not met")`;
361
- }
362
- }
363
- if (finalAttribute.max !== undefined) {
364
- if (BigInt(finalAttribute.max) === BigInt(9223372036854776000)) {
365
- delete finalAttribute.max;
366
- } else {
367
- baseSchemaCode += `.max(${finalAttribute.max}, "Maximum value of ${finalAttribute.max} exceeded")`;
368
- }
369
- }
370
- if (finalAttribute.xdefault !== undefined) {
371
- baseSchemaCode += `.default(${finalAttribute.xdefault})`;
372
- }
373
- if (!finalAttribute.required && !finalAttribute.array) {
374
- baseSchemaCode += ".nullish()";
375
- }
376
- break;
377
- case "float":
378
- baseSchemaCode = "z.number()";
379
- if (finalAttribute.min !== undefined) {
380
- baseSchemaCode += `.min(${finalAttribute.min}, "Minimum value of ${finalAttribute.min} not met")`;
381
- }
382
- if (finalAttribute.max !== undefined) {
383
- baseSchemaCode += `.max(${finalAttribute.max}, "Maximum value of ${finalAttribute.max} exceeded")`;
384
- }
385
- if (finalAttribute.xdefault !== undefined) {
386
- baseSchemaCode += `.default(${finalAttribute.xdefault})`;
387
- }
388
- if (!finalAttribute.required && !finalAttribute.array) {
389
- baseSchemaCode += ".nullish()";
390
- }
391
- break;
392
- case "boolean":
393
- baseSchemaCode = "z.boolean()";
394
- if (finalAttribute.xdefault !== undefined) {
395
- baseSchemaCode += `.default(${finalAttribute.xdefault})`;
396
- }
397
- if (!finalAttribute.required && !finalAttribute.array) {
398
- baseSchemaCode += ".nullish()";
399
- }
400
- break;
401
- case "datetime":
402
- baseSchemaCode = "z.date()";
403
- if (finalAttribute.xdefault !== undefined) {
404
- baseSchemaCode += `.default(new Date("${finalAttribute.xdefault}"))`;
405
- }
406
- if (!finalAttribute.required && !finalAttribute.array) {
407
- baseSchemaCode += ".nullish()";
408
- }
409
- break;
410
- case "email":
411
- baseSchemaCode = "z.string().email()";
412
- if (finalAttribute.xdefault !== undefined) {
413
- baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
414
- }
415
- if (!finalAttribute.required && !finalAttribute.array) {
416
- baseSchemaCode += ".nullish()";
417
- }
418
- break;
419
- case "ip":
420
- baseSchemaCode = "z.string()"; // Add custom validation as needed
421
- if (finalAttribute.xdefault !== undefined) {
422
- baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
423
- }
424
- if (!finalAttribute.required && !finalAttribute.array) {
425
- baseSchemaCode += ".nullish()";
426
- }
427
- break;
428
- case "url":
429
- baseSchemaCode = "z.string().url()";
430
- if (finalAttribute.xdefault !== undefined) {
431
- baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
432
- }
433
- if (!finalAttribute.required && !finalAttribute.array) {
434
- baseSchemaCode += ".nullish()";
435
- }
436
- break;
437
- case "enum":
438
- baseSchemaCode = `z.enum([${finalAttribute.elements
439
- .map((element) => `"${element}"`)
440
- .join(", ")}])`;
441
- if (finalAttribute.xdefault !== undefined) {
442
- baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
443
- }
444
- if (!attribute.required && !attribute.array) {
445
- baseSchemaCode += ".nullish()";
446
- }
447
- break;
448
- case "relationship":
449
- break;
450
- default:
451
- baseSchemaCode = "z.any()";
452
- }
453
-
454
- // Handle arrays
455
- if (attribute.array) {
456
- baseSchemaCode = `z.array(${baseSchemaCode})`;
457
- }
458
- if (attribute.array && !attribute.required) {
459
- baseSchemaCode += ".nullish()";
460
- }
461
- if (attribute.description) {
462
- if (typeof attribute.description === "string") {
463
- baseSchemaCode += `.openapi({ description: "${attribute.description}" })`;
464
- } else {
465
- baseSchemaCode += `.openapi(${Object.entries(attribute.description)
466
- .map(([key, value]) => `"${key}": ${value}`)
467
- .join(", ")})`;
468
- }
469
- }
470
-
471
- return baseSchemaCode;
472
- };
473
- }
1
+ import { toCamelCase, toPascalCase } from "../utils/index.js";
2
+ import { Databases } from "node-appwrite";
3
+ import type {
4
+ AppwriteConfig,
5
+ Attribute,
6
+ RelationshipAttribute,
7
+ } from "appwrite-utils";
8
+ import { z } from "zod";
9
+ import fs from "fs";
10
+ import path from "path";
11
+ import { dump } from "js-yaml";
12
+ // import { getClientFromConfig } from "./getClientFromConfig.js";
13
+
14
+ interface RelationshipDetail {
15
+ parentCollection: string;
16
+ childCollection: string;
17
+ parentKey: string;
18
+ childKey: string;
19
+ isArray: boolean;
20
+ isChild: boolean;
21
+ }
22
+
23
+ export class SchemaGenerator {
24
+ private relationshipMap = new Map<string, RelationshipDetail[]>();
25
+ private config: AppwriteConfig;
26
+ private appwriteFolderPath: string;
27
+
28
+ constructor(config: AppwriteConfig, appwriteFolderPath: string) {
29
+ this.config = config;
30
+ this.appwriteFolderPath = appwriteFolderPath;
31
+ this.extractRelationships();
32
+ }
33
+
34
+ public updateTsSchemas(): void {
35
+ const collections = this.config.collections;
36
+ delete this.config.collections;
37
+
38
+ const configPath = path.join(this.appwriteFolderPath, "appwriteConfig.ts");
39
+ const configContent = `import { type AppwriteConfig } from "appwrite-utils";
40
+
41
+ const appwriteConfig: AppwriteConfig = {
42
+ appwriteEndpoint: "${this.config.appwriteEndpoint}",
43
+ appwriteProject: "${this.config.appwriteProject}",
44
+ appwriteKey: "${this.config.appwriteKey}",
45
+ enableBackups: ${this.config.enableBackups},
46
+ backupInterval: ${this.config.backupInterval},
47
+ backupRetention: ${this.config.backupRetention},
48
+ enableBackupCleanup: ${this.config.enableBackupCleanup},
49
+ enableMockData: ${this.config.enableMockData},
50
+ documentBucketId: "${this.config.documentBucketId}",
51
+ usersCollectionName: "${this.config.usersCollectionName}",
52
+ databases: ${JSON.stringify(this.config.databases)},
53
+ buckets: ${JSON.stringify(this.config.buckets)},
54
+ };
55
+
56
+ export default appwriteConfig;
57
+ `;
58
+ fs.writeFileSync(configPath, configContent, { encoding: "utf-8" });
59
+
60
+ const collectionsFolderPath = path.join(
61
+ this.appwriteFolderPath,
62
+ "collections"
63
+ );
64
+ if (!fs.existsSync(collectionsFolderPath)) {
65
+ fs.mkdirSync(collectionsFolderPath, { recursive: true });
66
+ }
67
+
68
+ collections?.forEach((collection) => {
69
+ const { databaseId, ...collectionWithoutDbId } = collection; // Destructure to exclude databaseId
70
+ const collectionFilePath = path.join(
71
+ collectionsFolderPath,
72
+ `${collection.name}.ts`
73
+ );
74
+ const collectionContent = `import { type CollectionCreate } from "appwrite-utils";
75
+
76
+ const ${collection.name}Config: Partial<CollectionCreate> = {
77
+ name: "${collection.name}",
78
+ $id: "${collection.$id}",
79
+ enabled: ${collection.enabled},
80
+ documentSecurity: ${collection.documentSecurity},
81
+ $permissions: [
82
+ ${collection.$permissions
83
+ .map(
84
+ (permission) =>
85
+ `{ permission: "${permission.permission}", target: "${permission.target}" }`
86
+ )
87
+ .join(",\n ")}
88
+ ],
89
+ attributes: [
90
+ ${collection.attributes
91
+ .map((attr) => {
92
+ return `{ ${Object.entries(attr)
93
+ .map(([key, value]) => {
94
+ // Check the type of the value and format it accordingly
95
+ if (typeof value === "string") {
96
+ // If the value is a string, wrap it in quotes
97
+ return `${key}: "${value.replace(/"/g, '\\"')}"`; // Escape existing quotes in the string
98
+ } else if (Array.isArray(value)) {
99
+ // If the value is an array, join it with commas
100
+ if (value.length > 0) {
101
+ return `${key}: [${value
102
+ .map((item) => `"${item}"`)
103
+ .join(", ")}]`;
104
+ } else {
105
+ return `${key}: []`;
106
+ }
107
+ } else {
108
+ // If the value is not a string (e.g., boolean or number), output it directly
109
+ return `${key}: ${value}`;
110
+ }
111
+ })
112
+ .join(", ")} }`;
113
+ })
114
+ .join(",\n ")}
115
+ ],
116
+ indexes: [
117
+ ${(
118
+ collection.indexes?.map((index) => {
119
+ // Map each attribute to ensure it is properly quoted
120
+ const formattedAttributes =
121
+ index.attributes.map((attr) => `"${attr}"`).join(", ") ?? "";
122
+ return `{ key: "${index.key}", type: "${
123
+ index.type
124
+ }", attributes: [${formattedAttributes}], orders: [${
125
+ index.orders
126
+ ?.filter((order) => order !== null)
127
+ .map((order) => `"${order}"`)
128
+ .join(", ") ?? ""
129
+ }] }`;
130
+ }) ?? []
131
+ ).join(",\n ")}
132
+ ]
133
+ };
134
+
135
+ export default ${collection.name}Config;
136
+ `;
137
+ fs.writeFileSync(collectionFilePath, collectionContent, {
138
+ encoding: "utf-8",
139
+ });
140
+ console.log(`Collection schema written to ${collectionFilePath}`);
141
+ });
142
+ }
143
+
144
+ private extractRelationships(): void {
145
+ if (!this.config.collections) {
146
+ return;
147
+ }
148
+ this.config.collections.forEach((collection) => {
149
+ collection.attributes.forEach((attr) => {
150
+ if (attr.type === "relationship" && attr.twoWay && attr.twoWayKey) {
151
+ const relationshipAttr = attr as RelationshipAttribute;
152
+ let isArrayParent = false;
153
+ let isArrayChild = false;
154
+ switch (relationshipAttr.relationType) {
155
+ case "oneToMany":
156
+ isArrayParent = true;
157
+ isArrayChild = false;
158
+ break;
159
+ case "manyToMany":
160
+ isArrayParent = true;
161
+ isArrayChild = true;
162
+ break;
163
+ case "oneToOne":
164
+ isArrayParent = false;
165
+ isArrayChild = false;
166
+ break;
167
+ case "manyToOne":
168
+ isArrayParent = false;
169
+ isArrayChild = true;
170
+ break;
171
+ default:
172
+ break;
173
+ }
174
+ this.addRelationship(
175
+ collection.name,
176
+ relationshipAttr.relatedCollection,
177
+ attr.key,
178
+ relationshipAttr.twoWayKey,
179
+ isArrayParent,
180
+ isArrayChild
181
+ );
182
+ console.log(
183
+ `Extracted relationship: ${attr.key}\n\t${collection.name} -> ${relationshipAttr.relatedCollection}, databaseId: ${collection.databaseId}`
184
+ );
185
+ }
186
+ });
187
+ });
188
+ }
189
+
190
+ private addRelationship(
191
+ parentCollection: string,
192
+ childCollection: string,
193
+ parentKey: string,
194
+ childKey: string,
195
+ isArrayParent: boolean,
196
+ isArrayChild: boolean
197
+ ): void {
198
+ const relationshipsChild = this.relationshipMap.get(childCollection) || [];
199
+ const relationshipsParent =
200
+ this.relationshipMap.get(parentCollection) || [];
201
+ relationshipsParent.push({
202
+ parentCollection,
203
+ childCollection,
204
+ parentKey,
205
+ childKey,
206
+ isArray: isArrayParent,
207
+ isChild: false,
208
+ });
209
+ relationshipsChild.push({
210
+ parentCollection,
211
+ childCollection,
212
+ parentKey,
213
+ childKey,
214
+ isArray: isArrayChild,
215
+ isChild: true,
216
+ });
217
+ this.relationshipMap.set(childCollection, relationshipsChild);
218
+ this.relationshipMap.set(parentCollection, relationshipsParent);
219
+ }
220
+
221
+ public generateSchemas(): void {
222
+ if (!this.config.collections) {
223
+ return;
224
+ }
225
+ this.config.collections.forEach((collection) => {
226
+ const schemaString = this.createSchemaString(
227
+ collection.name,
228
+ collection.attributes
229
+ );
230
+ const camelCaseName = toCamelCase(collection.name);
231
+ const schemaPath = path.join(
232
+ this.appwriteFolderPath,
233
+ "schemas",
234
+ `${camelCaseName}.ts`
235
+ );
236
+ fs.writeFileSync(schemaPath, schemaString, { encoding: "utf-8" });
237
+ console.log(`Schema written to ${schemaPath}`);
238
+ });
239
+ }
240
+
241
+ createSchemaString = (name: string, attributes: Attribute[]): string => {
242
+ const pascalName = toPascalCase(name);
243
+ let imports = `import { z } from "zod";\n`;
244
+ const hasDescription = attributes.some((attr) => attr.description);
245
+ if (hasDescription) {
246
+ imports += `import { extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi";\n`;
247
+ imports += `extendZodWithOpenApi(z);\n`;
248
+ }
249
+
250
+ // Use the relationshipMap to find related collections
251
+ const relationshipDetails = this.relationshipMap.get(name) || [];
252
+ const relatedCollections = relationshipDetails
253
+ .filter((detail, index, self) => {
254
+ const uniqueKey = `${detail.parentCollection}-${detail.childCollection}-${detail.parentKey}-${detail.childKey}`;
255
+ return (
256
+ index ===
257
+ self.findIndex(
258
+ (obj) =>
259
+ `${obj.parentCollection}-${obj.childCollection}-${obj.parentKey}-${obj.childKey}` ===
260
+ uniqueKey
261
+ )
262
+ );
263
+ })
264
+ .map((detail) => {
265
+ const relatedCollectionName = detail.isChild
266
+ ? detail.parentCollection
267
+ : detail.childCollection;
268
+ const key = detail.isChild ? detail.childKey : detail.parentKey;
269
+ const isArray = detail.isArray ? "array" : "";
270
+ return [relatedCollectionName, key, isArray];
271
+ });
272
+
273
+ let relatedTypes = "";
274
+ let relatedTypesLazy = "";
275
+ let curNum = 0;
276
+ let maxNum = relatedCollections.length;
277
+ relatedCollections.forEach((relatedCollection) => {
278
+ console.log(relatedCollection);
279
+ let relatedPascalName = toPascalCase(relatedCollection[0]);
280
+ let relatedCamelName = toCamelCase(relatedCollection[0]);
281
+ curNum++;
282
+ let endNameTypes = relatedPascalName;
283
+ let endNameLazy = `${relatedPascalName}Schema`;
284
+ if (relatedCollection[2] === "array") {
285
+ endNameTypes += "[]";
286
+ endNameLazy += ".array().default([])";
287
+ } else if (!(relatedCollection[2] === "array")) {
288
+ endNameTypes += " | null";
289
+ endNameLazy += ".nullish()";
290
+ }
291
+ imports += `import { ${relatedPascalName}Schema, type ${relatedPascalName} } from "./${relatedCamelName}";\n`;
292
+ relatedTypes += `${relatedCollection[1]}?: ${endNameTypes};\n`;
293
+ if (relatedTypes.length > 0 && curNum !== maxNum) {
294
+ relatedTypes += " ";
295
+ }
296
+ relatedTypesLazy += `${relatedCollection[1]}: z.lazy(() => ${endNameLazy}),\n`;
297
+ if (relatedTypesLazy.length > 0 && curNum !== maxNum) {
298
+ relatedTypesLazy += " ";
299
+ }
300
+ });
301
+
302
+ let schemaString = `${imports}\n\n`;
303
+ schemaString += `export const ${pascalName}SchemaBase = z.object({\n`;
304
+ schemaString += ` $id: z.string().optional(),\n`;
305
+ schemaString += ` $createdAt: z.date().or(z.string()).optional(),\n`;
306
+ schemaString += ` $updatedAt: z.date().or(z.string()).optional(),\n`;
307
+ for (const attribute of attributes) {
308
+ if (attribute.type === "relationship") {
309
+ continue;
310
+ }
311
+ schemaString += ` ${attribute.key}: ${this.typeToZod(attribute)},\n`;
312
+ }
313
+ schemaString += `});\n\n`;
314
+ schemaString += `export type ${pascalName}Base = z.infer<typeof ${pascalName}SchemaBase>`;
315
+ if (relatedTypes.length > 0) {
316
+ schemaString += ` & {\n ${relatedTypes}};\n\n`;
317
+ } else {
318
+ schemaString += `;\n\n`;
319
+ }
320
+ schemaString += `export const ${pascalName}Schema: z.ZodType<${pascalName}Base> = ${pascalName}SchemaBase`;
321
+ if (relatedTypes.length > 0) {
322
+ schemaString += `.extend({\n ${relatedTypesLazy}});\n\n`;
323
+ } else {
324
+ schemaString += `;\n`;
325
+ }
326
+ schemaString += `export type ${pascalName} = z.infer<typeof ${pascalName}Schema>;\n\n`;
327
+
328
+ return schemaString;
329
+ };
330
+
331
+ typeToZod = (attribute: Attribute) => {
332
+ let baseSchemaCode = "";
333
+ const finalAttribute: Attribute = (
334
+ attribute.type === "string" &&
335
+ attribute.format &&
336
+ attribute.format === "enum" &&
337
+ attribute.type === "string"
338
+ ? { ...attribute, type: attribute.format }
339
+ : attribute
340
+ ) as Attribute;
341
+ switch (finalAttribute.type) {
342
+ case "string":
343
+ baseSchemaCode = "z.string()";
344
+ if (finalAttribute.size) {
345
+ baseSchemaCode += `.max(${finalAttribute.size}, "Maximum length of ${finalAttribute.size} characters exceeded")`;
346
+ }
347
+ if (finalAttribute.xdefault !== undefined) {
348
+ baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
349
+ }
350
+ if (!attribute.required && !attribute.array) {
351
+ baseSchemaCode += ".nullish()";
352
+ }
353
+ break;
354
+ case "integer":
355
+ baseSchemaCode = "z.number().int()";
356
+ if (finalAttribute.min !== undefined) {
357
+ if (BigInt(finalAttribute.min) === BigInt(-9223372036854776000)) {
358
+ delete finalAttribute.min;
359
+ } else {
360
+ baseSchemaCode += `.min(${finalAttribute.min}, "Minimum value of ${finalAttribute.min} not met")`;
361
+ }
362
+ }
363
+ if (finalAttribute.max !== undefined) {
364
+ if (BigInt(finalAttribute.max) === BigInt(9223372036854776000)) {
365
+ delete finalAttribute.max;
366
+ } else {
367
+ baseSchemaCode += `.max(${finalAttribute.max}, "Maximum value of ${finalAttribute.max} exceeded")`;
368
+ }
369
+ }
370
+ if (finalAttribute.xdefault !== undefined) {
371
+ baseSchemaCode += `.default(${finalAttribute.xdefault})`;
372
+ }
373
+ if (!finalAttribute.required && !finalAttribute.array) {
374
+ baseSchemaCode += ".nullish()";
375
+ }
376
+ break;
377
+ case "float":
378
+ baseSchemaCode = "z.number()";
379
+ if (finalAttribute.min !== undefined) {
380
+ baseSchemaCode += `.min(${finalAttribute.min}, "Minimum value of ${finalAttribute.min} not met")`;
381
+ }
382
+ if (finalAttribute.max !== undefined) {
383
+ baseSchemaCode += `.max(${finalAttribute.max}, "Maximum value of ${finalAttribute.max} exceeded")`;
384
+ }
385
+ if (finalAttribute.xdefault !== undefined) {
386
+ baseSchemaCode += `.default(${finalAttribute.xdefault})`;
387
+ }
388
+ if (!finalAttribute.required && !finalAttribute.array) {
389
+ baseSchemaCode += ".nullish()";
390
+ }
391
+ break;
392
+ case "boolean":
393
+ baseSchemaCode = "z.boolean()";
394
+ if (finalAttribute.xdefault !== undefined) {
395
+ baseSchemaCode += `.default(${finalAttribute.xdefault})`;
396
+ }
397
+ if (!finalAttribute.required && !finalAttribute.array) {
398
+ baseSchemaCode += ".nullish()";
399
+ }
400
+ break;
401
+ case "datetime":
402
+ baseSchemaCode = "z.date()";
403
+ if (finalAttribute.xdefault !== undefined) {
404
+ baseSchemaCode += `.default(new Date("${finalAttribute.xdefault}"))`;
405
+ }
406
+ if (!finalAttribute.required && !finalAttribute.array) {
407
+ baseSchemaCode += ".nullish()";
408
+ }
409
+ break;
410
+ case "email":
411
+ baseSchemaCode = "z.string().email()";
412
+ if (finalAttribute.xdefault !== undefined) {
413
+ baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
414
+ }
415
+ if (!finalAttribute.required && !finalAttribute.array) {
416
+ baseSchemaCode += ".nullish()";
417
+ }
418
+ break;
419
+ case "ip":
420
+ baseSchemaCode = "z.string()"; // Add custom validation as needed
421
+ if (finalAttribute.xdefault !== undefined) {
422
+ baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
423
+ }
424
+ if (!finalAttribute.required && !finalAttribute.array) {
425
+ baseSchemaCode += ".nullish()";
426
+ }
427
+ break;
428
+ case "url":
429
+ baseSchemaCode = "z.string().url()";
430
+ if (finalAttribute.xdefault !== undefined) {
431
+ baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
432
+ }
433
+ if (!finalAttribute.required && !finalAttribute.array) {
434
+ baseSchemaCode += ".nullish()";
435
+ }
436
+ break;
437
+ case "enum":
438
+ baseSchemaCode = `z.enum([${finalAttribute.elements
439
+ .map((element) => `"${element}"`)
440
+ .join(", ")}])`;
441
+ if (finalAttribute.xdefault !== undefined) {
442
+ baseSchemaCode += `.default("${finalAttribute.xdefault}")`;
443
+ }
444
+ if (!attribute.required && !attribute.array) {
445
+ baseSchemaCode += ".nullish()";
446
+ }
447
+ break;
448
+ case "relationship":
449
+ break;
450
+ default:
451
+ baseSchemaCode = "z.any()";
452
+ }
453
+
454
+ // Handle arrays
455
+ if (attribute.array) {
456
+ baseSchemaCode = `z.array(${baseSchemaCode})`;
457
+ }
458
+ if (attribute.array && !attribute.required) {
459
+ baseSchemaCode += ".nullish()";
460
+ }
461
+ if (attribute.description) {
462
+ if (typeof attribute.description === "string") {
463
+ baseSchemaCode += `.openapi({ description: "${attribute.description}" })`;
464
+ } else {
465
+ baseSchemaCode += `.openapi(${Object.entries(attribute.description)
466
+ .map(([key, value]) => `"${key}": ${value}`)
467
+ .join(", ")})`;
468
+ }
469
+ }
470
+
471
+ return baseSchemaCode;
472
+ };
473
+ }