appwrite-utils-cli 1.3.4 → 1.4.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 (116) hide show
  1. package/dist/adapters/AdapterFactory.d.ts +87 -0
  2. package/dist/adapters/AdapterFactory.js +217 -0
  3. package/dist/adapters/DatabaseAdapter.d.ts +217 -0
  4. package/dist/adapters/DatabaseAdapter.js +50 -0
  5. package/dist/adapters/LegacyAdapter.d.ts +49 -0
  6. package/dist/adapters/LegacyAdapter.js +382 -0
  7. package/dist/adapters/TablesDBAdapter.d.ts +55 -0
  8. package/dist/adapters/TablesDBAdapter.js +302 -0
  9. package/dist/adapters/index.d.ts +11 -0
  10. package/dist/adapters/index.js +12 -0
  11. package/dist/collections/attributes.js +43 -24
  12. package/dist/collections/methods.d.ts +4 -3
  13. package/dist/collections/methods.js +34 -14
  14. package/dist/config/yamlConfig.d.ts +40 -437
  15. package/dist/config/yamlConfig.js +8 -2
  16. package/dist/databases/setup.js +2 -2
  17. package/dist/main.js +0 -0
  18. package/dist/migrations/appwriteToX.d.ts +26 -37
  19. package/dist/migrations/comprehensiveTransfer.js +4 -4
  20. package/dist/migrations/dataLoader.d.ts +124 -1484
  21. package/dist/migrations/dataLoader.js +2 -1
  22. package/dist/migrations/relationships.d.ts +2 -3
  23. package/dist/migrations/relationships.js +1 -1
  24. package/dist/migrations/services/UserMappingService.js +1 -1
  25. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +24 -279
  26. package/dist/migrations/yaml/YamlImportConfigLoader.js +7 -2
  27. package/dist/schemas/authUser.d.ts +7 -47
  28. package/dist/schemas/authUser.js +1 -1
  29. package/dist/shared/jsonSchemaGenerator.d.ts +0 -2
  30. package/dist/shared/jsonSchemaGenerator.js +4 -17
  31. package/dist/shared/migrationHelpers.d.ts +17 -119
  32. package/dist/shared/operationQueue.js +16 -7
  33. package/dist/shared/schemaGenerator.js +2 -17
  34. package/dist/storage/schemas.d.ts +149 -296
  35. package/dist/users/methods.d.ts +2 -2
  36. package/dist/utils/configMigration.js +0 -1
  37. package/dist/utils/getClientFromConfig.d.ts +26 -0
  38. package/dist/utils/getClientFromConfig.js +37 -0
  39. package/dist/utils/loadConfigs.js +0 -2
  40. package/dist/utils/schemaStrings.js +2 -17
  41. package/dist/utils/setupFiles.js +2 -0
  42. package/dist/utils/versionDetection.d.ts +56 -0
  43. package/dist/utils/versionDetection.js +217 -0
  44. package/dist/utils/yamlConverter.d.ts +0 -1
  45. package/dist/utils/yamlConverter.js +0 -2
  46. package/dist/utilsController.js +2 -0
  47. package/package.json +3 -2
  48. package/src/adapters/AdapterFactory.ts +296 -0
  49. package/src/adapters/DatabaseAdapter.ts +290 -0
  50. package/src/adapters/LegacyAdapter.ts +667 -0
  51. package/src/adapters/TablesDBAdapter.ts +429 -0
  52. package/src/adapters/index.ts +37 -0
  53. package/src/collections/attributes.ts +351 -157
  54. package/src/collections/methods.ts +43 -28
  55. package/src/config/yamlConfig.ts +8 -2
  56. package/src/databases/setup.ts +2 -2
  57. package/src/migrations/afterImportActions.ts +2 -2
  58. package/src/migrations/comprehensiveTransfer.ts +4 -0
  59. package/src/migrations/dataLoader.ts +2 -1
  60. package/src/migrations/relationships.ts +1 -1
  61. package/src/migrations/services/UserMappingService.ts +1 -1
  62. package/src/migrations/yaml/YamlImportConfigLoader.ts +7 -2
  63. package/src/schemas/authUser.ts +1 -1
  64. package/src/shared/jsonSchemaGenerator.ts +4 -19
  65. package/src/shared/operationQueue.ts +20 -13
  66. package/src/shared/schemaGenerator.ts +2 -16
  67. package/src/types/node-appwrite-tablesdb.d.ts +44 -0
  68. package/src/users/methods.ts +2 -2
  69. package/src/utils/configMigration.ts +0 -1
  70. package/src/utils/getClientFromConfig.ts +56 -0
  71. package/src/utils/loadConfigs.ts +0 -2
  72. package/src/utils/schemaStrings.ts +2 -16
  73. package/src/utils/setupFiles.ts +2 -0
  74. package/src/utils/versionDetection.ts +265 -0
  75. package/src/utils/yamlConverter.ts +0 -2
  76. package/src/utilsController.ts +2 -0
  77. package/dist/functions/openapi.d.ts +0 -4
  78. package/dist/functions/openapi.js +0 -60
  79. package/dist/migrations/attributes.d.ts +0 -4
  80. package/dist/migrations/attributes.js +0 -301
  81. package/dist/migrations/backup.d.ts +0 -687
  82. package/dist/migrations/backup.js +0 -175
  83. package/dist/migrations/collections.d.ts +0 -22
  84. package/dist/migrations/collections.js +0 -347
  85. package/dist/migrations/converters.d.ts +0 -46
  86. package/dist/migrations/converters.js +0 -139
  87. package/dist/migrations/databases.d.ts +0 -2
  88. package/dist/migrations/databases.js +0 -28
  89. package/dist/migrations/dbHelpers.d.ts +0 -5
  90. package/dist/migrations/dbHelpers.js +0 -57
  91. package/dist/migrations/helper.d.ts +0 -3
  92. package/dist/migrations/helper.js +0 -21
  93. package/dist/migrations/indexes.d.ts +0 -4
  94. package/dist/migrations/indexes.js +0 -19
  95. package/dist/migrations/logging.d.ts +0 -10
  96. package/dist/migrations/logging.js +0 -46
  97. package/dist/migrations/migrationHelper.d.ts +0 -173
  98. package/dist/migrations/migrationHelper.js +0 -130
  99. package/dist/migrations/openapi.d.ts +0 -4
  100. package/dist/migrations/openapi.js +0 -60
  101. package/dist/migrations/queue.d.ts +0 -13
  102. package/dist/migrations/queue.js +0 -79
  103. package/dist/migrations/schemaStrings.d.ts +0 -14
  104. package/dist/migrations/schemaStrings.js +0 -478
  105. package/dist/migrations/setupDatabase.d.ts +0 -6
  106. package/dist/migrations/setupDatabase.js +0 -115
  107. package/dist/migrations/storage.d.ts +0 -10
  108. package/dist/migrations/storage.js +0 -340
  109. package/dist/migrations/users.d.ts +0 -16
  110. package/dist/migrations/users.js +0 -276
  111. package/dist/migrations/validationRules.d.ts +0 -43
  112. package/dist/migrations/validationRules.js +0 -42
  113. package/dist/shared/attributeManager.d.ts +0 -17
  114. package/dist/shared/attributeManager.js +0 -272
  115. package/src/functions/openapi.ts +0 -83
  116. package/src/shared/attributeManager.ts +0 -428
@@ -1,115 +0,0 @@
1
- import { Databases, Query } from "node-appwrite";
2
- import { createOrUpdateAttribute } from "../collections/attributes.js";
3
- import { getMigrationCollectionSchemas } from "./backup.js";
4
- import { areCollectionNamesSame, delay, toCamelCase, tryAwaitWithRetry, } from "../utils/index.js";
5
- import {} from "appwrite-utils";
6
- import { ulid } from "ulidx";
7
- export const setupMigrationDatabase = async (config) => {
8
- console.log("---------------------------------");
9
- console.log("Starting Migrations Setup");
10
- console.log("---------------------------------");
11
- const database = new Databases(config.appwriteClient);
12
- if (!config.appwriteClient) {
13
- throw new Error("Appwrite client is not initialized in the config");
14
- }
15
- let db;
16
- const migrationCollectionsSetup = getMigrationCollectionSchemas();
17
- try {
18
- db = await tryAwaitWithRetry(async () => await database.get("migrations"), undefined, true);
19
- console.log("Migrations database found");
20
- }
21
- catch (e) {
22
- db = await tryAwaitWithRetry(async () => await database.create("migrations", "Migrations", true));
23
- console.log("Migrations database created");
24
- }
25
- if (!db) {
26
- console.error("Failed to create or retrieve the migrations database");
27
- return;
28
- }
29
- for (const [collectionName, { collection, attributes }] of Object.entries(migrationCollectionsSetup)) {
30
- const collectionId = toCamelCase(collectionName);
31
- let collectionFound;
32
- try {
33
- collectionFound = await tryAwaitWithRetry(async () => await database.getCollection(db.$id, collectionId), undefined, true);
34
- console.log(`Collection found: ${collectionId}`);
35
- }
36
- catch (e) {
37
- console.log(`Collection not found: ${collectionId}`);
38
- try {
39
- collectionFound = await tryAwaitWithRetry(async () => await database.createCollection(db.$id, collectionId, collectionName, undefined, collection.documentSecurity, collection.enabled), undefined, true);
40
- console.log(`Collection created: ${collectionId}`);
41
- }
42
- catch (createError) {
43
- console.error(`Failed to create collection: ${collectionId}`, createError);
44
- continue;
45
- }
46
- }
47
- if (!collectionFound) {
48
- console.error(`Failed to create or retrieve collection: ${collectionId}`);
49
- continue;
50
- }
51
- for (const attribute of attributes) {
52
- try {
53
- await createOrUpdateAttribute(database, db.$id, collectionFound, attribute);
54
- await delay(100);
55
- console.log(`Attribute created/updated: ${attribute.key}`);
56
- }
57
- catch (attrError) {
58
- console.error(`Failed to create/update attribute: ${attribute.key}`, attrError);
59
- }
60
- }
61
- }
62
- console.log("---------------------------------");
63
- console.log("Migrations Setup Complete");
64
- console.log("---------------------------------");
65
- };
66
- export const ensureDatabasesExist = async (config, databasesToEnsure) => {
67
- if (!config.appwriteClient) {
68
- throw new Error("Appwrite client is not initialized in the config");
69
- }
70
- const database = new Databases(config.appwriteClient);
71
- const databasesToCreate = databasesToEnsure || config.databases || [];
72
- if (!databasesToCreate.length) {
73
- console.log("No databases to create");
74
- return;
75
- }
76
- const existingDatabases = await tryAwaitWithRetry(async () => await database.list([Query.limit(500)]));
77
- const migrationsDatabase = existingDatabases.databases.find((d) => d.name.toLowerCase().trim().replace(" ", "") === "migrations");
78
- if (existingDatabases.databases.length !== 0 && migrationsDatabase) {
79
- console.log("Creating all databases except migrations");
80
- databasesToCreate.push(migrationsDatabase);
81
- }
82
- for (const db of databasesToCreate) {
83
- if (!existingDatabases.databases.some((d) => d.name === db.name)) {
84
- await tryAwaitWithRetry(async () => await database.create(db.$id || ulid(), db.name, true));
85
- console.log(`${db.name} database created`);
86
- }
87
- }
88
- };
89
- export const wipeOtherDatabases = async (database, databasesToKeep) => {
90
- console.log(`Databases to keep: ${databasesToKeep.map(db => db.name).join(", ")}`);
91
- const allDatabases = await tryAwaitWithRetry(async () => await database.list([Query.limit(500)]));
92
- const migrationsDatabase = allDatabases.databases.find((d) => d.name.toLowerCase().trim().replace(" ", "") === "migrations");
93
- if (allDatabases.databases.length !== 0 && migrationsDatabase) {
94
- console.log("Wiping all databases except migrations");
95
- databasesToKeep.push(migrationsDatabase);
96
- }
97
- for (const db of allDatabases.databases) {
98
- if (!databasesToKeep.some((d) => d.name === db.name)) {
99
- await tryAwaitWithRetry(async () => await database.delete(db.$id));
100
- console.log(`Deleted database: ${db.name}`);
101
- }
102
- }
103
- };
104
- export const ensureCollectionsExist = async (config, database, collectionsToEnsure) => {
105
- const databaseClient = new Databases(config.appwriteClient);
106
- const collectionsToCreate = collectionsToEnsure ||
107
- (config.collections ? config.collections : []);
108
- const existingCollections = await tryAwaitWithRetry(async () => await databaseClient.listCollections(database.$id, [Query.limit(500)]));
109
- for (const collection of collectionsToCreate) {
110
- if (!existingCollections.collections.some((c) => c.name === collection.name)) {
111
- await tryAwaitWithRetry(async () => await databaseClient.createCollection(database.$id, ulid(), collection.name, undefined, true, true));
112
- console.log(`${collection.name} collection created in ${database.name}`);
113
- }
114
- }
115
- };
@@ -1,10 +0,0 @@
1
- import { Storage, Databases, type Models } from "node-appwrite";
2
- import { type OperationCreate } from "./backup.js";
3
- import type { AppwriteConfig } from "appwrite-utils";
4
- export declare const logOperation: (db: Databases, dbId: string, operationDetails: OperationCreate, operationId?: string) => Promise<Models.Document>;
5
- export declare const initOrGetBackupStorage: (storage: Storage) => Promise<Models.Bucket>;
6
- export declare const initOrGetDocumentStorage: (storage: Storage, config: AppwriteConfig, dbId: string, bucketName?: string) => Promise<Models.Bucket | undefined>;
7
- export declare const wipeDocumentStorage: (storage: Storage, config: AppwriteConfig, dbName: string) => Promise<void>;
8
- export declare const backupDatabase: (database: Databases, databaseId: string, storage: Storage) => Promise<void>;
9
- export declare const transferStorageLocalToLocal: (storage: Storage, fromBucketId: string, toBucketId: string) => Promise<void>;
10
- export declare const transferStorageLocalToRemote: (localStorage: Storage, endpoint: string, projectId: string, apiKey: string, fromBucketId: string, toBucketId: string) => Promise<void>;
@@ -1,340 +0,0 @@
1
- import { Storage, Databases, Query, ID, Permission, } from "node-appwrite";
2
- import { InputFile } from "node-appwrite/file";
3
- import {} from "./backup.js";
4
- import { splitIntoBatches } from "./migrationHelper.js";
5
- import { getAppwriteClient, tryAwaitWithRetry, } from "../utils/helperFunctions.js";
6
- export const logOperation = async (db, dbId, operationDetails, operationId) => {
7
- try {
8
- let operation;
9
- if (operationId) {
10
- // Update existing operation log
11
- operation = await tryAwaitWithRetry(async () => await db.updateDocument("migrations", "currentOperations", operationId, operationDetails));
12
- }
13
- else {
14
- // Create new operation log
15
- operation = await db.createDocument("migrations", "currentOperations", ID.unique(), operationDetails);
16
- }
17
- console.log(`Operation logged: ${operation.$id}`);
18
- return operation;
19
- }
20
- catch (error) {
21
- console.error(`Error logging operation: ${error}`);
22
- throw error;
23
- }
24
- };
25
- export const initOrGetBackupStorage = async (storage) => {
26
- try {
27
- const backupStorage = await tryAwaitWithRetry(async () => await storage.getBucket("backupStorage"));
28
- return backupStorage;
29
- }
30
- catch (e) {
31
- // ID backupStorage
32
- // Name Backups Storage
33
- const backupStorage = await tryAwaitWithRetry(async () => await storage.createBucket("backupStorage", "Backups Storage"));
34
- return backupStorage;
35
- }
36
- };
37
- export const initOrGetDocumentStorage = async (storage, config, dbId, bucketName) => {
38
- try {
39
- await tryAwaitWithRetry(async () => await storage.getBucket(bucketName ??
40
- `${config.documentBucketId}_${dbId.toLowerCase().replace(" ", "")}`));
41
- }
42
- catch (e) {
43
- // ID documentStorage
44
- // Name Document Storage
45
- const documentStorage = await tryAwaitWithRetry(async () => await storage.createBucket(`${config.documentBucketId}_${dbId.toLowerCase().replace(" ", "")}`, `${dbId} Storage`, [
46
- Permission.read("any"),
47
- Permission.create("users"),
48
- Permission.update("users"),
49
- Permission.delete("users"),
50
- ]));
51
- return documentStorage;
52
- }
53
- };
54
- export const wipeDocumentStorage = async (storage, config, dbName) => {
55
- const bucketId = `${config.documentBucketId
56
- .toLowerCase()
57
- .replace(" ", "")}_${dbName.toLowerCase().replace(" ", "")}`;
58
- console.log(`Wiping storage for bucket ID: ${bucketId}`);
59
- let moreFiles = true;
60
- let lastFileId;
61
- const allFiles = [];
62
- while (moreFiles) {
63
- const queries = [Query.limit(100)]; // Adjust the limit as needed
64
- if (lastFileId) {
65
- queries.push(Query.cursorAfter(lastFileId));
66
- }
67
- const filesPulled = await tryAwaitWithRetry(async () => await storage.listFiles(bucketId, queries));
68
- if (filesPulled.files.length === 0) {
69
- console.log("No files found, done!");
70
- moreFiles = false;
71
- break;
72
- }
73
- else if (filesPulled.files.length > 0) {
74
- const fileIds = filesPulled.files.map((file) => file.$id);
75
- allFiles.push(...fileIds);
76
- }
77
- moreFiles = filesPulled.files.length === 100; // Adjust based on the limit
78
- if (moreFiles) {
79
- lastFileId = filesPulled.files[filesPulled.files.length - 1].$id;
80
- }
81
- }
82
- for (const fileId of allFiles) {
83
- console.log(`Deleting file: ${fileId}`);
84
- await tryAwaitWithRetry(async () => await storage.deleteFile(bucketId, fileId));
85
- }
86
- console.log(`All files in bucket ${bucketId} have been deleted.`);
87
- };
88
- async function retryFailedPromises(batch, maxRetries = 3) {
89
- const results = await Promise.allSettled(batch);
90
- const toRetry = [];
91
- results.forEach((result, index) => {
92
- if (result.status === "rejected") {
93
- console.error("Promise rejected with reason:", result.reason);
94
- if (maxRetries > 0) {
95
- toRetry.push(batch[index]);
96
- }
97
- }
98
- });
99
- if (toRetry.length > 0) {
100
- console.log(`Retrying ${toRetry.length} promises`);
101
- return retryFailedPromises(toRetry, maxRetries - 1);
102
- }
103
- else {
104
- return results
105
- .filter((result) => result.status === "fulfilled")
106
- .map((result) => result);
107
- }
108
- }
109
- export const backupDatabase = async (database, databaseId, storage) => {
110
- console.log("---------------------------------");
111
- console.log("Starting Database Backup of " + databaseId);
112
- console.log("---------------------------------");
113
- let data = {
114
- database: "",
115
- collections: [],
116
- documents: [],
117
- };
118
- const backupOperation = await logOperation(database, databaseId, {
119
- operationType: "backup",
120
- collectionId: "",
121
- data: "Starting backup...",
122
- progress: 0,
123
- total: 100, // This will be dynamically updated later
124
- error: "",
125
- status: "in_progress",
126
- });
127
- // Fetch and backup the database details
128
- let db;
129
- try {
130
- db = await tryAwaitWithRetry(async () => await database.get(databaseId));
131
- }
132
- catch (e) {
133
- console.error(`Error fetching database: ${e}`);
134
- await logOperation(database, databaseId, {
135
- operationType: "backup",
136
- collectionId: "",
137
- data: "Error fetching database, skipping...",
138
- progress: 0,
139
- total: 100, // This will be dynamically updated later
140
- error: `Error fetching database: ${e}`,
141
- status: "error",
142
- }, backupOperation.$id);
143
- return;
144
- }
145
- data.database = JSON.stringify(db);
146
- // Initialize pagination for collections
147
- let lastCollectionId = "";
148
- let moreCollections = true;
149
- let progress = 0;
150
- let total = 0; // Initialize total to 0, will be updated dynamically
151
- while (moreCollections) {
152
- const collectionResponse = await tryAwaitWithRetry(async () => await database.listCollections(databaseId, [
153
- Query.limit(500), // Adjust the limit as needed
154
- ...(lastCollectionId ? [Query.cursorAfter(lastCollectionId)] : []),
155
- ]));
156
- total += collectionResponse.collections.length; // Update total with number of collections
157
- for (const { $id: collectionId, name: collectionName, } of collectionResponse.collections) {
158
- let collectionDocumentCount = 0; // Initialize document count for the current collection
159
- try {
160
- const collection = await tryAwaitWithRetry(async () => await database.getCollection(databaseId, collectionId));
161
- progress++;
162
- data.collections.push(JSON.stringify(collection));
163
- // Initialize pagination for documents within the current collection
164
- let lastDocumentId = "";
165
- let moreDocuments = true;
166
- while (moreDocuments) {
167
- const documentResponse = await tryAwaitWithRetry(async () => await database.listDocuments(databaseId, collectionId, [
168
- Query.limit(500), // Adjust the limit as needed
169
- ...(lastDocumentId ? [Query.cursorAfter(lastDocumentId)] : []),
170
- ]));
171
- total += documentResponse.documents.length; // Update total with number of documents
172
- collectionDocumentCount += documentResponse.documents.length; // Update document count for the current collection
173
- let documentPromises = [];
174
- for (const { $id: documentId } of documentResponse.documents) {
175
- documentPromises.push(database.getDocument(databaseId, collectionId, documentId));
176
- }
177
- const promiseBatches = splitIntoBatches(documentPromises);
178
- const documentsPulled = [];
179
- for (const batch of promiseBatches) {
180
- const successfulDocuments = await retryFailedPromises(batch);
181
- documentsPulled.push(...successfulDocuments);
182
- }
183
- const documents = documentsPulled;
184
- data.documents.push({
185
- collectionId: collectionId,
186
- data: JSON.stringify(documents),
187
- });
188
- progress += documents.length;
189
- console.log(`Collection ${collectionName} backed up ${collectionDocumentCount} documents (so far)`);
190
- // Update the operation log with the current progress
191
- await logOperation(database, databaseId, {
192
- operationType: "backup",
193
- collectionId: collectionId,
194
- data: `Still backing up, ${data.collections.length} collections so far`,
195
- progress: progress,
196
- total: total,
197
- error: "",
198
- status: "in_progress",
199
- }, backupOperation.$id);
200
- // Check if there are more documents to fetch
201
- moreDocuments = documentResponse.documents.length === 500;
202
- if (moreDocuments) {
203
- lastDocumentId =
204
- documentResponse.documents[documentResponse.documents.length - 1]
205
- .$id;
206
- }
207
- }
208
- console.log(`Collection ${collectionName} backed up with ${collectionDocumentCount} documents.`);
209
- }
210
- catch (error) {
211
- console.log(`Collection ${collectionName} must not exist, continuing...`);
212
- continue;
213
- }
214
- }
215
- // Check if there are more collections to fetch
216
- moreCollections = collectionResponse.collections.length === 500;
217
- if (moreCollections) {
218
- lastCollectionId =
219
- collectionResponse.collections[collectionResponse.collections.length - 1].$id;
220
- }
221
- }
222
- // Update the backup operation with the current progress and total
223
- await logOperation(database, databaseId, {
224
- operationType: "backup",
225
- collectionId: "",
226
- data: `Still backing up, ${data.collections.length} collections so far`,
227
- progress: progress,
228
- total: total,
229
- error: "",
230
- status: "in_progress",
231
- }, backupOperation.$id);
232
- // Create the backup with the accumulated data
233
- const bucket = await initOrGetBackupStorage(storage);
234
- const inputFile = InputFile.fromPlainText(JSON.stringify(data), `${new Date().toISOString()}-${databaseId}.json`);
235
- const fileCreated = await storage.createFile(bucket.$id, ID.unique(), inputFile);
236
- // Final update to the backup operation marking it as completed
237
- await logOperation(database, databaseId, {
238
- operationType: "backup",
239
- collectionId: "",
240
- data: fileCreated.$id,
241
- progress: 100,
242
- total: total, // Ensure the total reflects the actual total processed
243
- error: "",
244
- status: "completed",
245
- }, backupOperation.$id);
246
- console.log("---------------------------------");
247
- console.log("Database Backup Complete");
248
- console.log("---------------------------------");
249
- };
250
- export const transferStorageLocalToLocal = async (storage, fromBucketId, toBucketId) => {
251
- console.log(`Transferring files from ${fromBucketId} to ${toBucketId}`);
252
- let lastFileId;
253
- let fromFiles = await tryAwaitWithRetry(async () => await storage.listFiles(fromBucketId, [Query.limit(100)]));
254
- const allFromFiles = fromFiles.files;
255
- let numberOfFiles = 0;
256
- const downloadFileWithRetry = async (bucketId, fileId) => {
257
- let attempts = 3;
258
- while (attempts > 0) {
259
- try {
260
- return await storage.getFileDownload(bucketId, fileId);
261
- }
262
- catch (error) {
263
- console.error(`Error downloading file ${fileId}: ${error}`);
264
- attempts--;
265
- if (attempts === 0)
266
- throw error;
267
- }
268
- }
269
- };
270
- if (fromFiles.files.length < 100) {
271
- for (const file of allFromFiles) {
272
- const fileData = await tryAwaitWithRetry(async () => await downloadFileWithRetry(file.bucketId, file.$id));
273
- if (!fileData) {
274
- console.error(`Error downloading file ${file.$id}`);
275
- continue;
276
- }
277
- const fileToCreate = InputFile.fromBuffer(new Uint8Array(fileData), file.name);
278
- console.log(`Creating file: ${file.name}`);
279
- tryAwaitWithRetry(async () => await storage.createFile(toBucketId, file.$id, fileToCreate, file.$permissions));
280
- numberOfFiles++;
281
- }
282
- }
283
- else {
284
- lastFileId = fromFiles.files[fromFiles.files.length - 1].$id;
285
- while (lastFileId) {
286
- const files = await tryAwaitWithRetry(async () => await storage.listFiles(fromBucketId, [
287
- Query.limit(100),
288
- Query.cursorAfter(lastFileId),
289
- ]));
290
- allFromFiles.push(...files.files);
291
- if (files.files.length < 100) {
292
- lastFileId = undefined;
293
- }
294
- else {
295
- lastFileId = files.files[files.files.length - 1].$id;
296
- }
297
- }
298
- for (const file of allFromFiles) {
299
- const fileData = await tryAwaitWithRetry(async () => await downloadFileWithRetry(file.bucketId, file.$id));
300
- if (!fileData) {
301
- console.error(`Error downloading file ${file.$id}`);
302
- continue;
303
- }
304
- const fileToCreate = InputFile.fromBuffer(new Uint8Array(fileData), file.name);
305
- await tryAwaitWithRetry(async () => await storage.createFile(toBucketId, file.$id, fileToCreate, file.$permissions));
306
- numberOfFiles++;
307
- }
308
- }
309
- console.log(`Transferred ${numberOfFiles} files from ${fromBucketId} to ${toBucketId}`);
310
- };
311
- export const transferStorageLocalToRemote = async (localStorage, endpoint, projectId, apiKey, fromBucketId, toBucketId) => {
312
- console.log(`Transferring files from current storage ${fromBucketId} to ${endpoint} bucket ${toBucketId}`);
313
- const client = getAppwriteClient(endpoint, apiKey, projectId);
314
- const remoteStorage = new Storage(client);
315
- let numberOfFiles = 0;
316
- let lastFileId;
317
- let fromFiles = await tryAwaitWithRetry(async () => await localStorage.listFiles(fromBucketId, [Query.limit(100)]));
318
- const allFromFiles = fromFiles.files;
319
- if (fromFiles.files.length === 100) {
320
- lastFileId = fromFiles.files[fromFiles.files.length - 1].$id;
321
- while (lastFileId) {
322
- const files = await tryAwaitWithRetry(async () => await localStorage.listFiles(fromBucketId, [
323
- Query.limit(100),
324
- Query.cursorAfter(lastFileId),
325
- ]));
326
- allFromFiles.push(...files.files);
327
- if (files.files.length < 100) {
328
- break;
329
- }
330
- lastFileId = files.files[files.files.length - 1].$id;
331
- }
332
- }
333
- for (const file of allFromFiles) {
334
- const fileData = await tryAwaitWithRetry(async () => await localStorage.getFileDownload(file.bucketId, file.$id));
335
- const fileToCreate = InputFile.fromBuffer(new Uint8Array(fileData), file.name);
336
- await tryAwaitWithRetry(async () => await remoteStorage.createFile(toBucketId, file.$id, fileToCreate, file.$permissions));
337
- numberOfFiles++;
338
- }
339
- console.log(`Transferred ${numberOfFiles} files from ${fromBucketId} to ${toBucketId}`);
340
- };
@@ -1,16 +0,0 @@
1
- import type { AppwriteConfig } from "appwrite-utils";
2
- import { Databases, type Models } from "node-appwrite";
3
- import { type AuthUserCreate } from "../schemas/authUser.js";
4
- export declare class UsersController {
5
- private config;
6
- private users;
7
- static userFields: string[];
8
- constructor(config: AppwriteConfig, db: Databases);
9
- wipeUsers(): Promise<void>;
10
- getAllUsers(): Promise<Models.User<Models.Preferences>[]>;
11
- createUsersAndReturn(items: AuthUserCreate[]): Promise<(Models.User<Models.Preferences> | undefined)[]>;
12
- createUserAndReturn(item: AuthUserCreate): Promise<Models.User<Models.Preferences> | undefined>;
13
- createAndCheckForUserAndReturn(item: AuthUserCreate): Promise<Models.User<Models.Preferences> | undefined>;
14
- getUserIdByEmailOrPhone(email?: string, phone?: string): Promise<string | undefined>;
15
- transferUsersBetweenDbsLocalToRemote: (endpoint: string, projectId: string, apiKey: string) => Promise<void>;
16
- }