appwrite-utils-cli 0.0.285 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +122 -96
  2. package/dist/collections/attributes.d.ts +4 -0
  3. package/dist/collections/attributes.js +224 -0
  4. package/dist/collections/indexes.d.ts +4 -0
  5. package/dist/collections/indexes.js +27 -0
  6. package/dist/collections/methods.d.ts +16 -0
  7. package/dist/collections/methods.js +216 -0
  8. package/dist/databases/methods.d.ts +6 -0
  9. package/dist/databases/methods.js +33 -0
  10. package/dist/interactiveCLI.d.ts +19 -0
  11. package/dist/interactiveCLI.js +555 -0
  12. package/dist/main.js +227 -62
  13. package/dist/migrations/afterImportActions.js +37 -40
  14. package/dist/migrations/appwriteToX.d.ts +26 -25
  15. package/dist/migrations/appwriteToX.js +42 -6
  16. package/dist/migrations/attributes.js +21 -20
  17. package/dist/migrations/backup.d.ts +93 -87
  18. package/dist/migrations/collections.d.ts +6 -0
  19. package/dist/migrations/collections.js +149 -20
  20. package/dist/migrations/converters.d.ts +2 -18
  21. package/dist/migrations/converters.js +13 -2
  22. package/dist/migrations/dataLoader.d.ts +276 -161
  23. package/dist/migrations/dataLoader.js +535 -292
  24. package/dist/migrations/databases.js +8 -2
  25. package/dist/migrations/helper.d.ts +3 -0
  26. package/dist/migrations/helper.js +21 -0
  27. package/dist/migrations/importController.d.ts +5 -2
  28. package/dist/migrations/importController.js +125 -88
  29. package/dist/migrations/importDataActions.d.ts +9 -1
  30. package/dist/migrations/importDataActions.js +15 -3
  31. package/dist/migrations/indexes.js +3 -2
  32. package/dist/migrations/logging.js +20 -8
  33. package/dist/migrations/migrationHelper.d.ts +9 -4
  34. package/dist/migrations/migrationHelper.js +6 -5
  35. package/dist/migrations/openapi.d.ts +1 -1
  36. package/dist/migrations/openapi.js +33 -18
  37. package/dist/migrations/queue.js +3 -2
  38. package/dist/migrations/relationships.d.ts +2 -2
  39. package/dist/migrations/schemaStrings.js +53 -41
  40. package/dist/migrations/setupDatabase.d.ts +2 -4
  41. package/dist/migrations/setupDatabase.js +24 -105
  42. package/dist/migrations/storage.d.ts +3 -1
  43. package/dist/migrations/storage.js +110 -16
  44. package/dist/migrations/transfer.d.ts +30 -0
  45. package/dist/migrations/transfer.js +337 -0
  46. package/dist/migrations/users.d.ts +2 -1
  47. package/dist/migrations/users.js +78 -43
  48. package/dist/schemas/authUser.d.ts +2 -2
  49. package/dist/storage/methods.d.ts +15 -0
  50. package/dist/storage/methods.js +207 -0
  51. package/dist/storage/schemas.d.ts +687 -0
  52. package/dist/storage/schemas.js +175 -0
  53. package/dist/utils/getClientFromConfig.d.ts +4 -0
  54. package/dist/utils/getClientFromConfig.js +16 -0
  55. package/dist/utils/helperFunctions.d.ts +11 -1
  56. package/dist/utils/helperFunctions.js +38 -0
  57. package/dist/utils/retryFailedPromises.d.ts +2 -0
  58. package/dist/utils/retryFailedPromises.js +21 -0
  59. package/dist/utils/schemaStrings.d.ts +13 -0
  60. package/dist/utils/schemaStrings.js +403 -0
  61. package/dist/utils/setupFiles.js +110 -61
  62. package/dist/utilsController.d.ts +40 -22
  63. package/dist/utilsController.js +164 -84
  64. package/package.json +13 -15
  65. package/src/collections/attributes.ts +483 -0
  66. package/src/collections/indexes.ts +53 -0
  67. package/src/collections/methods.ts +331 -0
  68. package/src/databases/methods.ts +47 -0
  69. package/src/init.ts +64 -64
  70. package/src/interactiveCLI.ts +767 -0
  71. package/src/main.ts +292 -83
  72. package/src/migrations/afterImportActions.ts +553 -490
  73. package/src/migrations/appwriteToX.ts +237 -174
  74. package/src/migrations/attributes.ts +483 -422
  75. package/src/migrations/backup.ts +205 -205
  76. package/src/migrations/collections.ts +545 -300
  77. package/src/migrations/converters.ts +161 -150
  78. package/src/migrations/dataLoader.ts +1615 -1304
  79. package/src/migrations/databases.ts +44 -25
  80. package/src/migrations/dbHelpers.ts +92 -92
  81. package/src/migrations/helper.ts +40 -0
  82. package/src/migrations/importController.ts +448 -384
  83. package/src/migrations/importDataActions.ts +315 -307
  84. package/src/migrations/indexes.ts +40 -37
  85. package/src/migrations/logging.ts +29 -16
  86. package/src/migrations/migrationHelper.ts +207 -201
  87. package/src/migrations/openapi.ts +83 -70
  88. package/src/migrations/queue.ts +118 -119
  89. package/src/migrations/relationships.ts +324 -324
  90. package/src/migrations/schemaStrings.ts +472 -460
  91. package/src/migrations/setupDatabase.ts +118 -219
  92. package/src/migrations/storage.ts +538 -358
  93. package/src/migrations/transfer.ts +608 -0
  94. package/src/migrations/users.ts +362 -285
  95. package/src/migrations/validationRules.ts +63 -63
  96. package/src/schemas/authUser.ts +23 -23
  97. package/src/setup.ts +8 -8
  98. package/src/storage/methods.ts +371 -0
  99. package/src/storage/schemas.ts +205 -0
  100. package/src/types.ts +9 -9
  101. package/src/utils/getClientFromConfig.ts +17 -0
  102. package/src/utils/helperFunctions.ts +181 -127
  103. package/src/utils/index.ts +2 -2
  104. package/src/utils/loadConfigs.ts +59 -59
  105. package/src/utils/retryFailedPromises.ts +27 -0
  106. package/src/utils/schemaStrings.ts +473 -0
  107. package/src/utils/setupFiles.ts +228 -182
  108. package/src/utilsController.ts +325 -194
  109. package/tsconfig.json +37 -37
@@ -1,490 +1,553 @@
1
- import {
2
- Databases,
3
- Storage,
4
- InputFile,
5
- Query,
6
- ID,
7
- type Models,
8
- Client,
9
- } from "node-appwrite";
10
- import path from "path";
11
- import fs from "fs";
12
- import os from "os";
13
- import { logger } from "./logging.js";
14
- import { type AfterImportActions, type AppwriteConfig } from "appwrite-utils";
15
-
16
- export const getDatabaseFromConfig = (config: AppwriteConfig) => {
17
- if (!config.appwriteClient) {
18
- config.appwriteClient = new Client()
19
- .setEndpoint(config.appwriteEndpoint)
20
- .setProject(config.appwriteProject)
21
- .setKey(config.appwriteKey);
22
- }
23
- return new Databases(config.appwriteClient!);
24
- };
25
-
26
- export const getStorageFromConfig = (config: AppwriteConfig) => {
27
- if (!config.appwriteClient) {
28
- config.appwriteClient = new Client()
29
- .setEndpoint(config.appwriteEndpoint)
30
- .setProject(config.appwriteProject)
31
- .setKey(config.appwriteKey);
32
- }
33
- return new Storage(config.appwriteClient!);
34
- };
35
-
36
- export const afterImportActions = {
37
- updateCreatedDocument: async (
38
- config: AppwriteConfig,
39
- dbId: string,
40
- collId: string,
41
- docId: string,
42
- data: any
43
- ) => {
44
- try {
45
- const db = getDatabaseFromConfig(config);
46
- await db.updateDocument(dbId, collId, docId, data);
47
- } catch (error) {
48
- console.error("Error updating document: ", error);
49
- }
50
- },
51
- checkAndUpdateFieldInDocument: async (
52
- config: AppwriteConfig,
53
- dbId: string,
54
- collId: string,
55
- docId: string,
56
- fieldName: string,
57
- oldFieldValue: any,
58
- newFieldValue: any
59
- ) => {
60
- try {
61
- const db = getDatabaseFromConfig(config);
62
- const doc = await db.getDocument(dbId, collId, docId);
63
- if (doc[fieldName as keyof typeof doc] == oldFieldValue) {
64
- await db.updateDocument(dbId, collId, docId, {
65
- [fieldName]: newFieldValue,
66
- });
67
- }
68
- } catch (error) {
69
- console.error("Error updating document: ", error);
70
- }
71
- },
72
- setFieldFromOtherCollectionDocument: async (
73
- config: AppwriteConfig,
74
- dbId: string,
75
- collIdOrName: string,
76
- docId: string,
77
- fieldName: string,
78
- otherCollIdOrName: string,
79
- otherDocId: string,
80
- otherFieldName: string
81
- ) => {
82
- const db = getDatabaseFromConfig(config);
83
-
84
- // Helper function to find a collection ID by name or return the ID if given
85
- const findCollectionId = async (collectionIdentifier: string) => {
86
- const collectionsPulled = await db.listCollections(dbId, [
87
- Query.limit(25),
88
- Query.equal("name", collectionIdentifier),
89
- ]);
90
- if (collectionsPulled.total > 0) {
91
- return collectionsPulled.collections[0].$id;
92
- } else {
93
- // Assuming the passed identifier might directly be an ID if not found by name
94
- return collectionIdentifier;
95
- }
96
- };
97
-
98
- try {
99
- // Resolve the IDs for both the target and other collections
100
- const targetCollectionId = await findCollectionId(collIdOrName);
101
- const otherCollectionId = await findCollectionId(otherCollIdOrName);
102
-
103
- // Retrieve the "other" document
104
- const otherDoc = await db.getDocument(
105
- dbId,
106
- otherCollectionId,
107
- otherDocId
108
- );
109
- const valueToSet = otherDoc[otherFieldName as keyof typeof otherDoc];
110
-
111
- if (valueToSet) {
112
- // Update the target document
113
- await db.updateDocument(dbId, targetCollectionId, docId, {
114
- [fieldName]: valueToSet,
115
- });
116
- }
117
-
118
- console.log(
119
- `Field ${fieldName} updated successfully in document ${docId}.`
120
- );
121
- } catch (error) {
122
- console.error(
123
- "Error setting field from other collection document: ",
124
- error
125
- );
126
- }
127
- },
128
- /**
129
- * Updates a field in a document by setting it with document IDs from another collection
130
- * based on a matching field value.
131
- */
132
- setFieldFromOtherCollectionDocuments: async (
133
- config: AppwriteConfig,
134
- dbId: string,
135
- collIdOrName: string,
136
- docId: string,
137
- fieldName: string,
138
- otherCollIdOrName: string,
139
- matchingFieldName: string,
140
- matchingFieldValue: any,
141
- fieldToSet?: string
142
- ): Promise<void> => {
143
- const db = getDatabaseFromConfig(config);
144
-
145
- // Helper function to find a collection ID by name or return the ID if given
146
- const findCollectionId = async (collectionIdentifier: string) => {
147
- const collections = await db.listCollections(dbId, [
148
- Query.equal("name", collectionIdentifier),
149
- Query.limit(1),
150
- ]);
151
- return collections.total > 0
152
- ? collections.collections[0].$id
153
- : collectionIdentifier;
154
- };
155
-
156
- // Function to check if the target field is an array
157
- const isTargetFieldArray = async (
158
- collectionId: string,
159
- fieldName: string
160
- ) => {
161
- const collection = await db.getCollection(dbId, collectionId);
162
- const attribute = collection.attributes.find(
163
- (attr: any) => attr.key === fieldName
164
- );
165
- // @ts-ignore
166
- return attribute?.array === true;
167
- };
168
-
169
- try {
170
- const targetCollectionId = await findCollectionId(collIdOrName);
171
- const otherCollectionId = await findCollectionId(otherCollIdOrName);
172
- const targetFieldIsArray = await isTargetFieldArray(
173
- targetCollectionId,
174
- fieldName
175
- );
176
-
177
- // Function to recursively fetch all matching documents from the other collection
178
- const fetchAllMatchingDocuments = async (
179
- cursor?: string
180
- ): Promise<Models.Document[]> => {
181
- const docLimit = 100;
182
- const queries = targetFieldIsArray
183
- ? // @ts-ignore
184
- [Query.contains(matchingFieldName, [matchingFieldValue])]
185
- : [Query.equal(matchingFieldName, matchingFieldValue)];
186
- if (cursor) {
187
- queries.push(Query.cursorAfter(cursor));
188
- }
189
- queries.push(Query.limit(docLimit));
190
- const response = await db.listDocuments(
191
- dbId,
192
- otherCollectionId,
193
- queries
194
- );
195
- const documents = response.documents;
196
- if (documents.length === 0 || documents.length < docLimit) {
197
- return documents;
198
- }
199
- const nextCursor = documents[documents.length - 1].$id;
200
- const nextBatch = await fetchAllMatchingDocuments(nextCursor);
201
- return documents.concat(nextBatch);
202
- };
203
-
204
- const matchingDocuments = await fetchAllMatchingDocuments();
205
- const documentIds = matchingDocuments.map((doc) => doc.$id);
206
-
207
- if (documentIds.length > 0) {
208
- const updatePayload = targetFieldIsArray
209
- ? { [fieldName]: documentIds }
210
- : { [fieldName]: documentIds[0] };
211
- await db.updateDocument(dbId, targetCollectionId, docId, updatePayload);
212
-
213
- console.log(
214
- `Field ${fieldName} updated successfully in document ${docId} with ${documentIds.length} document IDs.`
215
- );
216
- }
217
- } catch (error) {
218
- console.error(
219
- "Error setting field from other collection documents: ",
220
- error
221
- );
222
- }
223
- },
224
- setTargetFieldFromOtherCollectionDocumentsByMatchingField: async (
225
- config: AppwriteConfig,
226
- dbId: string,
227
- collIdOrName: string,
228
- docId: string,
229
- fieldName: string,
230
- otherCollIdOrName: string,
231
- matchingFieldName: string,
232
- matchingFieldValue: any,
233
- targetField: string
234
- ): Promise<void> => {
235
- const db = getDatabaseFromConfig(config);
236
-
237
- const findCollectionId = async (collectionIdentifier: string) => {
238
- const collections = await db.listCollections(dbId, [
239
- Query.equal("name", collectionIdentifier),
240
- Query.limit(1),
241
- ]);
242
- return collections.total > 0
243
- ? collections.collections[0].$id
244
- : collectionIdentifier;
245
- };
246
-
247
- const isTargetFieldArray = async (
248
- collectionId: string,
249
- fieldName: string
250
- ) => {
251
- const collection = await db.getCollection(dbId, collectionId);
252
- const attribute = collection.attributes.find(
253
- (attr: any) => attr.key === fieldName
254
- );
255
- // @ts-ignore
256
- return attribute?.array === true;
257
- };
258
-
259
- try {
260
- const targetCollectionId = await findCollectionId(collIdOrName);
261
- const otherCollectionId = await findCollectionId(otherCollIdOrName);
262
- const targetFieldIsArray = await isTargetFieldArray(
263
- targetCollectionId,
264
- fieldName
265
- );
266
-
267
- const fetchAllMatchingDocuments = async (
268
- cursor?: string
269
- ): Promise<Models.Document[]> => {
270
- const docLimit = 100;
271
- const queries = [
272
- Query.equal(matchingFieldName, matchingFieldValue),
273
- Query.limit(docLimit),
274
- ];
275
- if (cursor) {
276
- queries.push(Query.cursorAfter(cursor));
277
- }
278
- const response = await db.listDocuments(
279
- dbId,
280
- otherCollectionId,
281
- queries
282
- );
283
- const documents = response.documents;
284
- if (documents.length === 0 || documents.length < docLimit) {
285
- return documents;
286
- }
287
- const nextCursor = documents[documents.length - 1].$id;
288
- const nextBatch = await fetchAllMatchingDocuments(nextCursor);
289
- return documents.concat(nextBatch);
290
- };
291
-
292
- const matchingDocuments = await fetchAllMatchingDocuments();
293
- // Map the values from the targetField instead of the document IDs
294
- const targetFieldValues = matchingDocuments.map(
295
- (doc) => doc[targetField as keyof typeof doc]
296
- );
297
-
298
- if (targetFieldValues.length > 0) {
299
- const updatePayload = targetFieldIsArray
300
- ? { [fieldName]: targetFieldValues }
301
- : { [fieldName]: targetFieldValues[0] };
302
- await db.updateDocument(dbId, targetCollectionId, docId, updatePayload);
303
-
304
- console.log(
305
- `Field ${fieldName} updated successfully in document ${docId} with values from field ${targetField}.`
306
- );
307
- }
308
- } catch (error) {
309
- console.error(
310
- "Error setting field from other collection documents: ",
311
- error
312
- );
313
- }
314
- },
315
- createOrGetBucket: async (
316
- config: AppwriteConfig,
317
- bucketName: string,
318
- bucketId?: string,
319
- permissions?: string[],
320
- fileSecurity?: boolean,
321
- enabled?: boolean,
322
- maxFileSize?: number,
323
- allowedExtensions?: string[],
324
- compression?: string,
325
- encryption?: boolean,
326
- antivirus?: boolean
327
- ) => {
328
- try {
329
- const storage = getStorageFromConfig(config);
330
- const bucket = await storage.listBuckets([
331
- Query.equal("name", bucketName),
332
- ]);
333
- if (bucket.buckets.length > 0) {
334
- return bucket.buckets[0];
335
- } else if (bucketId) {
336
- try {
337
- return await storage.getBucket(bucketId);
338
- } catch (error) {
339
- return await storage.createBucket(
340
- bucketId,
341
- bucketName,
342
- permissions,
343
- fileSecurity,
344
- enabled,
345
- maxFileSize,
346
- allowedExtensions,
347
- compression,
348
- encryption,
349
- antivirus
350
- );
351
- }
352
- } else {
353
- return await storage.createBucket(
354
- bucketId || ID.unique(),
355
- bucketName,
356
- permissions,
357
- fileSecurity,
358
- enabled,
359
- maxFileSize,
360
- allowedExtensions,
361
- compression,
362
- encryption,
363
- antivirus
364
- );
365
- }
366
- } catch (error) {
367
- console.error("Error creating or getting bucket: ", error);
368
- }
369
- },
370
- createFileAndUpdateField: async (
371
- config: AppwriteConfig,
372
- dbId: string,
373
- collId: string,
374
- docId: string,
375
- fieldName: string,
376
- bucketId: string,
377
- filePath: string,
378
- fileName: string
379
- ) => {
380
- try {
381
- const db = getDatabaseFromConfig(config);
382
- const storage = getStorageFromConfig(config);
383
- const collection = await db.getCollection(dbId, collId);
384
- const attributes = collection.attributes as any[];
385
- const attribute = attributes.find((a) => a.key === fieldName);
386
- // console.log(
387
- // `Processing field ${fieldName} in collection ${collId} for document ${docId} in database ${dbId} in bucket ${bucketId} with path ${filePath} and name ${fileName}...`
388
- // );
389
- let isArray = false;
390
- if (!attribute) {
391
- console.log(
392
- `Field ${fieldName} not found in collection ${collId}, weird, skipping...`
393
- );
394
- return;
395
- } else if (attribute.array === true) {
396
- isArray = true;
397
- }
398
-
399
- // Define a helper function to check if a value is a URL
400
- const isUrl = (value: any) =>
401
- typeof value === "string" &&
402
- (value.startsWith("http://") || value.startsWith("https://"));
403
-
404
- const doc = await db.getDocument(dbId, collId, docId);
405
- const existingFieldValue = doc[fieldName as keyof typeof doc];
406
-
407
- // Handle the case where the field is an array
408
- let updateData: string | string[] = isArray ? [] : "";
409
- if (isArray && Array.isArray(existingFieldValue)) {
410
- updateData = existingFieldValue.filter((val) => !isUrl(val)); // Remove URLs from the array
411
- }
412
-
413
- // Process file upload and update logic
414
- if (isUrl(filePath)) {
415
- // Create a temporary directory
416
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "appwrite_tmp"));
417
- const tempFilePath = path.join(tempDir, fileName);
418
-
419
- // Download the file using fetch
420
- const response = await fetch(filePath);
421
- if (!response.ok)
422
- console.error(
423
- `Failed to fetch ${filePath}: ${response.statusText} for document ${docId} with field ${fieldName}`
424
- );
425
-
426
- // Use arrayBuffer if buffer is not available
427
- const arrayBuffer = await response.arrayBuffer();
428
- const buffer = Buffer.from(arrayBuffer);
429
- fs.writeFileSync(tempFilePath, buffer);
430
-
431
- // Create InputFile from the downloaded file
432
- const inputFile = InputFile.fromPath(tempFilePath, fileName);
433
-
434
- // Use the full file name (with extension) for creating the file
435
- const file = await storage.createFile(bucketId, ID.unique(), inputFile);
436
-
437
- console.log("Created file from URL: ", file.$id);
438
-
439
- // After uploading, adjust the updateData based on whether the field is an array or not
440
- if (isArray) {
441
- updateData = [...updateData, file.$id]; // Append the new file ID
442
- } else {
443
- updateData = file.$id; // Set the new file ID
444
- }
445
- await db.updateDocument(dbId, collId, doc.$id, {
446
- [fieldName]: updateData,
447
- });
448
- // console.log(
449
- // "Updating document with file: ",
450
- // doc.$id,
451
- // `${fieldName}: `,
452
- // updateData
453
- // );
454
-
455
- // If the file was downloaded, delete it after uploading
456
- fs.unlinkSync(tempFilePath);
457
- } else {
458
- const files = fs.readdirSync(filePath);
459
- const fileFullName = files.find((file) => file.includes(fileName));
460
- if (!fileFullName) {
461
- console.error(
462
- `File starting with '${fileName}' not found in '${filePath}'`
463
- );
464
- return;
465
- }
466
- const pathToFile = path.join(filePath, fileFullName);
467
- const inputFile = InputFile.fromPath(pathToFile, fileName);
468
- const file = await storage.createFile(bucketId, ID.unique(), inputFile);
469
-
470
- if (isArray) {
471
- updateData = [...updateData, file.$id]; // Append the new file ID
472
- } else {
473
- updateData = file.$id; // Set the new file ID
474
- }
475
- await db.updateDocument(dbId, collId, doc.$id, {
476
- [fieldName]: updateData,
477
- });
478
- console.log("Created file from path: ", file.$id);
479
- }
480
- } catch (error) {
481
- logger.error(
482
- `Error creating file and updating field, params were:\ndbId: ${dbId}, collId: ${collId}, docId: ${docId}, fieldName: ${fieldName}, filePath: ${filePath}, fileName: ${fileName}\n\nError: ${error}`
483
- );
484
- console.error("Error creating file and updating field: ", error);
485
- console.log(
486
- `Params were: dbId: ${dbId}, collId: ${collId}, docId: ${docId}, fieldName: ${fieldName}, filePath: ${filePath}, fileName: ${fileName}`
487
- );
488
- }
489
- },
490
- };
1
+ import {
2
+ Databases,
3
+ Storage,
4
+ Query,
5
+ ID,
6
+ type Models,
7
+ Client,
8
+ Compression,
9
+ } from "node-appwrite";
10
+ import { InputFile } from "node-appwrite/file";
11
+ import path from "path";
12
+ import fs from "fs";
13
+ import os from "os";
14
+ import { logger } from "./logging.js";
15
+ import {
16
+ tryAwaitWithRetry,
17
+ type AfterImportActions,
18
+ type AppwriteConfig,
19
+ } from "appwrite-utils";
20
+
21
+ export const getDatabaseFromConfig = (config: AppwriteConfig) => {
22
+ if (!config.appwriteClient) {
23
+ config.appwriteClient = new Client()
24
+ .setEndpoint(config.appwriteEndpoint)
25
+ .setProject(config.appwriteProject)
26
+ .setKey(config.appwriteKey);
27
+ }
28
+ return new Databases(config.appwriteClient!);
29
+ };
30
+
31
+ export const getStorageFromConfig = (config: AppwriteConfig) => {
32
+ if (!config.appwriteClient) {
33
+ config.appwriteClient = new Client()
34
+ .setEndpoint(config.appwriteEndpoint)
35
+ .setProject(config.appwriteProject)
36
+ .setKey(config.appwriteKey);
37
+ }
38
+ return new Storage(config.appwriteClient!);
39
+ };
40
+
41
+ export const afterImportActions = {
42
+ updateCreatedDocument: async (
43
+ config: AppwriteConfig,
44
+ dbId: string,
45
+ collId: string,
46
+ docId: string,
47
+ data: any
48
+ ) => {
49
+ try {
50
+ const db = getDatabaseFromConfig(config);
51
+ await tryAwaitWithRetry(
52
+ async () => await db.updateDocument(dbId, collId, docId, data)
53
+ );
54
+ } catch (error) {
55
+ console.error("Error updating document: ", error);
56
+ }
57
+ },
58
+ checkAndUpdateFieldInDocument: async (
59
+ config: AppwriteConfig,
60
+ dbId: string,
61
+ collId: string,
62
+ docId: string,
63
+ fieldName: string,
64
+ oldFieldValue: any,
65
+ newFieldValue: any
66
+ ) => {
67
+ try {
68
+ const db = getDatabaseFromConfig(config);
69
+ const doc = await tryAwaitWithRetry(
70
+ async () => await db.getDocument(dbId, collId, docId)
71
+ );
72
+ if (doc[fieldName as keyof typeof doc] == oldFieldValue) {
73
+ await tryAwaitWithRetry(
74
+ async () =>
75
+ await db.updateDocument(dbId, collId, docId, {
76
+ [fieldName]: newFieldValue,
77
+ })
78
+ );
79
+ }
80
+ } catch (error) {
81
+ console.error("Error updating document: ", error);
82
+ }
83
+ },
84
+ setFieldFromOtherCollectionDocument: async (
85
+ config: AppwriteConfig,
86
+ dbId: string,
87
+ collIdOrName: string,
88
+ docId: string,
89
+ fieldName: string,
90
+ otherCollIdOrName: string,
91
+ otherDocId: string,
92
+ otherFieldName: string
93
+ ) => {
94
+ const db = getDatabaseFromConfig(config);
95
+
96
+ // Helper function to find a collection ID by name or return the ID if given
97
+ const findCollectionId = async (collectionIdentifier: string) => {
98
+ const collectionsPulled = await tryAwaitWithRetry(
99
+ async () =>
100
+ await db.listCollections(dbId, [
101
+ Query.limit(25),
102
+ Query.equal("name", collectionIdentifier),
103
+ ])
104
+ );
105
+ if (collectionsPulled.total > 0) {
106
+ return collectionsPulled.collections[0].$id;
107
+ } else {
108
+ // Assuming the passed identifier might directly be an ID if not found by name
109
+ return collectionIdentifier;
110
+ }
111
+ };
112
+
113
+ try {
114
+ // Resolve the IDs for both the target and other collections
115
+ const targetCollectionId = await findCollectionId(collIdOrName);
116
+ const otherCollectionId = await findCollectionId(otherCollIdOrName);
117
+
118
+ // Retrieve the "other" document
119
+ const otherDoc = await db.getDocument(
120
+ dbId,
121
+ otherCollectionId,
122
+ otherDocId
123
+ );
124
+ const valueToSet = otherDoc[otherFieldName as keyof typeof otherDoc];
125
+
126
+ if (valueToSet) {
127
+ // Update the target document
128
+ await tryAwaitWithRetry(
129
+ async () =>
130
+ await db.updateDocument(dbId, targetCollectionId, docId, {
131
+ [fieldName]: valueToSet,
132
+ })
133
+ );
134
+ }
135
+
136
+ console.log(
137
+ `Field ${fieldName} updated successfully in document ${docId}.`
138
+ );
139
+ } catch (error) {
140
+ console.error(
141
+ "Error setting field from other collection document: ",
142
+ error
143
+ );
144
+ }
145
+ },
146
+ /**
147
+ * Updates a field in a document by setting it with document IDs from another collection
148
+ * based on a matching field value.
149
+ */
150
+ setFieldFromOtherCollectionDocuments: async (
151
+ config: AppwriteConfig,
152
+ dbId: string,
153
+ collIdOrName: string,
154
+ docId: string,
155
+ fieldName: string,
156
+ otherCollIdOrName: string,
157
+ matchingFieldName: string,
158
+ matchingFieldValue: any,
159
+ fieldToSet?: string
160
+ ): Promise<void> => {
161
+ const db = getDatabaseFromConfig(config);
162
+
163
+ // Helper function to find a collection ID by name or return the ID if given
164
+ const findCollectionId = async (collectionIdentifier: string) => {
165
+ const collections = await tryAwaitWithRetry(
166
+ async () =>
167
+ await db.listCollections(dbId, [
168
+ Query.equal("name", collectionIdentifier),
169
+ Query.limit(1),
170
+ ])
171
+ );
172
+ return collections.total > 0
173
+ ? collections.collections[0].$id
174
+ : collectionIdentifier;
175
+ };
176
+
177
+ // Function to check if the target field is an array
178
+ const isTargetFieldArray = async (
179
+ collectionId: string,
180
+ fieldName: string
181
+ ) => {
182
+ const collection = await tryAwaitWithRetry(
183
+ async () => await db.getCollection(dbId, collectionId)
184
+ );
185
+ const attribute = collection.attributes.find(
186
+ (attr: any) => attr.key === fieldName
187
+ );
188
+ // @ts-ignore
189
+ return attribute?.array === true;
190
+ };
191
+
192
+ try {
193
+ const targetCollectionId = await findCollectionId(collIdOrName);
194
+ const otherCollectionId = await findCollectionId(otherCollIdOrName);
195
+ const targetFieldIsArray = await isTargetFieldArray(
196
+ targetCollectionId,
197
+ fieldName
198
+ );
199
+
200
+ // Function to recursively fetch all matching documents from the other collection
201
+ const fetchAllMatchingDocuments = async (
202
+ cursor?: string
203
+ ): Promise<Models.Document[]> => {
204
+ const docLimit = 100;
205
+ const queries = targetFieldIsArray
206
+ ? // @ts-ignore
207
+ [Query.contains(matchingFieldName, [matchingFieldValue])]
208
+ : [Query.equal(matchingFieldName, matchingFieldValue)];
209
+ if (cursor) {
210
+ queries.push(Query.cursorAfter(cursor));
211
+ }
212
+ queries.push(Query.limit(docLimit));
213
+ const response = await tryAwaitWithRetry(
214
+ async () => await db.listDocuments(dbId, otherCollectionId, queries)
215
+ );
216
+ const documents = response.documents;
217
+ if (documents.length === 0 || documents.length < docLimit) {
218
+ return documents;
219
+ }
220
+ const nextCursor = documents[documents.length - 1].$id;
221
+ const nextBatch = await fetchAllMatchingDocuments(nextCursor);
222
+ return documents.concat(nextBatch);
223
+ };
224
+
225
+ const matchingDocuments = await fetchAllMatchingDocuments();
226
+ const documentIds = matchingDocuments.map((doc) => doc.$id);
227
+
228
+ if (documentIds.length > 0) {
229
+ const updatePayload = targetFieldIsArray
230
+ ? { [fieldName]: documentIds }
231
+ : { [fieldName]: documentIds[0] };
232
+ await tryAwaitWithRetry(
233
+ async () =>
234
+ await db.updateDocument(
235
+ dbId,
236
+ targetCollectionId,
237
+ docId,
238
+ updatePayload
239
+ )
240
+ );
241
+
242
+ console.log(
243
+ `Field ${fieldName} updated successfully in document ${docId} with ${documentIds.length} document IDs.`
244
+ );
245
+ }
246
+ } catch (error) {
247
+ console.error(
248
+ "Error setting field from other collection documents: ",
249
+ error
250
+ );
251
+ }
252
+ },
253
+ setTargetFieldFromOtherCollectionDocumentsByMatchingField: async (
254
+ config: AppwriteConfig,
255
+ dbId: string,
256
+ collIdOrName: string,
257
+ docId: string,
258
+ fieldName: string,
259
+ otherCollIdOrName: string,
260
+ matchingFieldName: string,
261
+ matchingFieldValue: any,
262
+ targetField: string
263
+ ): Promise<void> => {
264
+ const db = getDatabaseFromConfig(config);
265
+
266
+ const findCollectionId = async (collectionIdentifier: string) => {
267
+ const collections = await tryAwaitWithRetry(
268
+ async () =>
269
+ await db.listCollections(dbId, [
270
+ Query.equal("name", collectionIdentifier),
271
+ Query.limit(1),
272
+ ])
273
+ );
274
+ return collections.total > 0
275
+ ? collections.collections[0].$id
276
+ : collectionIdentifier;
277
+ };
278
+
279
+ const isTargetFieldArray = async (
280
+ collectionId: string,
281
+ fieldName: string
282
+ ) => {
283
+ const collection = await db.getCollection(dbId, collectionId);
284
+ const attribute = collection.attributes.find(
285
+ (attr: any) => attr.key === fieldName
286
+ );
287
+ // @ts-ignore
288
+ return attribute?.array === true;
289
+ };
290
+
291
+ try {
292
+ const targetCollectionId = await findCollectionId(collIdOrName);
293
+ const otherCollectionId = await findCollectionId(otherCollIdOrName);
294
+ const targetFieldIsArray = await isTargetFieldArray(
295
+ targetCollectionId,
296
+ fieldName
297
+ );
298
+
299
+ const fetchAllMatchingDocuments = async (
300
+ cursor?: string
301
+ ): Promise<Models.Document[]> => {
302
+ const docLimit = 100;
303
+ const queries = [
304
+ Query.equal(matchingFieldName, matchingFieldValue),
305
+ Query.limit(docLimit),
306
+ ];
307
+ if (cursor) {
308
+ queries.push(Query.cursorAfter(cursor));
309
+ }
310
+ const response = await tryAwaitWithRetry(
311
+ async () => await db.listDocuments(dbId, otherCollectionId, queries)
312
+ );
313
+ const documents = response.documents;
314
+ if (documents.length === 0 || documents.length < docLimit) {
315
+ return documents;
316
+ }
317
+ const nextCursor = documents[documents.length - 1].$id;
318
+ const nextBatch = await fetchAllMatchingDocuments(nextCursor);
319
+ return documents.concat(nextBatch);
320
+ };
321
+
322
+ const matchingDocuments = await fetchAllMatchingDocuments();
323
+ // Map the values from the targetField instead of the document IDs
324
+ const targetFieldValues = matchingDocuments.map(
325
+ (doc) => doc[targetField as keyof typeof doc]
326
+ );
327
+
328
+ if (targetFieldValues.length > 0) {
329
+ const updatePayload = targetFieldIsArray
330
+ ? { [fieldName]: targetFieldValues }
331
+ : { [fieldName]: targetFieldValues[0] };
332
+ await tryAwaitWithRetry(
333
+ async () =>
334
+ await db.updateDocument(
335
+ dbId,
336
+ targetCollectionId,
337
+ docId,
338
+ updatePayload
339
+ )
340
+ );
341
+
342
+ console.log(
343
+ `Field ${fieldName} updated successfully in document ${docId} with values from field ${targetField}.`
344
+ );
345
+ }
346
+ } catch (error) {
347
+ console.error(
348
+ "Error setting field from other collection documents: ",
349
+ error
350
+ );
351
+ }
352
+ },
353
+ createOrGetBucket: async (
354
+ config: AppwriteConfig,
355
+ bucketName: string,
356
+ bucketId?: string,
357
+ permissions?: string[],
358
+ fileSecurity?: boolean,
359
+ enabled?: boolean,
360
+ maxFileSize?: number,
361
+ allowedExtensions?: string[],
362
+ compression?: string,
363
+ encryption?: boolean,
364
+ antivirus?: boolean
365
+ ) => {
366
+ try {
367
+ const storage = getStorageFromConfig(config);
368
+ const bucket = await tryAwaitWithRetry(
369
+ async () => await storage.listBuckets([Query.equal("name", bucketName)])
370
+ );
371
+ if (bucket.buckets.length > 0) {
372
+ return bucket.buckets[0];
373
+ } else if (bucketId) {
374
+ try {
375
+ return await tryAwaitWithRetry(
376
+ async () => await storage.getBucket(bucketId)
377
+ );
378
+ } catch (error) {
379
+ return await tryAwaitWithRetry(
380
+ async () =>
381
+ await storage.createBucket(
382
+ bucketId,
383
+ bucketName,
384
+ permissions,
385
+ fileSecurity,
386
+ enabled,
387
+ maxFileSize,
388
+ allowedExtensions,
389
+ compression ? Compression.Gzip : undefined,
390
+ encryption,
391
+ antivirus
392
+ )
393
+ );
394
+ }
395
+ } else {
396
+ return await tryAwaitWithRetry(
397
+ async () =>
398
+ await storage.createBucket(
399
+ bucketId || ID.unique(),
400
+ bucketName,
401
+ permissions,
402
+ fileSecurity,
403
+ enabled,
404
+ maxFileSize,
405
+ allowedExtensions,
406
+ compression ? Compression.Gzip : undefined,
407
+ encryption,
408
+ antivirus
409
+ )
410
+ );
411
+ }
412
+ } catch (error) {
413
+ console.error("Error creating or getting bucket: ", error);
414
+ }
415
+ },
416
+ createFileAndUpdateField: async (
417
+ config: AppwriteConfig,
418
+ dbId: string,
419
+ collId: string,
420
+ docId: string,
421
+ fieldName: string,
422
+ bucketId: string,
423
+ filePath: string,
424
+ fileName: string
425
+ ) => {
426
+ try {
427
+ const db = getDatabaseFromConfig(config);
428
+ const storage = getStorageFromConfig(config);
429
+ const collection = await tryAwaitWithRetry(
430
+ async () => await db.getCollection(dbId, collId)
431
+ );
432
+ const attributes = collection.attributes as any[];
433
+ const attribute = attributes.find((a) => a.key === fieldName);
434
+ // console.log(
435
+ // `Processing field ${fieldName} in collection ${collId} for document ${docId} in database ${dbId} in bucket ${bucketId} with path ${filePath} and name ${fileName}...`
436
+ // );
437
+ if (filePath.length === 0 || fileName.length === 0) {
438
+ console.error(
439
+ `File path or name is empty for field ${fieldName} in collection ${collId}, skipping...`
440
+ );
441
+ return;
442
+ }
443
+
444
+ let isArray = false;
445
+ if (!attribute) {
446
+ console.log(
447
+ `Field ${fieldName} not found in collection ${collId}, weird, skipping...`
448
+ );
449
+ return;
450
+ } else if (attribute.array === true) {
451
+ isArray = true;
452
+ }
453
+
454
+ // Define a helper function to check if a value is a URL
455
+ const isUrl = (value: any) =>
456
+ typeof value === "string" &&
457
+ (value.startsWith("http://") || value.startsWith("https://"));
458
+
459
+ const doc = await tryAwaitWithRetry(
460
+ async () => await db.getDocument(dbId, collId, docId)
461
+ );
462
+ const existingFieldValue = doc[fieldName as keyof typeof doc];
463
+
464
+ // Handle the case where the field is an array
465
+ let updateData: string | string[] = isArray ? [] : "";
466
+ if (isArray && Array.isArray(existingFieldValue)) {
467
+ updateData = existingFieldValue.filter((val) => !isUrl(val)); // Remove URLs from the array
468
+ }
469
+
470
+ // Process file upload and update logic
471
+ if (isUrl(filePath)) {
472
+ // Create a temporary directory
473
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "appwrite_tmp"));
474
+ const tempFilePath = path.join(tempDir, fileName);
475
+
476
+ // Download the file using fetch
477
+ const response = await tryAwaitWithRetry(
478
+ async () => await fetch(filePath)
479
+ );
480
+ if (!response.ok)
481
+ console.error(
482
+ `Failed to fetch ${filePath}: ${response.statusText} for document ${docId} with field ${fieldName}`
483
+ );
484
+
485
+ // Use arrayBuffer if buffer is not available
486
+ const arrayBuffer = await response.arrayBuffer();
487
+ const buffer = Buffer.from(arrayBuffer);
488
+ fs.writeFileSync(tempFilePath, buffer);
489
+
490
+ // Create InputFile from the downloaded file
491
+ const inputFile = InputFile.fromPath(tempFilePath, fileName);
492
+
493
+ // Use the full file name (with extension) for creating the file
494
+ const file = await tryAwaitWithRetry(
495
+ async () => await storage.createFile(bucketId, ID.unique(), inputFile)
496
+ );
497
+
498
+ console.log("Created file from URL: ", file.$id);
499
+
500
+ // After uploading, adjust the updateData based on whether the field is an array or not
501
+ if (isArray) {
502
+ updateData = [...updateData, file.$id]; // Append the new file ID
503
+ } else {
504
+ updateData = file.$id; // Set the new file ID
505
+ }
506
+ await tryAwaitWithRetry(
507
+ async () =>
508
+ await db.updateDocument(dbId, collId, doc.$id, {
509
+ [fieldName]: updateData,
510
+ })
511
+ );
512
+
513
+ // If the file was downloaded, delete it after uploading
514
+ fs.unlinkSync(tempFilePath);
515
+ } else {
516
+ const files = fs.readdirSync(filePath);
517
+ const fileFullName = files.find((file) => file.includes(fileName));
518
+ if (!fileFullName) {
519
+ console.error(
520
+ `File starting with '${fileName}' not found in '${filePath}'`
521
+ );
522
+ return;
523
+ }
524
+ const pathToFile = path.join(filePath, fileFullName);
525
+ const inputFile = InputFile.fromPath(pathToFile, fileName);
526
+ const file = await tryAwaitWithRetry(
527
+ async () => await storage.createFile(bucketId, ID.unique(), inputFile)
528
+ );
529
+
530
+ if (isArray) {
531
+ updateData = [...updateData, file.$id]; // Append the new file ID
532
+ } else {
533
+ updateData = file.$id; // Set the new file ID
534
+ }
535
+ tryAwaitWithRetry(
536
+ async () =>
537
+ await db.updateDocument(dbId, collId, doc.$id, {
538
+ [fieldName]: updateData,
539
+ })
540
+ );
541
+ console.log("Created file from path: ", file.$id);
542
+ }
543
+ } catch (error) {
544
+ logger.error(
545
+ `Error creating file and updating field, params were:\ndbId: ${dbId}, collId: ${collId}, docId: ${docId}, fieldName: ${fieldName}, filePath: ${filePath}, fileName: ${fileName}\n\nError: ${error}`
546
+ );
547
+ console.error("Error creating file and updating field: ", error);
548
+ console.log(
549
+ `Params were: dbId: ${dbId}, collId: ${collId}, docId: ${docId}, fieldName: ${fieldName}, filePath: ${filePath}, fileName: ${fileName}`
550
+ );
551
+ }
552
+ },
553
+ };