appwrite-utils-cli 1.11.0 → 1.12.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 (250) hide show
  1. package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -1
  2. package/dist/adapters/index.js +10 -0
  3. package/dist/backups/operations/bucketBackup.d.ts +19 -0
  4. package/dist/backups/operations/bucketBackup.js +197 -0
  5. package/dist/backups/operations/collectionBackup.d.ts +30 -0
  6. package/dist/backups/operations/collectionBackup.js +201 -0
  7. package/dist/backups/operations/comprehensiveBackup.d.ts +25 -0
  8. package/dist/backups/operations/comprehensiveBackup.js +238 -0
  9. package/dist/backups/schemas/bucketManifest.d.ts +93 -0
  10. package/dist/backups/schemas/bucketManifest.js +33 -0
  11. package/dist/backups/schemas/comprehensiveManifest.d.ts +108 -0
  12. package/dist/backups/schemas/comprehensiveManifest.js +32 -0
  13. package/dist/backups/tracking/centralizedTracking.d.ts +34 -0
  14. package/dist/backups/tracking/centralizedTracking.js +274 -0
  15. package/dist/cli/commands/configCommands.d.ts +8 -0
  16. package/dist/cli/commands/configCommands.js +210 -0
  17. package/dist/cli/commands/databaseCommands.d.ts +14 -0
  18. package/dist/cli/commands/databaseCommands.js +696 -0
  19. package/dist/cli/commands/functionCommands.d.ts +7 -0
  20. package/dist/cli/commands/functionCommands.js +330 -0
  21. package/dist/cli/commands/importFileCommands.d.ts +7 -0
  22. package/dist/cli/commands/importFileCommands.js +674 -0
  23. package/dist/cli/commands/schemaCommands.d.ts +7 -0
  24. package/dist/cli/commands/schemaCommands.js +169 -0
  25. package/dist/cli/commands/storageCommands.d.ts +5 -0
  26. package/dist/cli/commands/storageCommands.js +142 -0
  27. package/dist/cli/commands/transferCommands.d.ts +5 -0
  28. package/dist/cli/commands/transferCommands.js +382 -0
  29. package/dist/collections/columns.d.ts +13 -0
  30. package/dist/collections/columns.js +1339 -0
  31. package/dist/collections/indexes.d.ts +12 -0
  32. package/dist/collections/indexes.js +215 -0
  33. package/dist/collections/methods.d.ts +19 -0
  34. package/dist/collections/methods.js +605 -0
  35. package/dist/collections/tableOperations.d.ts +87 -0
  36. package/dist/collections/tableOperations.js +466 -0
  37. package/dist/collections/transferOperations.d.ts +8 -0
  38. package/dist/collections/transferOperations.js +411 -0
  39. package/dist/collections/wipeOperations.d.ts +17 -0
  40. package/dist/collections/wipeOperations.js +306 -0
  41. package/dist/databases/methods.d.ts +6 -0
  42. package/dist/databases/methods.js +35 -0
  43. package/dist/databases/setup.d.ts +5 -0
  44. package/dist/databases/setup.js +45 -0
  45. package/dist/examples/yamlTerminologyExample.d.ts +42 -0
  46. package/dist/examples/yamlTerminologyExample.js +272 -0
  47. package/dist/functions/deployments.d.ts +4 -0
  48. package/dist/functions/deployments.js +146 -0
  49. package/dist/functions/fnConfigDiscovery.d.ts +3 -0
  50. package/dist/functions/fnConfigDiscovery.js +108 -0
  51. package/dist/functions/methods.d.ts +16 -0
  52. package/dist/functions/methods.js +174 -0
  53. package/dist/init.d.ts +2 -0
  54. package/dist/init.js +57 -0
  55. package/dist/interactiveCLI.d.ts +36 -0
  56. package/dist/interactiveCLI.js +952 -0
  57. package/dist/main.d.ts +2 -0
  58. package/dist/main.js +1125 -0
  59. package/dist/migrations/afterImportActions.d.ts +17 -0
  60. package/dist/migrations/afterImportActions.js +305 -0
  61. package/dist/migrations/appwriteToX.d.ts +211 -0
  62. package/dist/migrations/appwriteToX.js +493 -0
  63. package/dist/migrations/comprehensiveTransfer.d.ts +147 -0
  64. package/dist/migrations/comprehensiveTransfer.js +1315 -0
  65. package/dist/migrations/dataLoader.d.ts +755 -0
  66. package/dist/migrations/dataLoader.js +1272 -0
  67. package/dist/migrations/importController.d.ts +25 -0
  68. package/dist/migrations/importController.js +283 -0
  69. package/dist/migrations/importDataActions.d.ts +50 -0
  70. package/dist/migrations/importDataActions.js +230 -0
  71. package/dist/migrations/relationships.d.ts +29 -0
  72. package/dist/migrations/relationships.js +203 -0
  73. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  74. package/dist/migrations/services/DataTransformationService.js +158 -0
  75. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  76. package/dist/migrations/services/FileHandlerService.js +236 -0
  77. package/dist/migrations/services/ImportOrchestrator.d.ts +99 -0
  78. package/dist/migrations/services/ImportOrchestrator.js +493 -0
  79. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  80. package/dist/migrations/services/RateLimitManager.js +279 -0
  81. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  82. package/dist/migrations/services/RelationshipResolver.js +332 -0
  83. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  84. package/dist/migrations/services/UserMappingService.js +277 -0
  85. package/dist/migrations/services/ValidationService.d.ts +74 -0
  86. package/dist/migrations/services/ValidationService.js +260 -0
  87. package/dist/migrations/transfer.d.ts +30 -0
  88. package/dist/migrations/transfer.js +661 -0
  89. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +131 -0
  90. package/dist/migrations/yaml/YamlImportConfigLoader.js +383 -0
  91. package/dist/migrations/yaml/YamlImportIntegration.d.ts +93 -0
  92. package/dist/migrations/yaml/YamlImportIntegration.js +341 -0
  93. package/dist/migrations/yaml/generateImportSchemas.d.ts +30 -0
  94. package/dist/migrations/yaml/generateImportSchemas.js +1327 -0
  95. package/dist/schemas/authUser.d.ts +24 -0
  96. package/dist/schemas/authUser.js +17 -0
  97. package/dist/setup.d.ts +2 -0
  98. package/{src/setup.ts → dist/setup.js} +0 -3
  99. package/dist/setupCommands.d.ts +58 -0
  100. package/dist/setupCommands.js +489 -0
  101. package/dist/setupController.d.ts +9 -0
  102. package/dist/setupController.js +34 -0
  103. package/dist/shared/backupMetadataSchema.d.ts +94 -0
  104. package/dist/shared/backupMetadataSchema.js +38 -0
  105. package/dist/shared/backupTracking.d.ts +18 -0
  106. package/dist/shared/backupTracking.js +176 -0
  107. package/dist/shared/confirmationDialogs.d.ts +75 -0
  108. package/dist/shared/confirmationDialogs.js +236 -0
  109. package/dist/shared/migrationHelpers.d.ts +61 -0
  110. package/dist/shared/migrationHelpers.js +145 -0
  111. package/{src/shared/operationLogger.ts → dist/shared/operationLogger.d.ts} +1 -11
  112. package/dist/shared/operationLogger.js +12 -0
  113. package/dist/shared/operationQueue.d.ts +40 -0
  114. package/dist/shared/operationQueue.js +310 -0
  115. package/dist/shared/operationsTable.d.ts +26 -0
  116. package/dist/shared/operationsTable.js +287 -0
  117. package/dist/shared/operationsTableSchema.d.ts +48 -0
  118. package/dist/shared/operationsTableSchema.js +35 -0
  119. package/dist/shared/progressManager.d.ts +62 -0
  120. package/dist/shared/progressManager.js +215 -0
  121. package/dist/shared/relationshipExtractor.d.ts +56 -0
  122. package/dist/shared/relationshipExtractor.js +138 -0
  123. package/dist/shared/selectionDialogs.d.ts +220 -0
  124. package/dist/shared/selectionDialogs.js +588 -0
  125. package/dist/storage/backupCompression.d.ts +20 -0
  126. package/dist/storage/backupCompression.js +67 -0
  127. package/dist/storage/methods.d.ts +44 -0
  128. package/dist/storage/methods.js +475 -0
  129. package/dist/storage/schemas.d.ts +842 -0
  130. package/dist/storage/schemas.js +175 -0
  131. package/dist/tables/indexManager.d.ts +65 -0
  132. package/dist/tables/indexManager.js +294 -0
  133. package/{src/types.ts → dist/types.d.ts} +1 -6
  134. package/dist/types.js +3 -0
  135. package/dist/users/methods.d.ts +16 -0
  136. package/dist/users/methods.js +276 -0
  137. package/dist/utils/configMigration.d.ts +1 -0
  138. package/dist/utils/configMigration.js +261 -0
  139. package/dist/utils/index.js +2 -0
  140. package/dist/utils/loadConfigs.d.ts +50 -0
  141. package/dist/utils/loadConfigs.js +357 -0
  142. package/dist/utils/setupFiles.d.ts +4 -0
  143. package/dist/utils/setupFiles.js +1190 -0
  144. package/dist/utilsController.d.ts +114 -0
  145. package/dist/utilsController.js +898 -0
  146. package/package.json +6 -3
  147. package/CHANGELOG.md +0 -35
  148. package/CONFIG_TODO.md +0 -1189
  149. package/SELECTION_DIALOGS.md +0 -146
  150. package/SERVICE_IMPLEMENTATION_REPORT.md +0 -462
  151. package/scripts/copy-templates.ts +0 -23
  152. package/src/backups/operations/bucketBackup.ts +0 -277
  153. package/src/backups/operations/collectionBackup.ts +0 -310
  154. package/src/backups/operations/comprehensiveBackup.ts +0 -342
  155. package/src/backups/schemas/bucketManifest.ts +0 -78
  156. package/src/backups/schemas/comprehensiveManifest.ts +0 -76
  157. package/src/backups/tracking/centralizedTracking.ts +0 -352
  158. package/src/cli/commands/configCommands.ts +0 -265
  159. package/src/cli/commands/databaseCommands.ts +0 -931
  160. package/src/cli/commands/functionCommands.ts +0 -419
  161. package/src/cli/commands/importFileCommands.ts +0 -815
  162. package/src/cli/commands/schemaCommands.ts +0 -200
  163. package/src/cli/commands/storageCommands.ts +0 -151
  164. package/src/cli/commands/transferCommands.ts +0 -454
  165. package/src/collections/attributes.ts.backup +0 -1555
  166. package/src/collections/columns.ts +0 -2025
  167. package/src/collections/indexes.ts +0 -350
  168. package/src/collections/methods.ts +0 -714
  169. package/src/collections/tableOperations.ts +0 -542
  170. package/src/collections/transferOperations.ts +0 -589
  171. package/src/collections/wipeOperations.ts +0 -449
  172. package/src/databases/methods.ts +0 -49
  173. package/src/databases/setup.ts +0 -77
  174. package/src/examples/yamlTerminologyExample.ts +0 -346
  175. package/src/functions/deployments.ts +0 -221
  176. package/src/functions/fnConfigDiscovery.ts +0 -103
  177. package/src/functions/methods.ts +0 -284
  178. package/src/init.ts +0 -62
  179. package/src/interactiveCLI.ts +0 -1201
  180. package/src/main.ts +0 -1517
  181. package/src/migrations/afterImportActions.ts +0 -579
  182. package/src/migrations/appwriteToX.ts +0 -668
  183. package/src/migrations/comprehensiveTransfer.ts +0 -2285
  184. package/src/migrations/dataLoader.ts +0 -1729
  185. package/src/migrations/importController.ts +0 -440
  186. package/src/migrations/importDataActions.ts +0 -315
  187. package/src/migrations/relationships.ts +0 -333
  188. package/src/migrations/services/DataTransformationService.ts +0 -196
  189. package/src/migrations/services/FileHandlerService.ts +0 -311
  190. package/src/migrations/services/ImportOrchestrator.ts +0 -675
  191. package/src/migrations/services/RateLimitManager.ts +0 -363
  192. package/src/migrations/services/RelationshipResolver.ts +0 -461
  193. package/src/migrations/services/UserMappingService.ts +0 -345
  194. package/src/migrations/services/ValidationService.ts +0 -349
  195. package/src/migrations/transfer.ts +0 -1113
  196. package/src/migrations/yaml/YamlImportConfigLoader.ts +0 -439
  197. package/src/migrations/yaml/YamlImportIntegration.ts +0 -446
  198. package/src/migrations/yaml/generateImportSchemas.ts +0 -1354
  199. package/src/schemas/authUser.ts +0 -23
  200. package/src/setupCommands.ts +0 -602
  201. package/src/setupController.ts +0 -43
  202. package/src/shared/backupMetadataSchema.ts +0 -93
  203. package/src/shared/backupTracking.ts +0 -211
  204. package/src/shared/confirmationDialogs.ts +0 -327
  205. package/src/shared/migrationHelpers.ts +0 -232
  206. package/src/shared/operationQueue.ts +0 -376
  207. package/src/shared/operationsTable.ts +0 -338
  208. package/src/shared/operationsTableSchema.ts +0 -60
  209. package/src/shared/progressManager.ts +0 -278
  210. package/src/shared/relationshipExtractor.ts +0 -214
  211. package/src/shared/selectionDialogs.ts +0 -802
  212. package/src/storage/backupCompression.ts +0 -88
  213. package/src/storage/methods.ts +0 -711
  214. package/src/storage/schemas.ts +0 -205
  215. package/src/tables/indexManager.ts +0 -409
  216. package/src/types/node-appwrite-tablesdb.d.ts +0 -44
  217. package/src/users/methods.ts +0 -358
  218. package/src/utils/configMigration.ts +0 -348
  219. package/src/utils/loadConfigs.ts +0 -457
  220. package/src/utils/setupFiles.ts +0 -1236
  221. package/src/utilsController.ts +0 -1263
  222. package/tests/README.md +0 -497
  223. package/tests/adapters/AdapterFactory.test.ts +0 -277
  224. package/tests/integration/syncOperations.test.ts +0 -463
  225. package/tests/jest.config.js +0 -25
  226. package/tests/migration/configMigration.test.ts +0 -546
  227. package/tests/setup.ts +0 -62
  228. package/tests/testUtils.ts +0 -340
  229. package/tests/utils/loadConfigs.test.ts +0 -350
  230. package/tests/validation/configValidation.test.ts +0 -412
  231. package/tsconfig.json +0 -44
  232. /package/{src → dist}/functions/templates/count-docs-in-collection/README.md +0 -0
  233. /package/{src → dist}/functions/templates/count-docs-in-collection/src/main.ts +0 -0
  234. /package/{src → dist}/functions/templates/count-docs-in-collection/src/request.ts +0 -0
  235. /package/{src → dist}/functions/templates/hono-typescript/README.md +0 -0
  236. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/request.ts +0 -0
  237. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/response.ts +0 -0
  238. /package/{src → dist}/functions/templates/hono-typescript/src/app.ts +0 -0
  239. /package/{src → dist}/functions/templates/hono-typescript/src/context.ts +0 -0
  240. /package/{src → dist}/functions/templates/hono-typescript/src/main.ts +0 -0
  241. /package/{src → dist}/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -0
  242. /package/{src → dist}/functions/templates/typescript-node/README.md +0 -0
  243. /package/{src → dist}/functions/templates/typescript-node/src/context.ts +0 -0
  244. /package/{src → dist}/functions/templates/typescript-node/src/main.ts +0 -0
  245. /package/{src → dist}/functions/templates/uv/README.md +0 -0
  246. /package/{src → dist}/functions/templates/uv/pyproject.toml +0 -0
  247. /package/{src → dist}/functions/templates/uv/src/__init__.py +0 -0
  248. /package/{src → dist}/functions/templates/uv/src/context.py +0 -0
  249. /package/{src → dist}/functions/templates/uv/src/main.py +0 -0
  250. /package/{src/utils/index.ts → dist/utils/index.d.ts} +0 -0
@@ -1,579 +0,0 @@
1
- import {
2
- Databases,
3
- Storage,
4
- Query,
5
- ID,
6
- type Models,
7
- Compression,
8
- } from "node-appwrite";
9
- import { InputFile } from "node-appwrite/file";
10
- import path from "path";
11
- import fs from "fs";
12
- import os from "os";
13
- import { logger, MessageFormatter } from "appwrite-utils-helpers";
14
- import {
15
- tryAwaitWithRetry,
16
- type AfterImportActions,
17
- type AppwriteConfig,
18
- } from "appwrite-utils";
19
- import { getClientFromConfig } from "appwrite-utils-helpers";
20
-
21
- export const getDatabaseFromConfig = (config: AppwriteConfig) => {
22
- getClientFromConfig(config); // Sets config.appwriteClient if missing
23
- return new Databases(config.appwriteClient!);
24
- };
25
-
26
- export const getStorageFromConfig = (config: AppwriteConfig) => {
27
- getClientFromConfig(config); // Sets config.appwriteClient if missing
28
- return new Storage(config.appwriteClient!);
29
- };
30
-
31
- export const afterImportActions = {
32
- updateCreatedDocument: async (
33
- config: AppwriteConfig,
34
- dbId: string,
35
- collId: string,
36
- docId: string,
37
- data: any
38
- ) => {
39
- try {
40
- const db = getDatabaseFromConfig(config);
41
- await tryAwaitWithRetry(
42
- async () => await db.updateDocument(dbId, collId, docId, data)
43
- );
44
- } catch (error) {
45
- MessageFormatter.error(
46
- "Error updating document",
47
- error instanceof Error ? error : new Error(String(error)),
48
- { prefix: "Import" }
49
- );
50
- }
51
- },
52
- checkAndUpdateFieldInDocument: async (
53
- config: AppwriteConfig,
54
- dbId: string,
55
- collId: string,
56
- docId: string,
57
- fieldName: string,
58
- oldFieldValue: any,
59
- newFieldValue: any
60
- ) => {
61
- try {
62
- const db = getDatabaseFromConfig(config);
63
- const doc = await tryAwaitWithRetry(
64
- async () => await db.getDocument(dbId, collId, docId)
65
- );
66
- if (doc[fieldName as keyof typeof doc] == oldFieldValue) {
67
- await tryAwaitWithRetry(
68
- async () =>
69
- await db.updateDocument(dbId, collId, docId, {
70
- [fieldName]: newFieldValue,
71
- })
72
- );
73
- }
74
- } catch (error) {
75
- MessageFormatter.error(
76
- "Error updating document",
77
- error instanceof Error ? error : new Error(String(error)),
78
- { prefix: "Import" }
79
- );
80
- }
81
- },
82
- setFieldFromOtherCollectionDocument: async (
83
- config: AppwriteConfig,
84
- dbId: string,
85
- collIdOrName: string,
86
- docId: string,
87
- fieldName: string,
88
- otherCollIdOrName: string,
89
- otherDocId: string,
90
- otherFieldName: string
91
- ) => {
92
- const db = getDatabaseFromConfig(config);
93
-
94
- // Helper function to find a collection ID by name or return the ID if given
95
- const findCollectionId = async (collectionIdentifier: string) => {
96
- const collectionsPulled = await tryAwaitWithRetry(
97
- async () =>
98
- await db.listCollections(dbId, [
99
- Query.limit(25),
100
- Query.equal("name", collectionIdentifier),
101
- ])
102
- );
103
- if (collectionsPulled.total > 0) {
104
- return collectionsPulled.collections[0].$id;
105
- } else {
106
- // Assuming the passed identifier might directly be an ID if not found by name
107
- return collectionIdentifier;
108
- }
109
- };
110
-
111
- try {
112
- // Resolve the IDs for both the target and other collections
113
- const targetCollectionId = await findCollectionId(collIdOrName);
114
- const otherCollectionId = await findCollectionId(otherCollIdOrName);
115
-
116
- // Retrieve the "other" document
117
- const otherDoc = await db.getDocument(
118
- dbId,
119
- otherCollectionId,
120
- otherDocId
121
- );
122
- const valueToSet = otherDoc[otherFieldName as keyof typeof otherDoc];
123
-
124
- if (valueToSet) {
125
- // Update the target document
126
- await tryAwaitWithRetry(
127
- async () =>
128
- await db.updateDocument(dbId, targetCollectionId, docId, {
129
- [fieldName]: valueToSet,
130
- })
131
- );
132
- }
133
-
134
- MessageFormatter.success(
135
- `Field ${fieldName} updated successfully in document ${docId}`,
136
- { prefix: "Import" }
137
- );
138
- } catch (error) {
139
- MessageFormatter.error(
140
- "Error setting field from other collection document",
141
- error instanceof Error ? error : new Error(String(error)),
142
- { prefix: "Import" }
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 as any);
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
- MessageFormatter.success(
243
- `Field ${fieldName} updated successfully in document ${docId} with ${documentIds.length} document IDs`,
244
- { prefix: "Import" }
245
- );
246
- }
247
- } catch (error) {
248
- MessageFormatter.error(
249
- "Error setting field from other collection documents",
250
- error instanceof Error ? error : new Error(String(error)),
251
- { prefix: "Import" }
252
- );
253
- }
254
- },
255
- setTargetFieldFromOtherCollectionDocumentsByMatchingField: async (
256
- config: AppwriteConfig,
257
- dbId: string,
258
- collIdOrName: string,
259
- docId: string,
260
- fieldName: string,
261
- otherCollIdOrName: string,
262
- matchingFieldName: string,
263
- matchingFieldValue: any,
264
- targetField: string
265
- ): Promise<void> => {
266
- const db = getDatabaseFromConfig(config);
267
-
268
- const findCollectionId = async (collectionIdentifier: string) => {
269
- const collections = await tryAwaitWithRetry(
270
- async () =>
271
- await db.listCollections(dbId, [
272
- Query.equal("name", collectionIdentifier),
273
- Query.limit(1),
274
- ])
275
- );
276
- return collections.total > 0
277
- ? collections.collections[0].$id
278
- : collectionIdentifier;
279
- };
280
-
281
- const isTargetFieldArray = async (
282
- collectionId: string,
283
- fieldName: string
284
- ) => {
285
- const collection = await db.getCollection(dbId, collectionId);
286
- const attribute = collection.attributes.find(
287
- (attr: any) => attr.key === fieldName
288
- );
289
- // @ts-ignore
290
- return attribute?.array === true;
291
- };
292
-
293
- try {
294
- const targetCollectionId = await findCollectionId(collIdOrName);
295
- const otherCollectionId = await findCollectionId(otherCollIdOrName);
296
- const targetFieldIsArray = await isTargetFieldArray(
297
- targetCollectionId,
298
- fieldName
299
- );
300
-
301
- const fetchAllMatchingDocuments = async (
302
- cursor?: string
303
- ): Promise<Models.Document[]> => {
304
- const docLimit = 100;
305
- const queries = [
306
- Query.equal(matchingFieldName, matchingFieldValue),
307
- Query.limit(docLimit),
308
- ];
309
- if (cursor) {
310
- queries.push(Query.cursorAfter(cursor));
311
- }
312
- const response = await tryAwaitWithRetry(
313
- async () => await db.listDocuments(dbId, otherCollectionId, queries)
314
- );
315
- const documents = response.documents;
316
- if (documents.length === 0 || documents.length < docLimit) {
317
- return documents;
318
- }
319
- const nextCursor = documents[documents.length - 1].$id;
320
- const nextBatch = await fetchAllMatchingDocuments(nextCursor);
321
- return documents.concat(nextBatch as any);
322
- };
323
-
324
- const matchingDocuments = await fetchAllMatchingDocuments();
325
- // Map the values from the targetField instead of the document IDs
326
- const targetFieldValues = matchingDocuments.map(
327
- (doc) => doc[targetField as keyof typeof doc]
328
- );
329
-
330
- if (targetFieldValues.length > 0) {
331
- const updatePayload = targetFieldIsArray
332
- ? { [fieldName]: targetFieldValues }
333
- : { [fieldName]: targetFieldValues[0] };
334
- await tryAwaitWithRetry(
335
- async () =>
336
- await db.updateDocument(
337
- dbId,
338
- targetCollectionId,
339
- docId,
340
- updatePayload
341
- )
342
- );
343
-
344
- MessageFormatter.success(
345
- `Field ${fieldName} updated successfully in document ${docId} with values from field ${targetField}`,
346
- { prefix: "Import" }
347
- );
348
- }
349
- } catch (error) {
350
- MessageFormatter.error(
351
- "Error setting field from other collection documents",
352
- error instanceof Error ? error : new Error(String(error)),
353
- { prefix: "Import" }
354
- );
355
- }
356
- },
357
- createOrGetBucket: async (
358
- config: AppwriteConfig,
359
- bucketName: string,
360
- bucketId?: string,
361
- permissions?: string[],
362
- fileSecurity?: boolean,
363
- enabled?: boolean,
364
- maxFileSize?: number,
365
- allowedExtensions?: string[],
366
- compression?: string,
367
- encryption?: boolean,
368
- antivirus?: boolean
369
- ) => {
370
- try {
371
- const storage = getStorageFromConfig(config);
372
- const bucket = await tryAwaitWithRetry(
373
- async () => await storage.listBuckets([Query.equal("name", bucketName)])
374
- );
375
- if (bucket.buckets.length > 0) {
376
- return bucket.buckets[0];
377
- } else if (bucketId) {
378
- try {
379
- return await tryAwaitWithRetry(
380
- async () => await storage.getBucket(bucketId)
381
- );
382
- } catch (error) {
383
- return await tryAwaitWithRetry(
384
- async () =>
385
- await storage.createBucket(
386
- bucketId,
387
- bucketName,
388
- permissions,
389
- fileSecurity,
390
- enabled,
391
- maxFileSize,
392
- allowedExtensions,
393
- compression ? Compression.Gzip : undefined,
394
- encryption,
395
- antivirus
396
- )
397
- );
398
- }
399
- } else {
400
- return await tryAwaitWithRetry(
401
- async () =>
402
- await storage.createBucket(
403
- bucketId || ID.unique(),
404
- bucketName,
405
- permissions,
406
- fileSecurity,
407
- enabled,
408
- maxFileSize,
409
- allowedExtensions,
410
- compression ? Compression.Gzip : undefined,
411
- encryption,
412
- antivirus
413
- )
414
- );
415
- }
416
- } catch (error) {
417
- MessageFormatter.error(
418
- "Error creating or getting bucket",
419
- error instanceof Error ? error : new Error(String(error)),
420
- { prefix: "Import" }
421
- );
422
- }
423
- },
424
- createFileAndUpdateField: async (
425
- config: AppwriteConfig,
426
- dbId: string,
427
- collId: string,
428
- docId: string,
429
- fieldName: string,
430
- bucketId: string,
431
- filePath: string,
432
- fileName: string
433
- ) => {
434
- try {
435
- const db = getDatabaseFromConfig(config);
436
- const storage = getStorageFromConfig(config);
437
- const collection = await tryAwaitWithRetry(
438
- async () => await db.getCollection(dbId, collId)
439
- );
440
- const attributes = collection.attributes as any[];
441
- const attribute = attributes.find((a) => a.key === fieldName);
442
- // console.log(
443
- // `Processing field ${fieldName} in collection ${collId} for document ${docId} in database ${dbId} in bucket ${bucketId} with path ${filePath} and name ${fileName}...`
444
- // );
445
- if (filePath.length === 0 || fileName.length === 0) {
446
- MessageFormatter.error(
447
- `File path or name is empty for field ${fieldName} in collection ${collId}, skipping...`,
448
- undefined,
449
- { prefix: "Import" }
450
- );
451
- return;
452
- }
453
-
454
- let isArray = false;
455
- if (!attribute) {
456
- MessageFormatter.warning(
457
- `Field ${fieldName} not found in collection ${collId}, weird, skipping...`,
458
- { prefix: "Import" }
459
- );
460
- return;
461
- } else if (attribute.array === true) {
462
- isArray = true;
463
- }
464
-
465
- // Define a helper function to check if a value is a URL
466
- const isUrl = (value: any) =>
467
- typeof value === "string" &&
468
- (value.startsWith("http://") || value.startsWith("https://"));
469
-
470
- const doc = await tryAwaitWithRetry(
471
- async () => await db.getDocument(dbId, collId, docId)
472
- );
473
- const existingFieldValue = doc[fieldName as keyof typeof doc];
474
-
475
- // Handle the case where the field is an array
476
- let updateData: string | string[] = isArray ? [] : "";
477
- if (isArray && Array.isArray(existingFieldValue)) {
478
- updateData = existingFieldValue.filter((val) => !isUrl(val)); // Remove URLs from the array
479
- }
480
-
481
- // Process file upload and update logic
482
- if (isUrl(filePath)) {
483
- // Create a temporary directory
484
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "appwrite_tmp"));
485
- const tempFilePath = path.join(tempDir, fileName);
486
-
487
- // Download the file using fetch
488
- const response = await tryAwaitWithRetry(
489
- async () => await fetch(filePath)
490
- );
491
- if (!response.ok)
492
- MessageFormatter.error(
493
- `Failed to fetch ${filePath}: ${response.statusText} for document ${docId} with field ${fieldName}`,
494
- undefined,
495
- { prefix: "Import" }
496
- );
497
-
498
- // Use arrayBuffer if buffer is not available
499
- const arrayBuffer = await response.arrayBuffer();
500
- const buffer = Buffer.from(arrayBuffer);
501
- fs.writeFileSync(tempFilePath, new Uint8Array(buffer));
502
-
503
- // Create InputFile from the downloaded file
504
- const inputFile = InputFile.fromPath(tempFilePath, fileName);
505
-
506
- // Use the full file name (with extension) for creating the file
507
- const file = await tryAwaitWithRetry(
508
- async () => await storage.createFile(bucketId, ID.unique(), inputFile)
509
- );
510
-
511
- MessageFormatter.success(
512
- `Created file from URL: ${file.$id}`,
513
- { prefix: "Import" }
514
- );
515
-
516
- // After uploading, adjust the updateData based on whether the field is an array or not
517
- if (isArray) {
518
- updateData = [...updateData, file.$id]; // Append the new file ID
519
- } else {
520
- updateData = file.$id; // Set the new file ID
521
- }
522
- await tryAwaitWithRetry(
523
- async () =>
524
- await db.updateDocument(dbId, collId, doc.$id, {
525
- [fieldName]: updateData,
526
- })
527
- );
528
-
529
- // If the file was downloaded, delete it after uploading
530
- fs.unlinkSync(tempFilePath);
531
- } else {
532
- const files = fs.readdirSync(filePath);
533
- const fileFullName = files.find((file) => file.includes(fileName));
534
- if (!fileFullName) {
535
- MessageFormatter.error(
536
- `File starting with '${fileName}' not found in '${filePath}'`,
537
- undefined,
538
- { prefix: "Import" }
539
- );
540
- return;
541
- }
542
- const pathToFile = path.join(filePath, fileFullName);
543
- const inputFile = InputFile.fromPath(pathToFile, fileName);
544
- const file = await tryAwaitWithRetry(
545
- async () => await storage.createFile(bucketId, ID.unique(), inputFile)
546
- );
547
-
548
- if (isArray) {
549
- updateData = [...updateData, file.$id]; // Append the new file ID
550
- } else {
551
- updateData = file.$id; // Set the new file ID
552
- }
553
- tryAwaitWithRetry(
554
- async () =>
555
- await db.updateDocument(dbId, collId, doc.$id, {
556
- [fieldName]: updateData,
557
- })
558
- );
559
- MessageFormatter.success(
560
- `Created file from path: ${file.$id}`,
561
- { prefix: "Import" }
562
- );
563
- }
564
- } catch (error) {
565
- logger.error(
566
- `Error creating file and updating field, params were:\ndbId: ${dbId}, collId: ${collId}, docId: ${docId}, fieldName: ${fieldName}, filePath: ${filePath}, fileName: ${fileName}\n\nError: ${error}`
567
- );
568
- MessageFormatter.error(
569
- "Error creating file and updating field",
570
- error instanceof Error ? error : new Error(String(error)),
571
- { prefix: "Import" }
572
- );
573
- MessageFormatter.info(
574
- `Params were: dbId: ${dbId}, collId: ${collId}, docId: ${docId}, fieldName: ${fieldName}, filePath: ${filePath}, fileName: ${fileName}`,
575
- { prefix: "Import" }
576
- );
577
- }
578
- },
579
- };