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
@@ -0,0 +1,1272 @@
1
+ import { AttributeMappingsSchema, CollectionCreateSchema, importDefSchema, } from "appwrite-utils";
2
+ import path from "path";
3
+ import fs from "fs";
4
+ import { convertObjectByAttributeMappings } from "appwrite-utils-helpers";
5
+ import { z } from "zod";
6
+ import { checkForCollection } from "../collections/methods.js";
7
+ import { ID, Users } from "node-appwrite";
8
+ import { logger, AdapterFactory, MessageFormatter } from "appwrite-utils-helpers";
9
+ import { findOrCreateOperation, updateOperation } from "../shared/migrationHelpers.js";
10
+ import { AuthUserCreateSchema } from "../schemas/authUser.js";
11
+ import { UsersController } from "../users/methods.js";
12
+ import { isEmpty } from "es-toolkit/compat";
13
+ // Define a schema for the structure of collection import data using Zod for validation
14
+ export const CollectionImportDataSchema = z.object({
15
+ // Optional collection creation schema
16
+ collection: CollectionCreateSchema.optional(),
17
+ // Array of data objects each containing rawData, finalData, context, and an import definition
18
+ data: z.array(z.object({
19
+ rawData: z.any(), // The initial raw data
20
+ finalData: z.any(), // The transformed data ready for import
21
+ context: z.any(), // Additional context for the data transformation
22
+ importDef: importDefSchema.optional(), // The import definition schema
23
+ })),
24
+ });
25
+ // DataLoader class to handle the loading of data into collections
26
+ export class DataLoader {
27
+ // Private member variables to hold configuration and state
28
+ appwriteFolderPath;
29
+ importDataActions;
30
+ database;
31
+ usersController;
32
+ config;
33
+ // Map to hold the import data for each collection by name
34
+ importMap = new Map();
35
+ // Map to track old to new ID mappings for each collection, if applicable
36
+ oldIdToNewIdPerCollectionMap = new Map();
37
+ // Map to hold the import operation ID for each collection
38
+ collectionImportOperations = new Map();
39
+ // Map to hold the merged user map for relationship resolution
40
+ // Will hold an array of the old user ID's that are mapped to the same new user ID
41
+ // For example, if there are two users with the same email, they will both be mapped to the same new user ID
42
+ // Prevents duplicate users with the other two maps below it and allows me to keep the old ID's
43
+ mergedUserMap = new Map();
44
+ // Maps to hold email and phone to user ID mappings for unique-ness in User Accounts
45
+ emailToUserIdMap = new Map();
46
+ phoneToUserIdMap = new Map();
47
+ userIdSet = new Set();
48
+ userExistsMap = new Map();
49
+ shouldWriteFile = false;
50
+ _adapter = null;
51
+ async getAdapter() {
52
+ if (!this._adapter) {
53
+ const { adapter } = await AdapterFactory.createFromConfig(this.config);
54
+ this._adapter = adapter;
55
+ }
56
+ return this._adapter;
57
+ }
58
+ // Constructor to initialize the DataLoader with necessary configurations
59
+ constructor(appwriteFolderPath, importDataActions, database, config, shouldWriteFile) {
60
+ this.appwriteFolderPath = appwriteFolderPath;
61
+ this.importDataActions = importDataActions;
62
+ this.database = database;
63
+ this.usersController = new UsersController(config, database);
64
+ this.config = config;
65
+ this.shouldWriteFile = shouldWriteFile || false;
66
+ }
67
+ // Helper method to generate a consistent key for collections
68
+ getCollectionKey(name) {
69
+ return name.toLowerCase().replace(" ", "");
70
+ }
71
+ /**
72
+ * Merges two objects by updating the source object with the target object's values.
73
+ * It iterates through the target object's keys and updates the source object if:
74
+ * - The source object has the key.
75
+ * - The target object's value for that key is not null, undefined, or an empty string.
76
+ * - If the target object has an array value, it concatenates the values and removes duplicates.
77
+ *
78
+ * @param source - The source object to be updated.
79
+ * @param target - The target object with values to update the source object.
80
+ * @returns The updated source object.
81
+ */
82
+ mergeObjects(source, update) {
83
+ // Create a new object to hold the merged result
84
+ const result = { ...source };
85
+ // Loop through the keys of the object we care about
86
+ for (const [key, value] of Object.entries(source)) {
87
+ // Check if the key exists in the target object
88
+ if (!Object.hasOwn(update, key)) {
89
+ // If the key doesn't exist, we can just skip it like bad cheese
90
+ continue;
91
+ }
92
+ if (update[key] === value) {
93
+ continue;
94
+ }
95
+ // If the value ain't here, we can just do whatever man
96
+ if (value === undefined || value === null || value === "") {
97
+ // If the update key is defined
98
+ if (update[key] !== undefined &&
99
+ update[key] !== null &&
100
+ update[key] !== "") {
101
+ // might as well use it eh?
102
+ result[key] = update[key];
103
+ }
104
+ // ELSE if the value is an array, because it would then not be === to those things above
105
+ }
106
+ else if (Array.isArray(value)) {
107
+ // Get the update value
108
+ const updateValue = update[key];
109
+ // If the update value is an array, concatenate and remove duplicates
110
+ // and poopy data
111
+ if (Array.isArray(updateValue)) {
112
+ result[key] = [...new Set([...value, ...updateValue])].filter((item) => item !== null && item !== undefined && item !== "");
113
+ }
114
+ else {
115
+ // If the update value is not an array, just use it
116
+ result[key] = [...value, updateValue].filter((item) => item !== null && item !== undefined && item !== "");
117
+ }
118
+ }
119
+ else if (typeof value === "object" && !Array.isArray(value)) {
120
+ // If the value is an object, we need to merge it
121
+ if (typeof update[key] === "object" && !Array.isArray(update[key])) {
122
+ result[key] = this.mergeObjects(value, update[key]);
123
+ }
124
+ }
125
+ else {
126
+ // Finally, the source value is defined, and not an array, so we don't care about the update value
127
+ continue;
128
+ }
129
+ }
130
+ // Because the objects should technically always be validated FIRST, we can assume the update keys are also defined on the source object
131
+ for (const [key, value] of Object.entries(update)) {
132
+ if (value === undefined || value === null || value === "") {
133
+ continue;
134
+ }
135
+ else if (!Object.hasOwn(source, key)) {
136
+ result[key] = value;
137
+ }
138
+ else if (typeof source[key] === "object" &&
139
+ typeof value === "object" &&
140
+ !Array.isArray(source[key]) &&
141
+ !Array.isArray(value)) {
142
+ result[key] = this.mergeObjects(source[key], value);
143
+ }
144
+ else if (Array.isArray(source[key]) && Array.isArray(value)) {
145
+ result[key] = [...new Set([...source[key], ...value])].filter((item) => item !== null && item !== undefined && item !== "");
146
+ }
147
+ else if (source[key] === undefined ||
148
+ source[key] === null ||
149
+ source[key] === "") {
150
+ result[key] = value;
151
+ }
152
+ }
153
+ return result;
154
+ }
155
+ // Method to load data from a file specified in the import definition
156
+ loadData(importDef) {
157
+ // Simply join appwriteFolderPath with the importDef.filePath
158
+ const filePath = path.resolve(this.appwriteFolderPath, importDef.filePath);
159
+ MessageFormatter.info(`Loading data from: ${filePath}`, { prefix: "Data" });
160
+ if (!fs.existsSync(filePath)) {
161
+ MessageFormatter.error(`File not found: ${filePath}`, undefined, { prefix: "Data" });
162
+ return [];
163
+ }
164
+ // Read the file and parse the JSON data
165
+ const rawData = fs.readFileSync(filePath, "utf8");
166
+ const parsedData = importDef.basePath
167
+ ? JSON.parse(rawData)[importDef.basePath]
168
+ : JSON.parse(rawData);
169
+ MessageFormatter.success(`Loaded ${parsedData?.length || 0} items from ${filePath}`, { prefix: "Data" });
170
+ return parsedData;
171
+ }
172
+ // Helper method to check if a new ID already exists in the old-to-new ID map
173
+ checkMapValuesForId(newId, collectionName) {
174
+ const oldIdMap = this.oldIdToNewIdPerCollectionMap.get(collectionName);
175
+ for (const [key, value] of oldIdMap?.entries() || []) {
176
+ if (value === newId) {
177
+ return key;
178
+ }
179
+ }
180
+ return false;
181
+ }
182
+ // Method to generate a unique ID that doesn't conflict with existing IDs
183
+ getTrueUniqueId(collectionName) {
184
+ let newId = ID.unique();
185
+ let condition = this.checkMapValuesForId(newId, collectionName) ||
186
+ this.userExistsMap.has(newId) ||
187
+ this.userIdSet.has(newId) ||
188
+ this.importMap
189
+ .get(this.getCollectionKey("users"))
190
+ ?.data.some((user) => user.finalData.docId === newId || user.finalData.userId === newId);
191
+ while (condition) {
192
+ newId = ID.unique();
193
+ condition =
194
+ this.checkMapValuesForId(newId, collectionName) ||
195
+ this.userExistsMap.has(newId) ||
196
+ this.userIdSet.has(newId) ||
197
+ this.importMap
198
+ .get(this.getCollectionKey("users"))
199
+ ?.data.some((user) => user.finalData.docId === newId || user.finalData.userId === newId);
200
+ }
201
+ return newId;
202
+ }
203
+ // Method to create a context object for data transformation
204
+ createContext(db, collection, item, docId) {
205
+ return {
206
+ ...item, // Spread the item data for easy access to its properties
207
+ dbId: db.$id,
208
+ dbName: db.name,
209
+ collId: collection.$id,
210
+ collName: collection.name,
211
+ docId: docId,
212
+ createdDoc: {}, // Initially null, to be updated when the document is created
213
+ };
214
+ }
215
+ /**
216
+ * Transforms the given item based on the provided attribute mappings.
217
+ * This method applies conversion rules to the item's attributes as defined in the attribute mappings.
218
+ *
219
+ * @param item - The item to be transformed.
220
+ * @param attributeMappings - The mappings that define how each attribute should be transformed.
221
+ * @returns The transformed item.
222
+ */
223
+ transformData(item, attributeMappings) {
224
+ // Convert the item using the attribute mappings provided
225
+ const convertedItem = convertObjectByAttributeMappings(item, attributeMappings);
226
+ // Run additional converter functions on the converted item, if any
227
+ return this.importDataActions.runConverterFunctions(convertedItem, attributeMappings);
228
+ }
229
+ async setupMaps(dbId, specificCollections) {
230
+ // Initialize the users collection in the import map
231
+ this.importMap.set(this.getCollectionKey("users"), {
232
+ data: [],
233
+ });
234
+ for (const db of this.config.databases) {
235
+ if (db.$id !== dbId) {
236
+ continue;
237
+ }
238
+ if (!this.config.collections) {
239
+ continue;
240
+ }
241
+ for (let index = 0; index < this.config.collections.length; index++) {
242
+ const collectionConfig = this.config.collections[index];
243
+ let collection = CollectionCreateSchema.parse(collectionConfig);
244
+ // Skip collections not in the specific list if one was provided
245
+ if (specificCollections && specificCollections.length > 0 &&
246
+ !specificCollections.includes(collection.name)) {
247
+ continue;
248
+ }
249
+ // Check if the collection exists in the database
250
+ const collectionExists = await checkForCollection(this.database, db.$id, collection);
251
+ if (!collectionExists) {
252
+ logger.error(`No collection found for ${collection.name}`);
253
+ continue;
254
+ }
255
+ else if (!collection.name) {
256
+ logger.error(`Collection ${collection.name} has no name`);
257
+ continue;
258
+ }
259
+ // Update the collection ID with the existing one
260
+ collectionConfig.$id = collectionExists.$id;
261
+ collection.$id = collectionExists.$id;
262
+ this.config.collections[index] = collectionConfig;
263
+ // Find or create an import operation for the collection (non-fatal)
264
+ try {
265
+ const adapter = await this.getAdapter();
266
+ const collectionImportOperation = await findOrCreateOperation(adapter, dbId, "importData", collection.$id);
267
+ this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
268
+ }
269
+ catch (error) {
270
+ MessageFormatter.warning(`Operations tracking unavailable for ${collection.name}, import will proceed without it`, { prefix: "Import" });
271
+ }
272
+ // Initialize the collection in the import map
273
+ this.importMap.set(this.getCollectionKey(collection.name), {
274
+ collection: collection,
275
+ data: [],
276
+ });
277
+ }
278
+ }
279
+ }
280
+ async getAllUsers() {
281
+ const users = new UsersController(this.config, this.database);
282
+ const allUsers = await users.getAllUsers();
283
+ // Iterate over the users and setup our maps ahead of time for email and phone
284
+ for (const user of allUsers) {
285
+ if (user.email) {
286
+ this.emailToUserIdMap.set(user.email.toLowerCase(), user.$id);
287
+ }
288
+ if (user.phone) {
289
+ this.phoneToUserIdMap.set(user.phone, user.$id);
290
+ }
291
+ this.userExistsMap.set(user.$id, true);
292
+ this.userIdSet.add(user.$id);
293
+ let importData = this.importMap.get(this.getCollectionKey("users"));
294
+ if (!importData) {
295
+ importData = {
296
+ data: [],
297
+ };
298
+ }
299
+ importData.data.push({
300
+ finalData: {
301
+ ...user,
302
+ email: user.email?.toLowerCase(),
303
+ userId: user.$id,
304
+ docId: user.$id,
305
+ },
306
+ context: {
307
+ ...user,
308
+ email: user.email?.toLowerCase(),
309
+ userId: user.$id,
310
+ docId: user.$id,
311
+ },
312
+ rawData: user,
313
+ });
314
+ this.importMap.set(this.getCollectionKey("users"), importData);
315
+ }
316
+ return allUsers;
317
+ }
318
+ // Main method to start the data loading process for a given database ID
319
+ async start(dbId, specificCollections) {
320
+ MessageFormatter.divider();
321
+ MessageFormatter.info(`Starting data setup for database: ${dbId}`, { prefix: "Data" });
322
+ MessageFormatter.divider();
323
+ // Only fetch users if we're importing users or no specific collections specified
324
+ const needsUsers = !specificCollections || specificCollections.length === 0 ||
325
+ specificCollections.some(c => this.getCollectionKey(c) === this.getCollectionKey(this.config.usersCollectionName));
326
+ if (needsUsers) {
327
+ const allUsers = await this.getAllUsers();
328
+ MessageFormatter.info(`Fetched ${allUsers.length} users`, { prefix: "Data" });
329
+ }
330
+ // Iterate over the configured databases to find the matching one
331
+ for (const db of this.config.databases) {
332
+ if (db.$id !== dbId) {
333
+ continue;
334
+ }
335
+ if (!this.config.collections) {
336
+ continue;
337
+ }
338
+ // Iterate over the configured collections to process each
339
+ for (const collectionConfig of this.config.collections) {
340
+ const collection = collectionConfig;
341
+ // Skip collections not in the specific list
342
+ if (specificCollections && specificCollections.length > 0 &&
343
+ !specificCollections.includes(collection.name)) {
344
+ continue;
345
+ }
346
+ // Determine if this is the users collection
347
+ let isUsersCollection = this.getCollectionKey(this.config.usersCollectionName) ===
348
+ this.getCollectionKey(collection.name);
349
+ const collectionDefs = collection.importDefs;
350
+ if (!collectionDefs || !collectionDefs.length) {
351
+ continue;
352
+ }
353
+ // Process create and update definitions for the collection
354
+ const createDefs = collection.importDefs.filter((def) => def.type === "create" || !def.type);
355
+ const updateDefs = collection.importDefs.filter((def) => def.type === "update");
356
+ for (const createDef of createDefs) {
357
+ if (!isUsersCollection || !createDef.createUsers) {
358
+ await this.prepareCreateData(db, collection, createDef);
359
+ }
360
+ else {
361
+ // Special handling for users collection if needed
362
+ await this.prepareUserCollectionCreateData(db, collection, createDef);
363
+ }
364
+ }
365
+ for (const updateDef of updateDefs) {
366
+ if (!this.importMap.has(this.getCollectionKey(collection.name))) {
367
+ logger.error(`No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`);
368
+ continue;
369
+ }
370
+ // Prepare the update data for the collection
371
+ this.prepareUpdateData(db, collection, updateDef);
372
+ }
373
+ }
374
+ MessageFormatter.info("Running update references", { prefix: "Data" });
375
+ // this.dealWithMergedUsers();
376
+ this.updateOldReferencesForNew();
377
+ MessageFormatter.success("Done running update references", { prefix: "Data" });
378
+ }
379
+ // for (const collection of this.config.collections) {
380
+ // this.resolveDataItemRelationships(collection);
381
+ // }
382
+ MessageFormatter.divider();
383
+ MessageFormatter.success(`Data setup for database: ${dbId} completed`, { prefix: "Data" });
384
+ MessageFormatter.divider();
385
+ if (this.shouldWriteFile) {
386
+ this.writeMapsToJsonFile();
387
+ }
388
+ }
389
+ /**
390
+ * Deals with merged users by iterating through all collections in the configuration.
391
+ * We have merged users if there are duplicate emails or phones in the import data.
392
+ * This function will iterate through all collections that are the same name as the
393
+ * users collection and pull out their primaryKeyField's. It will then loop through
394
+ * each collection and find any documents that have a
395
+ *
396
+ * @return {void} This function does not return anything.
397
+ */
398
+ // dealWithMergedUsers() {
399
+ // const usersCollectionKey = this.getCollectionKey(
400
+ // this.config.usersCollectionName
401
+ // );
402
+ // const usersCollectionData = this.importMap.get(usersCollectionKey);
403
+ // if (!this.config.collections) {
404
+ // console.log("No collections found in configuration.");
405
+ // return;
406
+ // }
407
+ // let needsUpdate = false;
408
+ // let numUpdates = 0;
409
+ // for (const collectionConfig of this.config.collections) {
410
+ // const collectionKey = this.getCollectionKey(collectionConfig.name);
411
+ // const collectionData = this.importMap.get(collectionKey);
412
+ // const collectionImportDefs = collectionConfig.importDefs;
413
+ // const collectionIdMappings = collectionImportDefs
414
+ // .map((importDef) => importDef.idMappings)
415
+ // .flat()
416
+ // .filter((idMapping) => idMapping !== undefined && idMapping !== null);
417
+ // if (!collectionData || !collectionData.data) continue;
418
+ // for (const dataItem of collectionData.data) {
419
+ // for (const idMapping of collectionIdMappings) {
420
+ // // We know it's the users collection here
421
+ // if (this.getCollectionKey(idMapping.targetCollection) === usersCollectionKey) {
422
+ // const targetFieldKey = idMapping.targetFieldToMatch || idMapping.targetField;
423
+ // if (targetFieldKey === )
424
+ // const targetValue = dataItem.finalData[targetFieldKey];
425
+ // const targetCollectionData = this.importMap.get(this.getCollectionKey(idMapping.targetCollection));
426
+ // if (!targetCollectionData || !targetCollectionData.data) continue;
427
+ // const foundData = targetCollectionData.data.filter(({ context }) => {
428
+ // const targetValue = context[targetFieldKey];
429
+ // const isMatch = `${targetValue}` === `${valueToMatch}`;
430
+ // return isMatch && targetValue !== undefined && targetValue !== null;
431
+ // });
432
+ // }
433
+ // }
434
+ // }
435
+ // }
436
+ // }
437
+ /**
438
+ * Gets the value to match for a given key in the final data or context.
439
+ * @param finalData - The final data object.
440
+ * @param context - The context object.
441
+ * @param key - The key to get the value for.
442
+ * @returns The value to match for from finalData or Context
443
+ */
444
+ getValueFromData(finalData, context, key) {
445
+ if (context[key] !== undefined &&
446
+ context[key] !== null &&
447
+ context[key] !== "") {
448
+ return context[key];
449
+ }
450
+ return finalData[key];
451
+ }
452
+ updateOldReferencesForNew() {
453
+ if (!this.config.collections) {
454
+ return;
455
+ }
456
+ for (const collectionConfig of this.config.collections) {
457
+ const collectionKey = this.getCollectionKey(collectionConfig.name);
458
+ const collectionData = this.importMap.get(collectionKey);
459
+ if (!collectionData || !collectionData.data)
460
+ continue;
461
+ MessageFormatter.processing(`Updating references for collection: ${collectionConfig.name}`, { prefix: "Data" });
462
+ let needsUpdate = false;
463
+ // Iterate over each data item in the current collection
464
+ for (let i = 0; i < collectionData.data.length; i++) {
465
+ if (collectionConfig.importDefs) {
466
+ for (const importDef of collectionConfig.importDefs) {
467
+ if (importDef.idMappings) {
468
+ for (const idMapping of importDef.idMappings) {
469
+ const targetCollectionKey = this.getCollectionKey(idMapping.targetCollection);
470
+ const fieldToSetKey = idMapping.fieldToSet || idMapping.sourceField;
471
+ const targetFieldKey = idMapping.targetFieldToMatch || idMapping.targetField;
472
+ const sourceValue = this.getValueFromData(collectionData.data[i].finalData, collectionData.data[i].context, idMapping.sourceField);
473
+ // Skip if value to match is missing or empty
474
+ if (!sourceValue ||
475
+ isEmpty(sourceValue) ||
476
+ sourceValue === null)
477
+ continue;
478
+ const isFieldToSetArray = collectionConfig.attributes.find((attribute) => attribute.key === fieldToSetKey)?.array;
479
+ const targetCollectionData = this.importMap.get(targetCollectionKey);
480
+ if (!targetCollectionData || !targetCollectionData.data)
481
+ continue;
482
+ // Handle cases where sourceValue is an array
483
+ const sourceValues = Array.isArray(sourceValue)
484
+ ? sourceValue.map((sourceValue) => `${sourceValue}`)
485
+ : [`${sourceValue}`];
486
+ let newData = [];
487
+ for (const valueToMatch of sourceValues) {
488
+ // Find matching data in the target collection
489
+ const foundData = targetCollectionData.data.filter(({ context, finalData }) => {
490
+ const targetValue = this.getValueFromData(finalData, context, targetFieldKey);
491
+ const isMatch = `${targetValue}` === `${valueToMatch}`;
492
+ // Ensure the targetValue is defined and not null
493
+ return (isMatch &&
494
+ targetValue !== undefined &&
495
+ targetValue !== null);
496
+ });
497
+ if (foundData.length) {
498
+ newData.push(...foundData.map((data) => {
499
+ const newValue = this.getValueFromData(data.finalData, data.context, idMapping.targetField);
500
+ return newValue;
501
+ }));
502
+ }
503
+ else {
504
+ logger.info(`No data found for collection: ${targetCollectionKey} with value: ${valueToMatch} for field: ${fieldToSetKey} -- idMapping: ${JSON.stringify(idMapping, null, 2)}`);
505
+ }
506
+ continue;
507
+ }
508
+ const getCurrentDataFiltered = (currentData) => {
509
+ if (Array.isArray(currentData.finalData[fieldToSetKey])) {
510
+ return currentData.finalData[fieldToSetKey].filter((data) => !sourceValues.includes(`${data}`));
511
+ }
512
+ return currentData.finalData[fieldToSetKey];
513
+ };
514
+ // Get the current data to be updated
515
+ const currentDataFiltered = getCurrentDataFiltered(collectionData.data[i]);
516
+ if (newData.length) {
517
+ needsUpdate = true;
518
+ // Handle cases where current data is an array
519
+ if (isFieldToSetArray) {
520
+ if (!currentDataFiltered) {
521
+ // Set new data if current data is undefined
522
+ collectionData.data[i].finalData[fieldToSetKey] =
523
+ Array.isArray(newData) ? newData : [newData];
524
+ }
525
+ else {
526
+ if (Array.isArray(currentDataFiltered)) {
527
+ // Convert current data to array and merge if new data is non-empty array
528
+ collectionData.data[i].finalData[fieldToSetKey] = [
529
+ ...new Set([...currentDataFiltered, ...newData].filter((value) => value !== null &&
530
+ value !== undefined &&
531
+ value !== "")),
532
+ ];
533
+ }
534
+ else {
535
+ // Merge arrays if new data is non-empty array and filter for uniqueness
536
+ collectionData.data[i].finalData[fieldToSetKey] = [
537
+ ...new Set([
538
+ ...(Array.isArray(currentDataFiltered)
539
+ ? currentDataFiltered
540
+ : [currentDataFiltered]),
541
+ ...newData,
542
+ ].filter((value) => value !== null &&
543
+ value !== undefined &&
544
+ value !== "" &&
545
+ !sourceValues.includes(`${value}`))),
546
+ ];
547
+ }
548
+ }
549
+ }
550
+ else {
551
+ if (!currentDataFiltered) {
552
+ // Set new data if current data is undefined
553
+ collectionData.data[i].finalData[fieldToSetKey] =
554
+ Array.isArray(newData) ? newData[0] : newData;
555
+ }
556
+ else if (Array.isArray(newData) && newData.length > 0) {
557
+ // Convert current data to array and merge if new data is non-empty array, then filter for uniqueness
558
+ // and take the first value, because it's an array and the attribute is not an array
559
+ collectionData.data[i].finalData[fieldToSetKey] = [
560
+ ...new Set([currentDataFiltered, ...newData].filter((value) => value !== null &&
561
+ value !== undefined &&
562
+ value !== "" &&
563
+ !sourceValues.includes(`${value}`))),
564
+ ].slice(0, 1)[0];
565
+ }
566
+ else if (!Array.isArray(newData) &&
567
+ newData !== undefined) {
568
+ // Simply update the field if new data is not an array and defined
569
+ collectionData.data[i].finalData[fieldToSetKey] = newData;
570
+ }
571
+ }
572
+ }
573
+ }
574
+ }
575
+ }
576
+ }
577
+ }
578
+ // Update the import map if any changes were made
579
+ if (needsUpdate) {
580
+ this.importMap.set(collectionKey, collectionData);
581
+ }
582
+ }
583
+ }
584
+ writeMapsToJsonFile() {
585
+ const outputDir = path.resolve(process.cwd(), "zlogs");
586
+ // Ensure the logs directory exists
587
+ if (!fs.existsSync(outputDir)) {
588
+ fs.mkdirSync(outputDir);
589
+ }
590
+ // Helper function to write data to a file
591
+ const writeToFile = (fileName, data) => {
592
+ const outputFile = path.join(outputDir, fileName);
593
+ fs.writeFile(outputFile, JSON.stringify(data, null, 2), "utf8", (err) => {
594
+ if (err) {
595
+ MessageFormatter.error(`Error writing data to ${fileName}`, err instanceof Error ? err : new Error(String(err)), { prefix: "Data" });
596
+ return;
597
+ }
598
+ MessageFormatter.success(`Data successfully written to ${fileName}`, { prefix: "Data" });
599
+ });
600
+ };
601
+ // Convert Maps to arrays of entries for serialization
602
+ const oldIdToNewIdPerCollectionMap = Array.from(this.oldIdToNewIdPerCollectionMap.entries()).map(([key, value]) => {
603
+ return {
604
+ collection: key,
605
+ data: Array.from(value.entries()),
606
+ };
607
+ });
608
+ const mergedUserMap = Array.from(this.mergedUserMap.entries());
609
+ // Write each part to a separate file
610
+ writeToFile("oldIdToNewIdPerCollectionMap.json", oldIdToNewIdPerCollectionMap);
611
+ writeToFile("mergedUserMap.json", mergedUserMap);
612
+ // Write each collection's data to a separate file
613
+ this.importMap.forEach((value, key) => {
614
+ const data = {
615
+ collection: key,
616
+ data: value.data.map((item) => {
617
+ return {
618
+ finalData: item.finalData,
619
+ context: item.context,
620
+ };
621
+ }),
622
+ };
623
+ writeToFile(`${key}.json`, data);
624
+ });
625
+ }
626
+ /**
627
+ * Prepares user data by checking for duplicates based on email or phone, adding to a duplicate map if found,
628
+ * and then returning the transformed item without user-specific keys.
629
+ *
630
+ * @param item - The raw item to be processed.
631
+ * @param attributeMappings - The attribute mappings for the item.
632
+ * @returns The transformed item with user-specific keys removed.
633
+ */
634
+ prepareUserData(item, attributeMappings, primaryKeyField, newId) {
635
+ if (this.userIdSet.has(newId) ||
636
+ this.userExistsMap.has(newId) ||
637
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
638
+ Array.from(this.phoneToUserIdMap.values()).includes(newId)) {
639
+ newId = this.getTrueUniqueId(this.getCollectionKey("users"));
640
+ }
641
+ let transformedItem = this.transformData(item, attributeMappings);
642
+ let userData = AuthUserCreateSchema.safeParse(transformedItem);
643
+ if (userData.data?.email) {
644
+ userData.data.email = userData.data.email.toLowerCase();
645
+ }
646
+ if (!userData.success || !(userData.data.email || userData.data.phone)) {
647
+ logger.error(`Invalid user data: ${JSON.stringify(userData.error?.issues, undefined, 2)} or missing email/phone`);
648
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
649
+ userKeys.forEach((key) => {
650
+ if (transformedItem.hasOwnProperty(key)) {
651
+ delete transformedItem[key];
652
+ }
653
+ });
654
+ return {
655
+ transformedItem,
656
+ existingId: undefined,
657
+ userData: {
658
+ rawData: item,
659
+ finalData: transformedItem,
660
+ },
661
+ };
662
+ }
663
+ const email = userData.data.email?.toLowerCase();
664
+ const phone = userData.data.phone;
665
+ let existingId;
666
+ // Check for duplicate email and phone
667
+ if (email && this.emailToUserIdMap.has(email)) {
668
+ existingId = this.emailToUserIdMap.get(email);
669
+ if (phone && !this.phoneToUserIdMap.has(phone)) {
670
+ this.phoneToUserIdMap.set(phone, newId);
671
+ }
672
+ }
673
+ else if (phone && this.phoneToUserIdMap.has(phone)) {
674
+ existingId = this.phoneToUserIdMap.get(phone);
675
+ if (email && !this.emailToUserIdMap.has(email)) {
676
+ this.emailToUserIdMap.set(email, newId);
677
+ }
678
+ }
679
+ else {
680
+ if (email)
681
+ this.emailToUserIdMap.set(email, newId);
682
+ if (phone)
683
+ this.phoneToUserIdMap.set(phone, newId);
684
+ }
685
+ if (existingId) {
686
+ userData.data.userId = existingId;
687
+ const mergedUsers = this.mergedUserMap.get(existingId) || [];
688
+ mergedUsers.push(`${item[primaryKeyField]}`);
689
+ this.mergedUserMap.set(existingId, mergedUsers);
690
+ const userFound = this.importMap
691
+ .get(this.getCollectionKey("users"))
692
+ ?.data.find((userDataExisting) => {
693
+ let userIdToMatch;
694
+ if (userDataExisting?.finalData?.userId) {
695
+ userIdToMatch = userDataExisting?.finalData?.userId;
696
+ }
697
+ else if (userDataExisting?.finalData?.docId) {
698
+ userIdToMatch = userDataExisting?.finalData?.docId;
699
+ }
700
+ else if (userDataExisting?.context?.userId) {
701
+ userIdToMatch = userDataExisting.context.userId;
702
+ }
703
+ else if (userDataExisting?.context?.docId) {
704
+ userIdToMatch = userDataExisting.context.docId;
705
+ }
706
+ return userIdToMatch === existingId;
707
+ });
708
+ if (userFound) {
709
+ userFound.finalData.userId = existingId;
710
+ userFound.finalData.docId = existingId;
711
+ this.userIdSet.add(existingId);
712
+ transformedItem = {
713
+ ...transformedItem,
714
+ userId: existingId,
715
+ docId: existingId,
716
+ };
717
+ }
718
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
719
+ userKeys.forEach((key) => {
720
+ if (transformedItem.hasOwnProperty(key)) {
721
+ delete transformedItem[key];
722
+ }
723
+ });
724
+ return {
725
+ transformedItem,
726
+ existingId,
727
+ userData: {
728
+ rawData: userFound?.rawData,
729
+ finalData: userFound?.finalData,
730
+ },
731
+ };
732
+ }
733
+ else {
734
+ existingId = newId;
735
+ userData.data.userId = existingId;
736
+ }
737
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
738
+ userKeys.forEach((key) => {
739
+ if (transformedItem.hasOwnProperty(key)) {
740
+ delete transformedItem[key];
741
+ }
742
+ });
743
+ const usersMap = this.importMap.get(this.getCollectionKey("users"));
744
+ const userDataToAdd = {
745
+ rawData: item,
746
+ finalData: userData.data,
747
+ context: {},
748
+ };
749
+ this.importMap.set(this.getCollectionKey("users"), {
750
+ data: [...(usersMap?.data || []), userDataToAdd],
751
+ });
752
+ this.userIdSet.add(existingId);
753
+ return {
754
+ transformedItem,
755
+ existingId,
756
+ userData: userDataToAdd,
757
+ };
758
+ }
759
+ /**
760
+ * Prepares the data for creating user collection documents.
761
+ * This involves loading the data, transforming it according to the import definition,
762
+ * and handling the creation of new unique IDs for each item.
763
+ *
764
+ * @param db - The database configuration.
765
+ * @param collection - The collection configuration.
766
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
767
+ */
768
+ async prepareUserCollectionCreateData(db, collection, importDef) {
769
+ // Load the raw data based on the import definition
770
+ const rawData = this.loadData(importDef);
771
+ let operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
772
+ // Initialize a new map for old ID to new ID mappings
773
+ const oldIdToNewIdMap = new Map();
774
+ // Retrieve or initialize the collection-specific old ID to new ID map
775
+ const collectionOldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name)) ||
776
+ this.oldIdToNewIdPerCollectionMap
777
+ .set(this.getCollectionKey(collection.name), oldIdToNewIdMap)
778
+ .get(this.getCollectionKey(collection.name));
779
+ const adapter = await this.getAdapter();
780
+ if (!operationId) {
781
+ const collectionImportOperation = await findOrCreateOperation(adapter, db.$id, "importData", collection.$id);
782
+ // Store the operation ID in the map
783
+ this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
784
+ operationId = collectionImportOperation.$id;
785
+ }
786
+ if (operationId) {
787
+ await updateOperation(adapter, db.$id, operationId, {
788
+ status: "in_progress",
789
+ total: rawData.length,
790
+ });
791
+ }
792
+ // Retrieve the current user data and the current collection data from the import map
793
+ const currentUserData = this.importMap.get(this.getCollectionKey("users"));
794
+ const currentData = this.importMap.get(this.getCollectionKey(collection.name));
795
+ // Log errors if the necessary data is not found in the import map
796
+ if (!currentUserData) {
797
+ logger.error(`No data found for collection ${"users"} for createDef but it says it's supposed to have one...`);
798
+ return;
799
+ }
800
+ else if (!currentData) {
801
+ logger.error(`No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`);
802
+ return;
803
+ }
804
+ // Iterate through each item in the raw data
805
+ for (const item of rawData) {
806
+ // Prepare user data, check for duplicates, and remove user-specific keys
807
+ let { transformedItem, existingId, userData } = this.prepareUserData(item, importDef.attributeMappings, importDef.primaryKeyField, this.getTrueUniqueId(this.getCollectionKey("users")));
808
+ logger.info(`In create user -- transformedItem: ${JSON.stringify(transformedItem, null, 2)}`);
809
+ // Generate a new unique ID for the item or use existing ID
810
+ if (!existingId && !userData.finalData?.userId) {
811
+ // No existing user ID, generate a new unique ID
812
+ existingId = this.getTrueUniqueId(this.getCollectionKey(collection.name));
813
+ transformedItem = {
814
+ ...transformedItem,
815
+ userId: existingId,
816
+ docId: existingId,
817
+ };
818
+ }
819
+ else if (!existingId && userData.finalData?.userId) {
820
+ // Existing user ID, use it as the new ID
821
+ existingId = userData.finalData.userId;
822
+ transformedItem = {
823
+ ...transformedItem,
824
+ userId: existingId,
825
+ docId: existingId,
826
+ };
827
+ }
828
+ // Create a context object for the item, including the new ID
829
+ let context = this.createContext(db, collection, item, existingId);
830
+ // Merge the transformed data into the context
831
+ context = { ...context, ...transformedItem, ...userData.finalData };
832
+ // If a primary key field is defined, handle the ID mapping and check for duplicates
833
+ if (importDef.primaryKeyField) {
834
+ const oldId = item[importDef.primaryKeyField];
835
+ // Check if the oldId already exists to handle potential duplicates
836
+ if (this.oldIdToNewIdPerCollectionMap
837
+ .get(this.getCollectionKey(collection.name))
838
+ ?.has(`${oldId}`)) {
839
+ // Found a duplicate oldId, now decide how to merge or handle these duplicates
840
+ for (const data of currentData.data) {
841
+ if (data.finalData.docId === oldId ||
842
+ data.finalData.userId === oldId ||
843
+ data.context.docId === oldId ||
844
+ data.context.userId === oldId) {
845
+ transformedItem = this.mergeObjects(data.finalData, transformedItem);
846
+ }
847
+ }
848
+ }
849
+ else {
850
+ // No duplicate found, simply map the oldId to the new itemId
851
+ collectionOldIdToNewIdMap?.set(`${oldId}`, `${existingId}`);
852
+ }
853
+ }
854
+ // Handle merging for currentUserData
855
+ for (let i = 0; i < currentUserData.data.length; i++) {
856
+ const currentUserDataItem = currentUserData.data[i];
857
+ const samePhones = currentUserDataItem.finalData.phone &&
858
+ transformedItem.phone &&
859
+ currentUserDataItem.finalData.phone === transformedItem.phone;
860
+ const sameEmails = currentUserDataItem.finalData.email &&
861
+ transformedItem.email &&
862
+ currentUserDataItem.finalData.email === transformedItem.email;
863
+ if ((currentUserDataItem.finalData.docId === existingId ||
864
+ currentUserDataItem.finalData.userId === existingId) &&
865
+ (samePhones || sameEmails) &&
866
+ currentUserDataItem.finalData &&
867
+ userData.finalData) {
868
+ const userDataMerged = this.mergeObjects(currentUserData.data[i].finalData, userData.finalData);
869
+ currentUserData.data[i].finalData = userDataMerged;
870
+ this.importMap.set(this.getCollectionKey("users"), currentUserData);
871
+ }
872
+ }
873
+ // Update the attribute mappings with any actions that need to be performed post-import
874
+ // We added the basePath to get the folder from the filePath
875
+ const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedItem);
876
+ // Update the import definition with the new attribute mappings
877
+ const newImportDef = {
878
+ ...importDef,
879
+ attributeMappings: mappingsWithActions,
880
+ };
881
+ const updatedData = this.importMap.get(this.getCollectionKey(collection.name));
882
+ let foundData = false;
883
+ for (let i = 0; i < updatedData.data.length; i++) {
884
+ if (updatedData.data[i].finalData.docId === existingId ||
885
+ updatedData.data[i].finalData.userId === existingId ||
886
+ updatedData.data[i].context.docId === existingId ||
887
+ updatedData.data[i].context.userId === existingId) {
888
+ updatedData.data[i].finalData = this.mergeObjects(updatedData.data[i].finalData, transformedItem);
889
+ updatedData.data[i].context = this.mergeObjects(updatedData.data[i].context, context);
890
+ const mergedImportDef = {
891
+ ...updatedData.data[i].importDef,
892
+ idMappings: [
893
+ ...(updatedData.data[i].importDef?.idMappings || []),
894
+ ...(newImportDef.idMappings || []),
895
+ ],
896
+ attributeMappings: [
897
+ ...(updatedData.data[i].importDef?.attributeMappings || []),
898
+ ...(newImportDef.attributeMappings || []),
899
+ ],
900
+ };
901
+ updatedData.data[i].importDef = mergedImportDef;
902
+ this.importMap.set(this.getCollectionKey(collection.name), updatedData);
903
+ this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
904
+ foundData = true;
905
+ }
906
+ }
907
+ if (!foundData) {
908
+ // Add new data to the associated collection
909
+ updatedData.data.push({
910
+ rawData: item,
911
+ context: context,
912
+ importDef: newImportDef,
913
+ finalData: transformedItem,
914
+ });
915
+ this.importMap.set(this.getCollectionKey(collection.name), updatedData);
916
+ this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
917
+ }
918
+ }
919
+ }
920
+ /**
921
+ * Prepares the data for creating documents in a collection.
922
+ * This involves loading the data, transforming it, and handling ID mappings.
923
+ *
924
+ * @param db - The database configuration.
925
+ * @param collection - The collection configuration.
926
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
927
+ */
928
+ async prepareCreateData(db, collection, importDef) {
929
+ // Load the raw data based on the import definition
930
+ const rawData = this.loadData(importDef);
931
+ let operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
932
+ const adapter = await this.getAdapter();
933
+ if (!operationId) {
934
+ const collectionImportOperation = await findOrCreateOperation(adapter, db.$id, "importData", collection.$id);
935
+ // Store the operation ID in the map
936
+ this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
937
+ operationId = collectionImportOperation.$id;
938
+ }
939
+ if (operationId) {
940
+ await updateOperation(adapter, db.$id, operationId, {
941
+ status: "in_progress",
942
+ total: rawData.length,
943
+ });
944
+ }
945
+ // Initialize a new map for old ID to new ID mappings
946
+ const oldIdToNewIdMapNew = new Map();
947
+ // Retrieve or initialize the collection-specific old ID to new ID map
948
+ const collectionOldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name)) ||
949
+ this.oldIdToNewIdPerCollectionMap
950
+ .set(this.getCollectionKey(collection.name), oldIdToNewIdMapNew)
951
+ .get(this.getCollectionKey(collection.name));
952
+ const isRegions = collection.name.toLowerCase() === "regions";
953
+ // Iterate through each item in the raw data
954
+ for (const item of rawData) {
955
+ // Generate a new unique ID for the item
956
+ const itemIdNew = this.getTrueUniqueId(this.getCollectionKey(collection.name));
957
+ if (isRegions) {
958
+ logger.info(`Creating region: ${JSON.stringify(item, null, 2)}`);
959
+ }
960
+ // Retrieve the current collection data from the import map
961
+ const currentData = this.importMap.get(this.getCollectionKey(collection.name));
962
+ // Create a context object for the item, including the new ID
963
+ let context = this.createContext(db, collection, item, itemIdNew);
964
+ // Transform the item data based on the attribute mappings
965
+ let transformedData = this.transformData(item, importDef.attributeMappings);
966
+ // If a primary key field is defined, handle the ID mapping and check for duplicates
967
+ if (importDef.primaryKeyField) {
968
+ const oldId = item[importDef.primaryKeyField];
969
+ if (collectionOldIdToNewIdMap?.has(`${oldId}`)) {
970
+ logger.error(`Collection ${collection.name} has multiple documents with the same primary key ${oldId}`);
971
+ continue;
972
+ }
973
+ collectionOldIdToNewIdMap?.set(`${oldId}`, `${itemIdNew}`);
974
+ }
975
+ // Merge the transformed data into the context
976
+ context = { ...context, ...transformedData };
977
+ // Validate the item before proceeding
978
+ const isValid = this.importDataActions.validateItem(transformedData, importDef.attributeMappings, context);
979
+ if (!isValid) {
980
+ continue;
981
+ }
982
+ // Update the attribute mappings with any actions that need to be performed post-import
983
+ // We added the basePath to get the folder from the filePath
984
+ const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedData);
985
+ // Update the import definition with the new attribute mappings
986
+ const newImportDef = {
987
+ ...importDef,
988
+ attributeMappings: mappingsWithActions,
989
+ };
990
+ // If the current collection data exists, add the item with its context and final data
991
+ if (currentData && currentData.data) {
992
+ currentData.data.push({
993
+ rawData: item,
994
+ context: context,
995
+ importDef: newImportDef,
996
+ finalData: transformedData,
997
+ });
998
+ this.importMap.set(this.getCollectionKey(collection.name), currentData);
999
+ this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
1000
+ }
1001
+ else {
1002
+ logger.error(`No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`);
1003
+ continue;
1004
+ }
1005
+ }
1006
+ }
1007
+ /**
1008
+ * Prepares the data for updating documents within a collection.
1009
+ * This method loads the raw data based on the import definition, transforms it according to the attribute mappings,
1010
+ * finds the new ID for each item based on the primary key or update mapping, and then validates the transformed data.
1011
+ * If the data is valid, it updates the import definition with any post-import actions and adds the item to the current collection data.
1012
+ *
1013
+ * @param db - The database configuration.
1014
+ * @param collection - The collection configuration.
1015
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
1016
+ */
1017
+ async prepareUpdateData(db, collection, importDef) {
1018
+ const currentData = this.importMap.get(this.getCollectionKey(collection.name));
1019
+ const oldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name));
1020
+ if (!(currentData?.data && currentData?.data.length > 0) &&
1021
+ !oldIdToNewIdMap) {
1022
+ logger.error(`No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`);
1023
+ return;
1024
+ }
1025
+ const rawData = this.loadData(importDef);
1026
+ const operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
1027
+ if (!operationId) {
1028
+ throw new Error(`No import operation found for collection ${collection.name}`);
1029
+ }
1030
+ for (const item of rawData) {
1031
+ let transformedData = this.transformData(item, importDef.attributeMappings);
1032
+ let newId;
1033
+ let oldId;
1034
+ let itemDataToUpdate;
1035
+ // Try to find itemDataToUpdate using updateMapping
1036
+ if (importDef.updateMapping) {
1037
+ oldId =
1038
+ item[importDef.updateMapping.originalIdField] ||
1039
+ transformedData[importDef.updateMapping.originalIdField];
1040
+ if (oldId) {
1041
+ itemDataToUpdate = currentData?.data.find(({ context, finalData }) => {
1042
+ const targetField = importDef.updateMapping.targetField ??
1043
+ importDef.updateMapping.originalIdField;
1044
+ return (`${context[targetField]}` === `${oldId}` ||
1045
+ `${finalData[targetField]}` === `${oldId}`);
1046
+ });
1047
+ if (itemDataToUpdate) {
1048
+ newId = itemDataToUpdate.context.docId;
1049
+ }
1050
+ }
1051
+ }
1052
+ // If updateMapping is not defined or did not find the item, use primaryKeyField
1053
+ if (!itemDataToUpdate && importDef.primaryKeyField) {
1054
+ oldId =
1055
+ item[importDef.primaryKeyField] ||
1056
+ transformedData[importDef.primaryKeyField];
1057
+ if (oldId && oldId.length > 0) {
1058
+ newId = oldIdToNewIdMap?.get(`${oldId}`);
1059
+ if (!newId &&
1060
+ this.getCollectionKey(this.config.usersCollectionName) ===
1061
+ this.getCollectionKey(collection.name)) {
1062
+ for (const [key, value] of this.mergedUserMap.entries()) {
1063
+ if (value.includes(`${oldId}`)) {
1064
+ newId = key;
1065
+ break;
1066
+ }
1067
+ }
1068
+ }
1069
+ }
1070
+ if (oldId && !itemDataToUpdate) {
1071
+ itemDataToUpdate = currentData?.data.find((data) => `${data.context[importDef.primaryKeyField]}` === `${oldId}`);
1072
+ }
1073
+ }
1074
+ if (!oldId) {
1075
+ logger.error(`No old ID found (to update another document with) in prepareUpdateData for ${collection.name}, ${JSON.stringify(item, null, 2)}`);
1076
+ continue;
1077
+ }
1078
+ if (!newId && !itemDataToUpdate) {
1079
+ logger.error(`No new id && no data found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but it says it's supposed to have one...`);
1080
+ continue;
1081
+ }
1082
+ else if (itemDataToUpdate) {
1083
+ newId =
1084
+ itemDataToUpdate.finalData.docId || itemDataToUpdate.context.docId;
1085
+ if (!newId) {
1086
+ logger.error(`No new id found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but has itemDataToUpdate ${JSON.stringify(itemDataToUpdate, null, 2)} but it says it's supposed to have one...`);
1087
+ continue;
1088
+ }
1089
+ }
1090
+ if (!itemDataToUpdate || !newId) {
1091
+ logger.error(`No data or ID (docId) found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but it says it's supposed to have one...`);
1092
+ continue;
1093
+ }
1094
+ transformedData = this.mergeObjects(itemDataToUpdate.finalData, transformedData);
1095
+ // Create a context object for the item, including the new ID and transformed data
1096
+ let context = itemDataToUpdate.context;
1097
+ context = this.mergeObjects(context, transformedData);
1098
+ // Validate the item before proceeding
1099
+ const isValid = this.importDataActions.validateItem(item, importDef.attributeMappings, context);
1100
+ if (!isValid) {
1101
+ logger.info(`Skipping item: ${JSON.stringify(item, null, 2)} because it's invalid`);
1102
+ continue;
1103
+ }
1104
+ // Update the attribute mappings with any actions that need to be performed post-import
1105
+ // We added the basePath to get the folder from the filePath
1106
+ const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedData);
1107
+ // Update the import definition with the new attribute mappings
1108
+ const newImportDef = {
1109
+ ...importDef,
1110
+ attributeMappings: mappingsWithActions,
1111
+ };
1112
+ if (itemDataToUpdate) {
1113
+ itemDataToUpdate.finalData = this.mergeObjects(itemDataToUpdate.finalData, transformedData);
1114
+ itemDataToUpdate.context = context;
1115
+ // Fix: Ensure we properly merge the attribute mappings and their actions
1116
+ const mergedAttributeMappings = newImportDef.attributeMappings.map((newMapping) => {
1117
+ const existingMapping = itemDataToUpdate.importDef?.attributeMappings.find((m) => m.targetKey === newMapping.targetKey);
1118
+ return {
1119
+ ...newMapping,
1120
+ postImportActions: [
1121
+ ...(existingMapping?.postImportActions || []),
1122
+ ...(newMapping.postImportActions || []),
1123
+ ],
1124
+ };
1125
+ });
1126
+ itemDataToUpdate.importDef = {
1127
+ ...newImportDef,
1128
+ attributeMappings: mergedAttributeMappings,
1129
+ };
1130
+ // Debug logging
1131
+ if (mergedAttributeMappings.some((m) => m.postImportActions?.length > 0)) {
1132
+ logger.info(`Post-import actions for ${collection.name}: ${JSON.stringify(mergedAttributeMappings
1133
+ .filter((m) => m.postImportActions?.length > 0)
1134
+ .map((m) => ({
1135
+ targetKey: m.targetKey,
1136
+ actions: m.postImportActions,
1137
+ })), null, 2)}`);
1138
+ }
1139
+ }
1140
+ else {
1141
+ currentData.data.push({
1142
+ rawData: item,
1143
+ context: context,
1144
+ importDef: newImportDef,
1145
+ finalData: transformedData,
1146
+ });
1147
+ }
1148
+ // Since we're modifying currentData in place, we ensure no duplicates are added
1149
+ this.importMap.set(this.getCollectionKey(collection.name), currentData);
1150
+ }
1151
+ }
1152
+ updateReferencesBasedOnAttributeMappings() {
1153
+ if (!this.config.collections) {
1154
+ return;
1155
+ }
1156
+ this.config.collections.forEach((collectionConfig) => {
1157
+ const collectionName = collectionConfig.name;
1158
+ const collectionData = this.importMap.get(this.getCollectionKey(collectionName));
1159
+ if (!collectionData) {
1160
+ logger.error(`No data found for collection ${collectionName}`);
1161
+ return;
1162
+ }
1163
+ collectionData.data.forEach((dataItem) => {
1164
+ collectionConfig.importDefs.forEach((importDef) => {
1165
+ if (!importDef.idMappings)
1166
+ return; // Skip collections without idMappings
1167
+ importDef.idMappings.forEach((mapping) => {
1168
+ if (mapping && mapping.targetField) {
1169
+ const idsToUpdate = Array.isArray(dataItem[mapping.targetField])
1170
+ ? dataItem[mapping.targetField]
1171
+ : [dataItem[mapping.targetField]];
1172
+ const updatedIds = idsToUpdate.map((id) => this.getMergedId(id, mapping.targetCollection));
1173
+ // Update the dataItem with the new IDs
1174
+ dataItem[mapping.targetField] =
1175
+ Array.isArray(dataItem[mapping.targetField])
1176
+ ? updatedIds
1177
+ : updatedIds[0];
1178
+ }
1179
+ });
1180
+ });
1181
+ });
1182
+ });
1183
+ }
1184
+ getMergedId(oldId, relatedCollectionName) {
1185
+ // Retrieve the old to new ID map for the related collection
1186
+ const oldToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(relatedCollectionName));
1187
+ // If there's a mapping for the old ID, return the new ID
1188
+ if (oldToNewIdMap && oldToNewIdMap.has(`${oldId}`)) {
1189
+ return oldToNewIdMap.get(`${oldId}`); // The non-null assertion (!) is used because we checked if the map has the key
1190
+ }
1191
+ // If no mapping is found, return the old ID as a fallback
1192
+ return oldId;
1193
+ }
1194
+ /**
1195
+ * Generates attribute mappings with post-import actions based on the provided attribute mappings.
1196
+ * This method checks each mapping for a fileData attribute and adds a post-import action to create a file
1197
+ * and update the field with the file's ID if necessary.
1198
+ *
1199
+ * @param attributeMappings - The attribute mappings from the import definition.
1200
+ * @param context - The context object containing information about the database, collection, and document.
1201
+ * @param item - The item being imported, used for resolving template paths in fileData mappings.
1202
+ * @returns The attribute mappings updated with any necessary post-import actions.
1203
+ */
1204
+ getAttributeMappingsWithActions(attributeMappings, context, item) {
1205
+ // Iterate over each attribute mapping to check for fileData attributes
1206
+ return attributeMappings.map((mapping) => {
1207
+ if (mapping.fileData) {
1208
+ // Resolve the file path using the provided template, context, and item
1209
+ let mappingFilePath = this.importDataActions.resolveTemplate(mapping.fileData.path, context, item);
1210
+ // Ensure the file path is absolute if it doesn't start with "http"
1211
+ if (!mappingFilePath.toLowerCase().startsWith("http")) {
1212
+ // First try the direct path
1213
+ let fullPath = path.resolve(this.appwriteFolderPath, mappingFilePath);
1214
+ // If file doesn't exist, search in subdirectories
1215
+ if (!fs.existsSync(fullPath)) {
1216
+ const findFileInDir = (dir) => {
1217
+ const files = fs.readdirSync(dir);
1218
+ for (const file of files) {
1219
+ const filePath = path.join(dir, file);
1220
+ const stat = fs.statSync(filePath);
1221
+ if (stat.isDirectory()) {
1222
+ // Recursively search subdirectories
1223
+ const found = findFileInDir(filePath);
1224
+ if (found)
1225
+ return found;
1226
+ }
1227
+ else if (file === path.basename(mappingFilePath)) {
1228
+ return filePath;
1229
+ }
1230
+ }
1231
+ return null;
1232
+ };
1233
+ const foundPath = findFileInDir(this.appwriteFolderPath);
1234
+ if (foundPath) {
1235
+ mappingFilePath = foundPath;
1236
+ }
1237
+ else {
1238
+ logger.warn(`File not found in any subdirectory: ${mappingFilePath}`);
1239
+ // Keep the original resolved path as fallback
1240
+ mappingFilePath = fullPath;
1241
+ }
1242
+ }
1243
+ else {
1244
+ mappingFilePath = fullPath;
1245
+ }
1246
+ }
1247
+ // Define the after-import action to create a file and update the field
1248
+ const afterImportAction = {
1249
+ action: "createFileAndUpdateField",
1250
+ params: [
1251
+ "{dbId}",
1252
+ "{collId}",
1253
+ "{docId}",
1254
+ mapping.targetKey,
1255
+ `${this.config.documentBucketId}_${context.dbName
1256
+ .toLowerCase()
1257
+ .replace(" ", "")}`, // Assuming 'images' is your bucket ID
1258
+ mappingFilePath,
1259
+ mapping.fileData.name,
1260
+ ],
1261
+ };
1262
+ // Add the after-import action to the mapping's postImportActions array
1263
+ const postImportActions = mapping.postImportActions
1264
+ ? [...mapping.postImportActions, afterImportAction]
1265
+ : [afterImportAction];
1266
+ return { ...mapping, postImportActions };
1267
+ }
1268
+ // Return the mapping unchanged if no fileData attribute is found
1269
+ return mapping;
1270
+ });
1271
+ }
1272
+ }