appwrite-utils-cli 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -1
  2. package/dist/adapters/index.js +10 -0
  3. package/dist/backups/operations/bucketBackup.d.ts +19 -0
  4. package/dist/backups/operations/bucketBackup.js +197 -0
  5. package/dist/backups/operations/collectionBackup.d.ts +30 -0
  6. package/dist/backups/operations/collectionBackup.js +201 -0
  7. package/dist/backups/operations/comprehensiveBackup.d.ts +25 -0
  8. package/dist/backups/operations/comprehensiveBackup.js +238 -0
  9. package/dist/backups/schemas/bucketManifest.d.ts +93 -0
  10. package/dist/backups/schemas/bucketManifest.js +33 -0
  11. package/dist/backups/schemas/comprehensiveManifest.d.ts +108 -0
  12. package/dist/backups/schemas/comprehensiveManifest.js +32 -0
  13. package/dist/backups/tracking/centralizedTracking.d.ts +34 -0
  14. package/dist/backups/tracking/centralizedTracking.js +274 -0
  15. package/dist/cli/commands/configCommands.d.ts +8 -0
  16. package/dist/cli/commands/configCommands.js +210 -0
  17. package/dist/cli/commands/databaseCommands.d.ts +14 -0
  18. package/dist/cli/commands/databaseCommands.js +696 -0
  19. package/dist/cli/commands/functionCommands.d.ts +7 -0
  20. package/dist/cli/commands/functionCommands.js +330 -0
  21. package/dist/cli/commands/importFileCommands.d.ts +7 -0
  22. package/dist/cli/commands/importFileCommands.js +674 -0
  23. package/dist/cli/commands/schemaCommands.d.ts +7 -0
  24. package/dist/cli/commands/schemaCommands.js +169 -0
  25. package/dist/cli/commands/storageCommands.d.ts +5 -0
  26. package/dist/cli/commands/storageCommands.js +142 -0
  27. package/dist/cli/commands/transferCommands.d.ts +5 -0
  28. package/dist/cli/commands/transferCommands.js +382 -0
  29. package/dist/collections/columns.d.ts +13 -0
  30. package/dist/collections/columns.js +1339 -0
  31. package/dist/collections/indexes.d.ts +12 -0
  32. package/dist/collections/indexes.js +215 -0
  33. package/dist/collections/methods.d.ts +19 -0
  34. package/dist/collections/methods.js +605 -0
  35. package/dist/collections/tableOperations.d.ts +87 -0
  36. package/dist/collections/tableOperations.js +466 -0
  37. package/dist/collections/transferOperations.d.ts +8 -0
  38. package/dist/collections/transferOperations.js +411 -0
  39. package/dist/collections/wipeOperations.d.ts +17 -0
  40. package/dist/collections/wipeOperations.js +306 -0
  41. package/dist/databases/methods.d.ts +6 -0
  42. package/dist/databases/methods.js +35 -0
  43. package/dist/databases/setup.d.ts +5 -0
  44. package/dist/databases/setup.js +45 -0
  45. package/dist/examples/yamlTerminologyExample.d.ts +42 -0
  46. package/dist/examples/yamlTerminologyExample.js +272 -0
  47. package/dist/functions/deployments.d.ts +4 -0
  48. package/dist/functions/deployments.js +146 -0
  49. package/dist/functions/fnConfigDiscovery.d.ts +3 -0
  50. package/dist/functions/fnConfigDiscovery.js +108 -0
  51. package/dist/functions/methods.d.ts +16 -0
  52. package/dist/functions/methods.js +174 -0
  53. package/dist/init.d.ts +2 -0
  54. package/dist/init.js +57 -0
  55. package/dist/interactiveCLI.d.ts +36 -0
  56. package/dist/interactiveCLI.js +952 -0
  57. package/dist/main.d.ts +2 -0
  58. package/dist/main.js +1125 -0
  59. package/dist/migrations/afterImportActions.d.ts +17 -0
  60. package/dist/migrations/afterImportActions.js +305 -0
  61. package/dist/migrations/appwriteToX.d.ts +211 -0
  62. package/dist/migrations/appwriteToX.js +493 -0
  63. package/dist/migrations/comprehensiveTransfer.d.ts +147 -0
  64. package/dist/migrations/comprehensiveTransfer.js +1315 -0
  65. package/dist/migrations/dataLoader.d.ts +755 -0
  66. package/dist/migrations/dataLoader.js +1272 -0
  67. package/dist/migrations/importController.d.ts +25 -0
  68. package/dist/migrations/importController.js +283 -0
  69. package/dist/migrations/importDataActions.d.ts +50 -0
  70. package/dist/migrations/importDataActions.js +230 -0
  71. package/dist/migrations/relationships.d.ts +29 -0
  72. package/dist/migrations/relationships.js +203 -0
  73. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  74. package/dist/migrations/services/DataTransformationService.js +158 -0
  75. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  76. package/dist/migrations/services/FileHandlerService.js +236 -0
  77. package/dist/migrations/services/ImportOrchestrator.d.ts +99 -0
  78. package/dist/migrations/services/ImportOrchestrator.js +493 -0
  79. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  80. package/dist/migrations/services/RateLimitManager.js +279 -0
  81. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  82. package/dist/migrations/services/RelationshipResolver.js +332 -0
  83. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  84. package/dist/migrations/services/UserMappingService.js +277 -0
  85. package/dist/migrations/services/ValidationService.d.ts +74 -0
  86. package/dist/migrations/services/ValidationService.js +260 -0
  87. package/dist/migrations/transfer.d.ts +30 -0
  88. package/dist/migrations/transfer.js +661 -0
  89. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +131 -0
  90. package/dist/migrations/yaml/YamlImportConfigLoader.js +383 -0
  91. package/dist/migrations/yaml/YamlImportIntegration.d.ts +93 -0
  92. package/dist/migrations/yaml/YamlImportIntegration.js +341 -0
  93. package/dist/migrations/yaml/generateImportSchemas.d.ts +30 -0
  94. package/dist/migrations/yaml/generateImportSchemas.js +1327 -0
  95. package/dist/schemas/authUser.d.ts +24 -0
  96. package/dist/schemas/authUser.js +17 -0
  97. package/dist/setup.d.ts +2 -0
  98. package/{src/setup.ts → dist/setup.js} +0 -3
  99. package/dist/setupCommands.d.ts +58 -0
  100. package/dist/setupCommands.js +489 -0
  101. package/dist/setupController.d.ts +9 -0
  102. package/dist/setupController.js +34 -0
  103. package/dist/shared/backupMetadataSchema.d.ts +94 -0
  104. package/dist/shared/backupMetadataSchema.js +38 -0
  105. package/dist/shared/backupTracking.d.ts +18 -0
  106. package/dist/shared/backupTracking.js +176 -0
  107. package/dist/shared/confirmationDialogs.d.ts +75 -0
  108. package/dist/shared/confirmationDialogs.js +236 -0
  109. package/dist/shared/migrationHelpers.d.ts +61 -0
  110. package/dist/shared/migrationHelpers.js +145 -0
  111. package/{src/shared/operationLogger.ts → dist/shared/operationLogger.d.ts} +1 -11
  112. package/dist/shared/operationLogger.js +12 -0
  113. package/dist/shared/operationQueue.d.ts +40 -0
  114. package/dist/shared/operationQueue.js +310 -0
  115. package/dist/shared/operationsTable.d.ts +26 -0
  116. package/dist/shared/operationsTable.js +287 -0
  117. package/dist/shared/operationsTableSchema.d.ts +48 -0
  118. package/dist/shared/operationsTableSchema.js +35 -0
  119. package/dist/shared/progressManager.d.ts +62 -0
  120. package/dist/shared/progressManager.js +215 -0
  121. package/dist/shared/relationshipExtractor.d.ts +56 -0
  122. package/dist/shared/relationshipExtractor.js +138 -0
  123. package/dist/shared/selectionDialogs.d.ts +220 -0
  124. package/dist/shared/selectionDialogs.js +588 -0
  125. package/dist/storage/backupCompression.d.ts +20 -0
  126. package/dist/storage/backupCompression.js +67 -0
  127. package/dist/storage/methods.d.ts +44 -0
  128. package/dist/storage/methods.js +475 -0
  129. package/dist/storage/schemas.d.ts +842 -0
  130. package/dist/storage/schemas.js +175 -0
  131. package/dist/tables/indexManager.d.ts +65 -0
  132. package/dist/tables/indexManager.js +294 -0
  133. package/{src/types.ts → dist/types.d.ts} +1 -6
  134. package/dist/types.js +3 -0
  135. package/dist/users/methods.d.ts +16 -0
  136. package/dist/users/methods.js +276 -0
  137. package/dist/utils/configMigration.d.ts +1 -0
  138. package/dist/utils/configMigration.js +261 -0
  139. package/dist/utils/index.js +2 -0
  140. package/dist/utils/loadConfigs.d.ts +50 -0
  141. package/dist/utils/loadConfigs.js +357 -0
  142. package/dist/utils/setupFiles.d.ts +4 -0
  143. package/dist/utils/setupFiles.js +1190 -0
  144. package/dist/utilsController.d.ts +114 -0
  145. package/dist/utilsController.js +898 -0
  146. package/package.json +6 -3
  147. package/CHANGELOG.md +0 -35
  148. package/CONFIG_TODO.md +0 -1189
  149. package/SELECTION_DIALOGS.md +0 -146
  150. package/SERVICE_IMPLEMENTATION_REPORT.md +0 -462
  151. package/scripts/copy-templates.ts +0 -23
  152. package/src/backups/operations/bucketBackup.ts +0 -277
  153. package/src/backups/operations/collectionBackup.ts +0 -310
  154. package/src/backups/operations/comprehensiveBackup.ts +0 -342
  155. package/src/backups/schemas/bucketManifest.ts +0 -78
  156. package/src/backups/schemas/comprehensiveManifest.ts +0 -76
  157. package/src/backups/tracking/centralizedTracking.ts +0 -352
  158. package/src/cli/commands/configCommands.ts +0 -265
  159. package/src/cli/commands/databaseCommands.ts +0 -931
  160. package/src/cli/commands/functionCommands.ts +0 -419
  161. package/src/cli/commands/importFileCommands.ts +0 -815
  162. package/src/cli/commands/schemaCommands.ts +0 -200
  163. package/src/cli/commands/storageCommands.ts +0 -151
  164. package/src/cli/commands/transferCommands.ts +0 -454
  165. package/src/collections/attributes.ts.backup +0 -1555
  166. package/src/collections/columns.ts +0 -2025
  167. package/src/collections/indexes.ts +0 -350
  168. package/src/collections/methods.ts +0 -714
  169. package/src/collections/tableOperations.ts +0 -542
  170. package/src/collections/transferOperations.ts +0 -589
  171. package/src/collections/wipeOperations.ts +0 -449
  172. package/src/databases/methods.ts +0 -49
  173. package/src/databases/setup.ts +0 -77
  174. package/src/examples/yamlTerminologyExample.ts +0 -346
  175. package/src/functions/deployments.ts +0 -221
  176. package/src/functions/fnConfigDiscovery.ts +0 -103
  177. package/src/functions/methods.ts +0 -284
  178. package/src/init.ts +0 -62
  179. package/src/interactiveCLI.ts +0 -1201
  180. package/src/main.ts +0 -1517
  181. package/src/migrations/afterImportActions.ts +0 -579
  182. package/src/migrations/appwriteToX.ts +0 -668
  183. package/src/migrations/comprehensiveTransfer.ts +0 -2285
  184. package/src/migrations/dataLoader.ts +0 -1729
  185. package/src/migrations/importController.ts +0 -440
  186. package/src/migrations/importDataActions.ts +0 -315
  187. package/src/migrations/relationships.ts +0 -333
  188. package/src/migrations/services/DataTransformationService.ts +0 -196
  189. package/src/migrations/services/FileHandlerService.ts +0 -311
  190. package/src/migrations/services/ImportOrchestrator.ts +0 -675
  191. package/src/migrations/services/RateLimitManager.ts +0 -363
  192. package/src/migrations/services/RelationshipResolver.ts +0 -461
  193. package/src/migrations/services/UserMappingService.ts +0 -345
  194. package/src/migrations/services/ValidationService.ts +0 -349
  195. package/src/migrations/transfer.ts +0 -1113
  196. package/src/migrations/yaml/YamlImportConfigLoader.ts +0 -439
  197. package/src/migrations/yaml/YamlImportIntegration.ts +0 -446
  198. package/src/migrations/yaml/generateImportSchemas.ts +0 -1354
  199. package/src/schemas/authUser.ts +0 -23
  200. package/src/setupCommands.ts +0 -602
  201. package/src/setupController.ts +0 -43
  202. package/src/shared/backupMetadataSchema.ts +0 -93
  203. package/src/shared/backupTracking.ts +0 -211
  204. package/src/shared/confirmationDialogs.ts +0 -327
  205. package/src/shared/migrationHelpers.ts +0 -232
  206. package/src/shared/operationQueue.ts +0 -376
  207. package/src/shared/operationsTable.ts +0 -338
  208. package/src/shared/operationsTableSchema.ts +0 -60
  209. package/src/shared/progressManager.ts +0 -278
  210. package/src/shared/relationshipExtractor.ts +0 -214
  211. package/src/shared/selectionDialogs.ts +0 -802
  212. package/src/storage/backupCompression.ts +0 -88
  213. package/src/storage/methods.ts +0 -711
  214. package/src/storage/schemas.ts +0 -205
  215. package/src/tables/indexManager.ts +0 -409
  216. package/src/types/node-appwrite-tablesdb.d.ts +0 -44
  217. package/src/users/methods.ts +0 -358
  218. package/src/utils/configMigration.ts +0 -348
  219. package/src/utils/loadConfigs.ts +0 -457
  220. package/src/utils/setupFiles.ts +0 -1236
  221. package/src/utilsController.ts +0 -1263
  222. package/tests/README.md +0 -497
  223. package/tests/adapters/AdapterFactory.test.ts +0 -277
  224. package/tests/integration/syncOperations.test.ts +0 -463
  225. package/tests/jest.config.js +0 -25
  226. package/tests/migration/configMigration.test.ts +0 -546
  227. package/tests/setup.ts +0 -62
  228. package/tests/testUtils.ts +0 -340
  229. package/tests/utils/loadConfigs.test.ts +0 -350
  230. package/tests/validation/configValidation.test.ts +0 -412
  231. package/tsconfig.json +0 -44
  232. /package/{src → dist}/functions/templates/count-docs-in-collection/README.md +0 -0
  233. /package/{src → dist}/functions/templates/count-docs-in-collection/src/main.ts +0 -0
  234. /package/{src → dist}/functions/templates/count-docs-in-collection/src/request.ts +0 -0
  235. /package/{src → dist}/functions/templates/hono-typescript/README.md +0 -0
  236. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/request.ts +0 -0
  237. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/response.ts +0 -0
  238. /package/{src → dist}/functions/templates/hono-typescript/src/app.ts +0 -0
  239. /package/{src → dist}/functions/templates/hono-typescript/src/context.ts +0 -0
  240. /package/{src → dist}/functions/templates/hono-typescript/src/main.ts +0 -0
  241. /package/{src → dist}/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -0
  242. /package/{src → dist}/functions/templates/typescript-node/README.md +0 -0
  243. /package/{src → dist}/functions/templates/typescript-node/src/context.ts +0 -0
  244. /package/{src → dist}/functions/templates/typescript-node/src/main.ts +0 -0
  245. /package/{src → dist}/functions/templates/uv/README.md +0 -0
  246. /package/{src → dist}/functions/templates/uv/pyproject.toml +0 -0
  247. /package/{src → dist}/functions/templates/uv/src/__init__.py +0 -0
  248. /package/{src → dist}/functions/templates/uv/src/context.py +0 -0
  249. /package/{src → dist}/functions/templates/uv/src/main.py +0 -0
  250. /package/{src/utils/index.ts → dist/utils/index.d.ts} +0 -0
@@ -1,1729 +0,0 @@
1
- import type { ImportDataActions } from "./importDataActions.js";
2
- import {
3
- AttributeMappingsSchema,
4
- CollectionCreateSchema,
5
- importDefSchema,
6
- type AppwriteConfig,
7
- type AttributeMappings,
8
- type CollectionCreate,
9
- type ConfigDatabase,
10
- type IdMapping,
11
- type ImportDef,
12
- type ImportDefs,
13
- type RelationshipAttribute,
14
- } from "appwrite-utils";
15
- import path from "path";
16
- import fs from "fs";
17
- import { convertObjectByAttributeMappings } from "appwrite-utils-helpers";
18
- import { z } from "zod";
19
- import { checkForCollection } from "../collections/methods.js";
20
- import { ID, Users, type Databases } from "node-appwrite";
21
- import { logger, AdapterFactory, type DatabaseAdapter, MessageFormatter } from "appwrite-utils-helpers";
22
- import { findOrCreateOperation, updateOperation } from "../shared/migrationHelpers.js";
23
- import { AuthUserCreateSchema } from "../schemas/authUser.js";
24
- import { UsersController } from "../users/methods.js";
25
- import { isEmpty } from "es-toolkit/compat";
26
-
27
- // Define a schema for the structure of collection import data using Zod for validation
28
- export const CollectionImportDataSchema = z.object({
29
- // Optional collection creation schema
30
- collection: CollectionCreateSchema.optional(),
31
- // Array of data objects each containing rawData, finalData, context, and an import definition
32
- data: z.array(
33
- z.object({
34
- rawData: z.any(), // The initial raw data
35
- finalData: z.any(), // The transformed data ready for import
36
- context: z.any(), // Additional context for the data transformation
37
- importDef: importDefSchema.optional(), // The import definition schema
38
- })
39
- ),
40
- });
41
-
42
- // Infer the TypeScript type from the Zod schema
43
- export type CollectionImportData = z.infer<typeof CollectionImportDataSchema>;
44
-
45
- // DataLoader class to handle the loading of data into collections
46
- export class DataLoader {
47
- // Private member variables to hold configuration and state
48
- private appwriteFolderPath: string;
49
- private importDataActions: ImportDataActions;
50
- private database: Databases;
51
- private usersController: UsersController;
52
- private config: AppwriteConfig;
53
- // Map to hold the import data for each collection by name
54
- importMap = new Map<string, CollectionImportData>();
55
- // Map to track old to new ID mappings for each collection, if applicable
56
- private oldIdToNewIdPerCollectionMap = new Map<string, Map<string, string>>();
57
- // Map to hold the import operation ID for each collection
58
- collectionImportOperations = new Map<string, string>();
59
- // Map to hold the merged user map for relationship resolution
60
- // Will hold an array of the old user ID's that are mapped to the same new user ID
61
- // For example, if there are two users with the same email, they will both be mapped to the same new user ID
62
- // Prevents duplicate users with the other two maps below it and allows me to keep the old ID's
63
- private mergedUserMap = new Map<string, string[]>();
64
- // Maps to hold email and phone to user ID mappings for unique-ness in User Accounts
65
- private emailToUserIdMap = new Map<string, string>();
66
- private phoneToUserIdMap = new Map<string, string>();
67
- private userIdSet = new Set<string>();
68
- userExistsMap = new Map<string, boolean>();
69
- private shouldWriteFile = false;
70
- private _adapter: DatabaseAdapter | null = null;
71
-
72
- private async getAdapter(): Promise<DatabaseAdapter> {
73
- if (!this._adapter) {
74
- const { adapter } = await AdapterFactory.createFromConfig(this.config);
75
- this._adapter = adapter;
76
- }
77
- return this._adapter;
78
- }
79
-
80
- // Constructor to initialize the DataLoader with necessary configurations
81
- constructor(
82
- appwriteFolderPath: string,
83
- importDataActions: ImportDataActions,
84
- database: Databases,
85
- config: AppwriteConfig,
86
- shouldWriteFile?: boolean
87
- ) {
88
- this.appwriteFolderPath = appwriteFolderPath;
89
- this.importDataActions = importDataActions;
90
- this.database = database;
91
- this.usersController = new UsersController(config, database);
92
- this.config = config;
93
- this.shouldWriteFile = shouldWriteFile || false;
94
- }
95
-
96
- // Helper method to generate a consistent key for collections
97
- getCollectionKey(name: string) {
98
- return name.toLowerCase().replace(" ", "");
99
- }
100
-
101
- /**
102
- * Merges two objects by updating the source object with the target object's values.
103
- * It iterates through the target object's keys and updates the source object if:
104
- * - The source object has the key.
105
- * - The target object's value for that key is not null, undefined, or an empty string.
106
- * - If the target object has an array value, it concatenates the values and removes duplicates.
107
- *
108
- * @param source - The source object to be updated.
109
- * @param target - The target object with values to update the source object.
110
- * @returns The updated source object.
111
- */
112
- mergeObjects(source: any, update: any): any {
113
- // Create a new object to hold the merged result
114
- const result = { ...source };
115
-
116
- // Loop through the keys of the object we care about
117
- for (const [key, value] of Object.entries(source)) {
118
- // Check if the key exists in the target object
119
- if (!Object.hasOwn(update, key)) {
120
- // If the key doesn't exist, we can just skip it like bad cheese
121
- continue;
122
- }
123
- if (update[key] === value) {
124
- continue;
125
- }
126
- // If the value ain't here, we can just do whatever man
127
- if (value === undefined || value === null || value === "") {
128
- // If the update key is defined
129
- if (
130
- update[key] !== undefined &&
131
- update[key] !== null &&
132
- update[key] !== ""
133
- ) {
134
- // might as well use it eh?
135
- result[key] = update[key];
136
- }
137
- // ELSE if the value is an array, because it would then not be === to those things above
138
- } else if (Array.isArray(value)) {
139
- // Get the update value
140
- const updateValue = update[key];
141
- // If the update value is an array, concatenate and remove duplicates
142
- // and poopy data
143
- if (Array.isArray(updateValue)) {
144
- result[key] = [...new Set([...value, ...updateValue])].filter(
145
- (item) => item !== null && item !== undefined && item !== ""
146
- );
147
- } else {
148
- // If the update value is not an array, just use it
149
- result[key] = [...value, updateValue].filter(
150
- (item) => item !== null && item !== undefined && item !== ""
151
- );
152
- }
153
- } else if (typeof value === "object" && !Array.isArray(value)) {
154
- // If the value is an object, we need to merge it
155
- if (typeof update[key] === "object" && !Array.isArray(update[key])) {
156
- result[key] = this.mergeObjects(value, update[key]);
157
- }
158
- } else {
159
- // Finally, the source value is defined, and not an array, so we don't care about the update value
160
- continue;
161
- }
162
- }
163
- // Because the objects should technically always be validated FIRST, we can assume the update keys are also defined on the source object
164
- for (const [key, value] of Object.entries(update)) {
165
- if (value === undefined || value === null || value === "") {
166
- continue;
167
- } else if (!Object.hasOwn(source, key)) {
168
- result[key] = value;
169
- } else if (
170
- typeof source[key] === "object" &&
171
- typeof value === "object" &&
172
- !Array.isArray(source[key]) &&
173
- !Array.isArray(value)
174
- ) {
175
- result[key] = this.mergeObjects(source[key], value);
176
- } else if (Array.isArray(source[key]) && Array.isArray(value)) {
177
- result[key] = [...new Set([...source[key], ...value])].filter(
178
- (item) => item !== null && item !== undefined && item !== ""
179
- );
180
- } else if (
181
- source[key] === undefined ||
182
- source[key] === null ||
183
- source[key] === ""
184
- ) {
185
- result[key] = value;
186
- }
187
- }
188
-
189
- return result;
190
- }
191
-
192
- // Method to load data from a file specified in the import definition
193
- loadData(importDef: ImportDef): any[] {
194
- // Simply join appwriteFolderPath with the importDef.filePath
195
- const filePath = path.resolve(this.appwriteFolderPath, importDef.filePath);
196
- MessageFormatter.info(`Loading data from: ${filePath}`, { prefix: "Data" });
197
- if (!fs.existsSync(filePath)) {
198
- MessageFormatter.error(`File not found: ${filePath}`, undefined, { prefix: "Data" });
199
- return [];
200
- }
201
-
202
- // Read the file and parse the JSON data
203
- const rawData = fs.readFileSync(filePath, "utf8");
204
- const parsedData = importDef.basePath
205
- ? JSON.parse(rawData)[importDef.basePath]
206
- : JSON.parse(rawData);
207
-
208
- MessageFormatter.success(`Loaded ${parsedData?.length || 0} items from ${filePath}`, { prefix: "Data" });
209
- return parsedData;
210
- }
211
-
212
- // Helper method to check if a new ID already exists in the old-to-new ID map
213
- checkMapValuesForId(newId: string, collectionName: string) {
214
- const oldIdMap = this.oldIdToNewIdPerCollectionMap.get(collectionName);
215
- for (const [key, value] of oldIdMap?.entries() || []) {
216
- if (value === newId) {
217
- return key;
218
- }
219
- }
220
- return false;
221
- }
222
-
223
- // Method to generate a unique ID that doesn't conflict with existing IDs
224
- getTrueUniqueId(collectionName: string) {
225
- let newId = ID.unique();
226
- let condition =
227
- this.checkMapValuesForId(newId, collectionName) ||
228
- this.userExistsMap.has(newId) ||
229
- this.userIdSet.has(newId) ||
230
- this.importMap
231
- .get(this.getCollectionKey("users"))
232
- ?.data.some(
233
- (user) =>
234
- user.finalData.docId === newId || user.finalData.userId === newId
235
- );
236
- while (condition) {
237
- newId = ID.unique();
238
- condition =
239
- this.checkMapValuesForId(newId, collectionName) ||
240
- this.userExistsMap.has(newId) ||
241
- this.userIdSet.has(newId) ||
242
- this.importMap
243
- .get(this.getCollectionKey("users"))
244
- ?.data.some(
245
- (user) =>
246
- user.finalData.docId === newId || user.finalData.userId === newId
247
- );
248
- }
249
- return newId;
250
- }
251
-
252
- // Method to create a context object for data transformation
253
- createContext(
254
- db: ConfigDatabase,
255
- collection: CollectionCreate,
256
- item: any,
257
- docId: string
258
- ) {
259
- return {
260
- ...item, // Spread the item data for easy access to its properties
261
- dbId: db.$id,
262
- dbName: db.name,
263
- collId: collection.$id,
264
- collName: collection.name,
265
- docId: docId,
266
- createdDoc: {}, // Initially null, to be updated when the document is created
267
- };
268
- }
269
-
270
- /**
271
- * Transforms the given item based on the provided attribute mappings.
272
- * This method applies conversion rules to the item's attributes as defined in the attribute mappings.
273
- *
274
- * @param item - The item to be transformed.
275
- * @param attributeMappings - The mappings that define how each attribute should be transformed.
276
- * @returns The transformed item.
277
- */
278
- transformData(item: any, attributeMappings: AttributeMappings): any {
279
- // Convert the item using the attribute mappings provided
280
- const convertedItem = convertObjectByAttributeMappings(
281
- item,
282
- attributeMappings
283
- );
284
- // Run additional converter functions on the converted item, if any
285
- return this.importDataActions.runConverterFunctions(
286
- convertedItem,
287
- attributeMappings
288
- );
289
- }
290
-
291
- async setupMaps(dbId: string, specificCollections?: string[]) {
292
- // Initialize the users collection in the import map
293
- this.importMap.set(this.getCollectionKey("users"), {
294
- data: [],
295
- });
296
- for (const db of this.config.databases) {
297
- if (db.$id !== dbId) {
298
- continue;
299
- }
300
- if (!this.config.collections) {
301
- continue;
302
- }
303
- for (let index = 0; index < this.config.collections.length; index++) {
304
- const collectionConfig = this.config.collections[index];
305
- let collection = CollectionCreateSchema.parse(collectionConfig);
306
- // Skip collections not in the specific list if one was provided
307
- if (specificCollections && specificCollections.length > 0 &&
308
- !specificCollections.includes(collection.name)) {
309
- continue;
310
- }
311
- // Check if the collection exists in the database
312
- const collectionExists = await checkForCollection(
313
- this.database,
314
- db.$id,
315
- collection
316
- );
317
- if (!collectionExists) {
318
- logger.error(`No collection found for ${collection.name}`);
319
- continue;
320
- } else if (!collection.name) {
321
- logger.error(`Collection ${collection.name} has no name`);
322
- continue;
323
- }
324
- // Update the collection ID with the existing one
325
- collectionConfig.$id = collectionExists.$id;
326
- collection.$id = collectionExists.$id;
327
- this.config.collections[index] = collectionConfig;
328
- // Find or create an import operation for the collection (non-fatal)
329
- try {
330
- const adapter = await this.getAdapter();
331
- const collectionImportOperation = await findOrCreateOperation(
332
- adapter,
333
- dbId,
334
- "importData",
335
- collection.$id!
336
- );
337
- this.collectionImportOperations.set(
338
- this.getCollectionKey(collection.name),
339
- collectionImportOperation.$id
340
- );
341
- } catch (error) {
342
- MessageFormatter.warning(
343
- `Operations tracking unavailable for ${collection.name}, import will proceed without it`,
344
- { prefix: "Import" }
345
- );
346
- }
347
- // Initialize the collection in the import map
348
- this.importMap.set(this.getCollectionKey(collection.name), {
349
- collection: collection,
350
- data: [],
351
- });
352
- }
353
- }
354
- }
355
-
356
- async getAllUsers() {
357
- const users = new UsersController(this.config, this.database);
358
- const allUsers = await users.getAllUsers();
359
- // Iterate over the users and setup our maps ahead of time for email and phone
360
- for (const user of allUsers) {
361
- if (user.email) {
362
- this.emailToUserIdMap.set(user.email.toLowerCase(), user.$id);
363
- }
364
- if (user.phone) {
365
- this.phoneToUserIdMap.set(user.phone, user.$id);
366
- }
367
- this.userExistsMap.set(user.$id, true);
368
- this.userIdSet.add(user.$id);
369
- let importData = this.importMap.get(this.getCollectionKey("users"));
370
- if (!importData) {
371
- importData = {
372
- data: [],
373
- };
374
- }
375
- importData.data.push({
376
- finalData: {
377
- ...user,
378
- email: user.email?.toLowerCase(),
379
- userId: user.$id,
380
- docId: user.$id,
381
- },
382
- context: {
383
- ...user,
384
- email: user.email?.toLowerCase(),
385
- userId: user.$id,
386
- docId: user.$id,
387
- },
388
- rawData: user,
389
- });
390
- this.importMap.set(this.getCollectionKey("users"), importData);
391
- }
392
- return allUsers;
393
- }
394
-
395
- // Main method to start the data loading process for a given database ID
396
- async start(dbId: string, specificCollections?: string[]) {
397
- MessageFormatter.divider();
398
- MessageFormatter.info(`Starting data setup for database: ${dbId}`, { prefix: "Data" });
399
- MessageFormatter.divider();
400
- // Only fetch users if we're importing users or no specific collections specified
401
- const needsUsers = !specificCollections || specificCollections.length === 0 ||
402
- specificCollections.some(c =>
403
- this.getCollectionKey(c) === this.getCollectionKey(this.config.usersCollectionName)
404
- );
405
- if (needsUsers) {
406
- const allUsers = await this.getAllUsers();
407
- MessageFormatter.info(
408
- `Fetched ${allUsers.length} users`,
409
- { prefix: "Data" }
410
- );
411
- }
412
- // Iterate over the configured databases to find the matching one
413
- for (const db of this.config.databases) {
414
- if (db.$id !== dbId) {
415
- continue;
416
- }
417
- if (!this.config.collections) {
418
- continue;
419
- }
420
- // Iterate over the configured collections to process each
421
- for (const collectionConfig of this.config.collections) {
422
- const collection = collectionConfig;
423
- // Skip collections not in the specific list
424
- if (specificCollections && specificCollections.length > 0 &&
425
- !specificCollections.includes(collection.name)) {
426
- continue;
427
- }
428
- // Determine if this is the users collection
429
- let isUsersCollection =
430
- this.getCollectionKey(this.config.usersCollectionName) ===
431
- this.getCollectionKey(collection.name);
432
- const collectionDefs = collection.importDefs;
433
- if (!collectionDefs || !collectionDefs.length) {
434
- continue;
435
- }
436
- // Process create and update definitions for the collection
437
- const createDefs = collection.importDefs.filter(
438
- (def: ImportDef) => def.type === "create" || !def.type
439
- );
440
- const updateDefs = collection.importDefs.filter(
441
- (def: ImportDef) => def.type === "update"
442
- );
443
- for (const createDef of createDefs) {
444
- if (!isUsersCollection || !createDef.createUsers) {
445
- await this.prepareCreateData(db, collection, createDef);
446
- } else {
447
- // Special handling for users collection if needed
448
- await this.prepareUserCollectionCreateData(
449
- db,
450
- collection,
451
- createDef
452
- );
453
- }
454
- }
455
- for (const updateDef of updateDefs) {
456
- if (!this.importMap.has(this.getCollectionKey(collection.name))) {
457
- logger.error(
458
- `No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`
459
- );
460
- continue;
461
- }
462
- // Prepare the update data for the collection
463
- this.prepareUpdateData(db, collection, updateDef);
464
- }
465
- }
466
- MessageFormatter.info("Running update references", { prefix: "Data" });
467
- // this.dealWithMergedUsers();
468
- this.updateOldReferencesForNew();
469
- MessageFormatter.success("Done running update references", { prefix: "Data" });
470
- }
471
- // for (const collection of this.config.collections) {
472
- // this.resolveDataItemRelationships(collection);
473
- // }
474
- MessageFormatter.divider();
475
- MessageFormatter.success(`Data setup for database: ${dbId} completed`, { prefix: "Data" });
476
- MessageFormatter.divider();
477
- if (this.shouldWriteFile) {
478
- this.writeMapsToJsonFile();
479
- }
480
- }
481
-
482
- /**
483
- * Deals with merged users by iterating through all collections in the configuration.
484
- * We have merged users if there are duplicate emails or phones in the import data.
485
- * This function will iterate through all collections that are the same name as the
486
- * users collection and pull out their primaryKeyField's. It will then loop through
487
- * each collection and find any documents that have a
488
- *
489
- * @return {void} This function does not return anything.
490
- */
491
- // dealWithMergedUsers() {
492
- // const usersCollectionKey = this.getCollectionKey(
493
- // this.config.usersCollectionName
494
- // );
495
- // const usersCollectionData = this.importMap.get(usersCollectionKey);
496
-
497
- // if (!this.config.collections) {
498
- // console.log("No collections found in configuration.");
499
- // return;
500
- // }
501
-
502
- // let needsUpdate = false;
503
- // let numUpdates = 0;
504
-
505
- // for (const collectionConfig of this.config.collections) {
506
- // const collectionKey = this.getCollectionKey(collectionConfig.name);
507
- // const collectionData = this.importMap.get(collectionKey);
508
- // const collectionImportDefs = collectionConfig.importDefs;
509
- // const collectionIdMappings = collectionImportDefs
510
- // .map((importDef) => importDef.idMappings)
511
- // .flat()
512
- // .filter((idMapping) => idMapping !== undefined && idMapping !== null);
513
- // if (!collectionData || !collectionData.data) continue;
514
- // for (const dataItem of collectionData.data) {
515
- // for (const idMapping of collectionIdMappings) {
516
- // // We know it's the users collection here
517
- // if (this.getCollectionKey(idMapping.targetCollection) === usersCollectionKey) {
518
- // const targetFieldKey = idMapping.targetFieldToMatch || idMapping.targetField;
519
- // if (targetFieldKey === )
520
- // const targetValue = dataItem.finalData[targetFieldKey];
521
- // const targetCollectionData = this.importMap.get(this.getCollectionKey(idMapping.targetCollection));
522
- // if (!targetCollectionData || !targetCollectionData.data) continue;
523
- // const foundData = targetCollectionData.data.filter(({ context }) => {
524
- // const targetValue = context[targetFieldKey];
525
- // const isMatch = `${targetValue}` === `${valueToMatch}`;
526
- // return isMatch && targetValue !== undefined && targetValue !== null;
527
- // });
528
- // }
529
- // }
530
- // }
531
- // }
532
- // }
533
-
534
- /**
535
- * Gets the value to match for a given key in the final data or context.
536
- * @param finalData - The final data object.
537
- * @param context - The context object.
538
- * @param key - The key to get the value for.
539
- * @returns The value to match for from finalData or Context
540
- */
541
- getValueFromData(finalData: any, context: any, key: string) {
542
- if (
543
- context[key] !== undefined &&
544
- context[key] !== null &&
545
- context[key] !== ""
546
- ) {
547
- return context[key];
548
- }
549
- return finalData[key];
550
- }
551
-
552
- updateOldReferencesForNew() {
553
- if (!this.config.collections) {
554
- return;
555
- }
556
-
557
- for (const collectionConfig of this.config.collections) {
558
- const collectionKey = this.getCollectionKey(collectionConfig.name);
559
- const collectionData = this.importMap.get(collectionKey);
560
-
561
- if (!collectionData || !collectionData.data) continue;
562
-
563
- MessageFormatter.processing(
564
- `Updating references for collection: ${collectionConfig.name}`,
565
- { prefix: "Data" }
566
- );
567
-
568
- let needsUpdate = false;
569
-
570
- // Iterate over each data item in the current collection
571
- for (let i = 0; i < collectionData.data.length; i++) {
572
- if (collectionConfig.importDefs) {
573
- for (const importDef of collectionConfig.importDefs) {
574
- if (importDef.idMappings) {
575
- for (const idMapping of importDef.idMappings) {
576
- const targetCollectionKey = this.getCollectionKey(
577
- idMapping.targetCollection
578
- );
579
- const fieldToSetKey =
580
- idMapping.fieldToSet || idMapping.sourceField;
581
- const targetFieldKey =
582
- idMapping.targetFieldToMatch || idMapping.targetField;
583
- const sourceValue = this.getValueFromData(
584
- collectionData.data[i].finalData,
585
- collectionData.data[i].context,
586
- idMapping.sourceField
587
- );
588
-
589
- // Skip if value to match is missing or empty
590
- if (
591
- !sourceValue ||
592
- isEmpty(sourceValue) ||
593
- sourceValue === null
594
- )
595
- continue;
596
-
597
- const isFieldToSetArray = collectionConfig.attributes.find(
598
- (attribute) => attribute.key === fieldToSetKey
599
- )?.array;
600
-
601
- const targetCollectionData =
602
- this.importMap.get(targetCollectionKey);
603
- if (!targetCollectionData || !targetCollectionData.data)
604
- continue;
605
-
606
- // Handle cases where sourceValue is an array
607
- const sourceValues = Array.isArray(sourceValue)
608
- ? sourceValue.map((sourceValue) => `${sourceValue}`)
609
- : [`${sourceValue}`];
610
- let newData = [];
611
-
612
- for (const valueToMatch of sourceValues) {
613
- // Find matching data in the target collection
614
- const foundData = targetCollectionData.data.filter(
615
- ({ context, finalData }) => {
616
- const targetValue = this.getValueFromData(
617
- finalData,
618
- context,
619
- targetFieldKey
620
- );
621
- const isMatch = `${targetValue}` === `${valueToMatch}`;
622
- // Ensure the targetValue is defined and not null
623
- return (
624
- isMatch &&
625
- targetValue !== undefined &&
626
- targetValue !== null
627
- );
628
- }
629
- );
630
-
631
- if (foundData.length) {
632
- newData.push(
633
- ...foundData.map((data) => {
634
- const newValue = this.getValueFromData(
635
- data.finalData,
636
- data.context,
637
- idMapping.targetField
638
- );
639
- return newValue;
640
- })
641
- );
642
- } else {
643
- logger.info(
644
- `No data found for collection: ${targetCollectionKey} with value: ${valueToMatch} for field: ${fieldToSetKey} -- idMapping: ${JSON.stringify(
645
- idMapping,
646
- null,
647
- 2
648
- )}`
649
- );
650
- }
651
- continue;
652
- }
653
-
654
- const getCurrentDataFiltered = (currentData: any) => {
655
- if (Array.isArray(currentData.finalData[fieldToSetKey])) {
656
- return currentData.finalData[fieldToSetKey].filter(
657
- (data: any) => !sourceValues.includes(`${data}`)
658
- );
659
- }
660
- return currentData.finalData[fieldToSetKey];
661
- };
662
-
663
- // Get the current data to be updated
664
- const currentDataFiltered = getCurrentDataFiltered(
665
- collectionData.data[i]
666
- );
667
-
668
- if (newData.length) {
669
- needsUpdate = true;
670
-
671
- // Handle cases where current data is an array
672
- if (isFieldToSetArray) {
673
- if (!currentDataFiltered) {
674
- // Set new data if current data is undefined
675
- collectionData.data[i].finalData[fieldToSetKey] =
676
- Array.isArray(newData) ? newData : [newData];
677
- } else {
678
- if (Array.isArray(currentDataFiltered)) {
679
- // Convert current data to array and merge if new data is non-empty array
680
- collectionData.data[i].finalData[fieldToSetKey] = [
681
- ...new Set(
682
- [...currentDataFiltered, ...newData].filter(
683
- (value: any) =>
684
- value !== null &&
685
- value !== undefined &&
686
- value !== ""
687
- )
688
- ),
689
- ];
690
- } else {
691
- // Merge arrays if new data is non-empty array and filter for uniqueness
692
- collectionData.data[i].finalData[fieldToSetKey] = [
693
- ...new Set(
694
- [
695
- ...(Array.isArray(currentDataFiltered)
696
- ? currentDataFiltered
697
- : [currentDataFiltered]),
698
- ...newData,
699
- ].filter(
700
- (value: any) =>
701
- value !== null &&
702
- value !== undefined &&
703
- value !== "" &&
704
- !sourceValues.includes(`${value}`)
705
- )
706
- ),
707
- ];
708
- }
709
- }
710
- } else {
711
- if (!currentDataFiltered) {
712
- // Set new data if current data is undefined
713
- collectionData.data[i].finalData[fieldToSetKey] =
714
- Array.isArray(newData) ? newData[0] : newData;
715
- } else if (Array.isArray(newData) && newData.length > 0) {
716
- // Convert current data to array and merge if new data is non-empty array, then filter for uniqueness
717
- // and take the first value, because it's an array and the attribute is not an array
718
- collectionData.data[i].finalData[fieldToSetKey] = [
719
- ...new Set(
720
- [currentDataFiltered, ...newData].filter(
721
- (value: any) =>
722
- value !== null &&
723
- value !== undefined &&
724
- value !== "" &&
725
- !sourceValues.includes(`${value}`)
726
- )
727
- ),
728
- ].slice(0, 1)[0];
729
- } else if (
730
- !Array.isArray(newData) &&
731
- newData !== undefined
732
- ) {
733
- // Simply update the field if new data is not an array and defined
734
- collectionData.data[i].finalData[fieldToSetKey] = newData;
735
- }
736
- }
737
- }
738
- }
739
- }
740
- }
741
- }
742
- }
743
-
744
- // Update the import map if any changes were made
745
- if (needsUpdate) {
746
- this.importMap.set(collectionKey, collectionData);
747
- }
748
- }
749
- }
750
-
751
- private writeMapsToJsonFile() {
752
- const outputDir = path.resolve(process.cwd(), "zlogs");
753
-
754
- // Ensure the logs directory exists
755
- if (!fs.existsSync(outputDir)) {
756
- fs.mkdirSync(outputDir);
757
- }
758
-
759
- // Helper function to write data to a file
760
- const writeToFile = (fileName: string, data: any) => {
761
- const outputFile = path.join(outputDir, fileName);
762
- fs.writeFile(outputFile, JSON.stringify(data, null, 2), "utf8", (err) => {
763
- if (err) {
764
- MessageFormatter.error(`Error writing data to ${fileName}`, err instanceof Error ? err : new Error(String(err)), { prefix: "Data" });
765
- return;
766
- }
767
- MessageFormatter.success(`Data successfully written to ${fileName}`, { prefix: "Data" });
768
- });
769
- };
770
-
771
- // Convert Maps to arrays of entries for serialization
772
- const oldIdToNewIdPerCollectionMap = Array.from(
773
- this.oldIdToNewIdPerCollectionMap.entries()
774
- ).map(([key, value]) => {
775
- return {
776
- collection: key,
777
- data: Array.from(value.entries()),
778
- };
779
- });
780
-
781
- const mergedUserMap = Array.from(this.mergedUserMap.entries());
782
-
783
- // Write each part to a separate file
784
- writeToFile(
785
- "oldIdToNewIdPerCollectionMap.json",
786
- oldIdToNewIdPerCollectionMap
787
- );
788
- writeToFile("mergedUserMap.json", mergedUserMap);
789
-
790
- // Write each collection's data to a separate file
791
- this.importMap.forEach((value, key) => {
792
- const data = {
793
- collection: key,
794
- data: value.data.map((item: any) => {
795
- return {
796
- finalData: item.finalData,
797
- context: item.context,
798
- };
799
- }),
800
- };
801
- writeToFile(`${key}.json`, data);
802
- });
803
- }
804
-
805
- /**
806
- * Prepares user data by checking for duplicates based on email or phone, adding to a duplicate map if found,
807
- * and then returning the transformed item without user-specific keys.
808
- *
809
- * @param item - The raw item to be processed.
810
- * @param attributeMappings - The attribute mappings for the item.
811
- * @returns The transformed item with user-specific keys removed.
812
- */
813
- prepareUserData(
814
- item: any,
815
- attributeMappings: AttributeMappings,
816
- primaryKeyField: string,
817
- newId: string
818
- ): {
819
- transformedItem: any;
820
- existingId: string | undefined;
821
- userData: {
822
- rawData: any;
823
- finalData: z.infer<typeof AuthUserCreateSchema>;
824
- };
825
- } {
826
- if (
827
- this.userIdSet.has(newId) ||
828
- this.userExistsMap.has(newId) ||
829
- Array.from(this.emailToUserIdMap.values()).includes(newId) ||
830
- Array.from(this.phoneToUserIdMap.values()).includes(newId)
831
- ) {
832
- newId = this.getTrueUniqueId(this.getCollectionKey("users"));
833
- }
834
- let transformedItem = this.transformData(item, attributeMappings);
835
- let userData = AuthUserCreateSchema.safeParse(transformedItem);
836
- if (userData.data?.email) {
837
- userData.data.email = userData.data.email.toLowerCase();
838
- }
839
- if (!userData.success || !(userData.data.email || userData.data.phone)) {
840
- logger.error(
841
- `Invalid user data: ${JSON.stringify(
842
- userData.error?.issues,
843
- undefined,
844
- 2
845
- )} or missing email/phone`
846
- );
847
-
848
- const userKeys = ["email", "phone", "name", "labels", "prefs"];
849
- userKeys.forEach((key) => {
850
- if (transformedItem.hasOwnProperty(key)) {
851
- delete transformedItem[key];
852
- }
853
- });
854
- return {
855
- transformedItem,
856
- existingId: undefined,
857
- userData: {
858
- rawData: item,
859
- finalData: transformedItem,
860
- },
861
- };
862
- }
863
- const email = userData.data.email?.toLowerCase();
864
- const phone = userData.data.phone;
865
- let existingId: string | undefined;
866
-
867
- // Check for duplicate email and phone
868
- if (email && this.emailToUserIdMap.has(email)) {
869
- existingId = this.emailToUserIdMap.get(email);
870
- if (phone && !this.phoneToUserIdMap.has(phone)) {
871
- this.phoneToUserIdMap.set(phone, newId);
872
- }
873
- } else if (phone && this.phoneToUserIdMap.has(phone)) {
874
- existingId = this.phoneToUserIdMap.get(phone);
875
- if (email && !this.emailToUserIdMap.has(email)) {
876
- this.emailToUserIdMap.set(email, newId);
877
- }
878
- } else {
879
- if (email) this.emailToUserIdMap.set(email, newId);
880
- if (phone) this.phoneToUserIdMap.set(phone, newId);
881
- }
882
-
883
- if (existingId) {
884
- userData.data.userId = existingId;
885
- const mergedUsers = this.mergedUserMap.get(existingId) || [];
886
- mergedUsers.push(`${item[primaryKeyField]}`);
887
- this.mergedUserMap.set(existingId, mergedUsers);
888
- const userFound = this.importMap
889
- .get(this.getCollectionKey("users"))
890
- ?.data.find((userDataExisting) => {
891
- let userIdToMatch: string | undefined;
892
- if (userDataExisting?.finalData?.userId) {
893
- userIdToMatch = userDataExisting?.finalData?.userId;
894
- } else if (userDataExisting?.finalData?.docId) {
895
- userIdToMatch = userDataExisting?.finalData?.docId;
896
- } else if (userDataExisting?.context?.userId) {
897
- userIdToMatch = userDataExisting.context.userId;
898
- } else if (userDataExisting?.context?.docId) {
899
- userIdToMatch = userDataExisting.context.docId;
900
- }
901
- return userIdToMatch === existingId;
902
- });
903
- if (userFound) {
904
- userFound.finalData.userId = existingId;
905
- userFound.finalData.docId = existingId;
906
- this.userIdSet.add(existingId);
907
- transformedItem = {
908
- ...transformedItem,
909
- userId: existingId,
910
- docId: existingId,
911
- };
912
- }
913
-
914
- const userKeys = ["email", "phone", "name", "labels", "prefs"];
915
- userKeys.forEach((key) => {
916
- if (transformedItem.hasOwnProperty(key)) {
917
- delete transformedItem[key];
918
- }
919
- });
920
- return {
921
- transformedItem,
922
- existingId,
923
- userData: {
924
- rawData: userFound?.rawData,
925
- finalData: userFound?.finalData,
926
- },
927
- };
928
- } else {
929
- existingId = newId;
930
- userData.data.userId = existingId;
931
- }
932
-
933
- const userKeys = ["email", "phone", "name", "labels", "prefs"];
934
- userKeys.forEach((key) => {
935
- if (transformedItem.hasOwnProperty(key)) {
936
- delete transformedItem[key];
937
- }
938
- });
939
-
940
- const usersMap = this.importMap.get(this.getCollectionKey("users"));
941
- const userDataToAdd = {
942
- rawData: item,
943
- finalData: userData.data,
944
- context: {},
945
- };
946
- this.importMap.set(this.getCollectionKey("users"), {
947
- data: [...(usersMap?.data || []), userDataToAdd],
948
- });
949
- this.userIdSet.add(existingId);
950
-
951
- return {
952
- transformedItem,
953
- existingId,
954
- userData: userDataToAdd,
955
- };
956
- }
957
-
958
- /**
959
- * Prepares the data for creating user collection documents.
960
- * This involves loading the data, transforming it according to the import definition,
961
- * and handling the creation of new unique IDs for each item.
962
- *
963
- * @param db - The database configuration.
964
- * @param collection - The collection configuration.
965
- * @param importDef - The import definition containing the attribute mappings and other relevant info.
966
- */
967
- async prepareUserCollectionCreateData(
968
- db: ConfigDatabase,
969
- collection: CollectionCreate,
970
- importDef: ImportDef
971
- ): Promise<void> {
972
- // Load the raw data based on the import definition
973
- const rawData = this.loadData(importDef);
974
- let operationId = this.collectionImportOperations.get(
975
- this.getCollectionKey(collection.name)
976
- );
977
- // Initialize a new map for old ID to new ID mappings
978
- const oldIdToNewIdMap = new Map<string, string>();
979
- // Retrieve or initialize the collection-specific old ID to new ID map
980
- const collectionOldIdToNewIdMap =
981
- this.oldIdToNewIdPerCollectionMap.get(
982
- this.getCollectionKey(collection.name)
983
- ) ||
984
- this.oldIdToNewIdPerCollectionMap
985
- .set(this.getCollectionKey(collection.name), oldIdToNewIdMap)
986
- .get(this.getCollectionKey(collection.name));
987
- const adapter = await this.getAdapter();
988
- if (!operationId) {
989
- const collectionImportOperation = await findOrCreateOperation(
990
- adapter,
991
- db.$id,
992
- "importData",
993
- collection.$id!
994
- );
995
- // Store the operation ID in the map
996
- this.collectionImportOperations.set(
997
- this.getCollectionKey(collection.name),
998
- collectionImportOperation.$id
999
- );
1000
- operationId = collectionImportOperation.$id;
1001
- }
1002
- if (operationId) {
1003
- await updateOperation(adapter, db.$id, operationId, {
1004
- status: "in_progress",
1005
- total: rawData.length,
1006
- });
1007
- }
1008
- // Retrieve the current user data and the current collection data from the import map
1009
- const currentUserData = this.importMap.get(this.getCollectionKey("users"));
1010
- const currentData = this.importMap.get(
1011
- this.getCollectionKey(collection.name)
1012
- );
1013
- // Log errors if the necessary data is not found in the import map
1014
- if (!currentUserData) {
1015
- logger.error(
1016
- `No data found for collection ${"users"} for createDef but it says it's supposed to have one...`
1017
- );
1018
- return;
1019
- } else if (!currentData) {
1020
- logger.error(
1021
- `No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`
1022
- );
1023
- return;
1024
- }
1025
- // Iterate through each item in the raw data
1026
- for (const item of rawData) {
1027
- // Prepare user data, check for duplicates, and remove user-specific keys
1028
- let { transformedItem, existingId, userData } = this.prepareUserData(
1029
- item,
1030
- importDef.attributeMappings,
1031
- importDef.primaryKeyField,
1032
- this.getTrueUniqueId(this.getCollectionKey("users"))
1033
- );
1034
-
1035
- logger.info(
1036
- `In create user -- transformedItem: ${JSON.stringify(
1037
- transformedItem,
1038
- null,
1039
- 2
1040
- )}`
1041
- );
1042
-
1043
- // Generate a new unique ID for the item or use existing ID
1044
- if (!existingId && !userData.finalData?.userId) {
1045
- // No existing user ID, generate a new unique ID
1046
- existingId = this.getTrueUniqueId(
1047
- this.getCollectionKey(collection.name)
1048
- );
1049
- transformedItem = {
1050
- ...transformedItem,
1051
- userId: existingId,
1052
- docId: existingId,
1053
- };
1054
- } else if (!existingId && userData.finalData?.userId) {
1055
- // Existing user ID, use it as the new ID
1056
- existingId = userData.finalData.userId;
1057
- transformedItem = {
1058
- ...transformedItem,
1059
- userId: existingId,
1060
- docId: existingId,
1061
- };
1062
- }
1063
-
1064
- // Create a context object for the item, including the new ID
1065
- let context = this.createContext(db, collection, item, existingId!);
1066
-
1067
- // Merge the transformed data into the context
1068
- context = { ...context, ...transformedItem, ...userData.finalData };
1069
-
1070
- // If a primary key field is defined, handle the ID mapping and check for duplicates
1071
- if (importDef.primaryKeyField) {
1072
- const oldId = item[importDef.primaryKeyField];
1073
-
1074
- // Check if the oldId already exists to handle potential duplicates
1075
- if (
1076
- this.oldIdToNewIdPerCollectionMap
1077
- .get(this.getCollectionKey(collection.name))
1078
- ?.has(`${oldId}`)
1079
- ) {
1080
- // Found a duplicate oldId, now decide how to merge or handle these duplicates
1081
- for (const data of currentData.data) {
1082
- if (
1083
- data.finalData.docId === oldId ||
1084
- data.finalData.userId === oldId ||
1085
- data.context.docId === oldId ||
1086
- data.context.userId === oldId
1087
- ) {
1088
- transformedItem = this.mergeObjects(
1089
- data.finalData,
1090
- transformedItem
1091
- );
1092
- }
1093
- }
1094
- } else {
1095
- // No duplicate found, simply map the oldId to the new itemId
1096
- collectionOldIdToNewIdMap?.set(`${oldId}`, `${existingId}`);
1097
- }
1098
- }
1099
-
1100
- // Handle merging for currentUserData
1101
- for (let i = 0; i < currentUserData.data.length; i++) {
1102
- const currentUserDataItem = currentUserData.data[i];
1103
- const samePhones =
1104
- currentUserDataItem.finalData.phone &&
1105
- transformedItem.phone &&
1106
- currentUserDataItem.finalData.phone === transformedItem.phone;
1107
- const sameEmails =
1108
- currentUserDataItem.finalData.email &&
1109
- transformedItem.email &&
1110
- currentUserDataItem.finalData.email === transformedItem.email;
1111
- if (
1112
- (currentUserDataItem.finalData.docId === existingId ||
1113
- currentUserDataItem.finalData.userId === existingId) &&
1114
- (samePhones || sameEmails) &&
1115
- currentUserDataItem.finalData &&
1116
- userData.finalData
1117
- ) {
1118
- const userDataMerged = this.mergeObjects(
1119
- currentUserData.data[i].finalData,
1120
- userData.finalData
1121
- );
1122
- currentUserData.data[i].finalData = userDataMerged;
1123
- this.importMap.set(this.getCollectionKey("users"), currentUserData);
1124
- }
1125
- }
1126
- // Update the attribute mappings with any actions that need to be performed post-import
1127
- // We added the basePath to get the folder from the filePath
1128
- const mappingsWithActions = this.getAttributeMappingsWithActions(
1129
- importDef.attributeMappings,
1130
- context,
1131
- transformedItem
1132
- );
1133
- // Update the import definition with the new attribute mappings
1134
- const newImportDef = {
1135
- ...importDef,
1136
- attributeMappings: mappingsWithActions,
1137
- };
1138
-
1139
- const updatedData = this.importMap.get(
1140
- this.getCollectionKey(collection.name)
1141
- )!;
1142
-
1143
- let foundData = false;
1144
- for (let i = 0; i < updatedData.data.length; i++) {
1145
- if (
1146
- updatedData.data[i].finalData.docId === existingId ||
1147
- updatedData.data[i].finalData.userId === existingId ||
1148
- updatedData.data[i].context.docId === existingId ||
1149
- updatedData.data[i].context.userId === existingId
1150
- ) {
1151
- updatedData.data[i].finalData = this.mergeObjects(
1152
- updatedData.data[i].finalData,
1153
- transformedItem
1154
- );
1155
- updatedData.data[i].context = this.mergeObjects(
1156
- updatedData.data[i].context,
1157
- context
1158
- );
1159
- const mergedImportDef = {
1160
- ...updatedData.data[i].importDef,
1161
- idMappings: [
1162
- ...(updatedData.data[i].importDef?.idMappings || []),
1163
- ...(newImportDef.idMappings || []),
1164
- ],
1165
- attributeMappings: [
1166
- ...(updatedData.data[i].importDef?.attributeMappings || []),
1167
- ...(newImportDef.attributeMappings || []),
1168
- ],
1169
- };
1170
- updatedData.data[i].importDef = mergedImportDef as ImportDef;
1171
- this.importMap.set(
1172
- this.getCollectionKey(collection.name),
1173
- updatedData
1174
- );
1175
- this.oldIdToNewIdPerCollectionMap.set(
1176
- this.getCollectionKey(collection.name),
1177
- collectionOldIdToNewIdMap!
1178
- );
1179
-
1180
- foundData = true;
1181
- }
1182
- }
1183
- if (!foundData) {
1184
- // Add new data to the associated collection
1185
- updatedData.data.push({
1186
- rawData: item,
1187
- context: context,
1188
- importDef: newImportDef,
1189
- finalData: transformedItem,
1190
- });
1191
- this.importMap.set(this.getCollectionKey(collection.name), updatedData);
1192
- this.oldIdToNewIdPerCollectionMap.set(
1193
- this.getCollectionKey(collection.name),
1194
- collectionOldIdToNewIdMap!
1195
- );
1196
- }
1197
- }
1198
- }
1199
-
1200
- /**
1201
- * Prepares the data for creating documents in a collection.
1202
- * This involves loading the data, transforming it, and handling ID mappings.
1203
- *
1204
- * @param db - The database configuration.
1205
- * @param collection - The collection configuration.
1206
- * @param importDef - The import definition containing the attribute mappings and other relevant info.
1207
- */
1208
- async prepareCreateData(
1209
- db: ConfigDatabase,
1210
- collection: CollectionCreate,
1211
- importDef: ImportDef
1212
- ): Promise<void> {
1213
- // Load the raw data based on the import definition
1214
- const rawData = this.loadData(importDef);
1215
- let operationId = this.collectionImportOperations.get(
1216
- this.getCollectionKey(collection.name)
1217
- );
1218
- const adapter = await this.getAdapter();
1219
- if (!operationId) {
1220
- const collectionImportOperation = await findOrCreateOperation(
1221
- adapter,
1222
- db.$id,
1223
- "importData",
1224
- collection.$id!
1225
- );
1226
- // Store the operation ID in the map
1227
- this.collectionImportOperations.set(
1228
- this.getCollectionKey(collection.name),
1229
- collectionImportOperation.$id
1230
- );
1231
- operationId = collectionImportOperation.$id;
1232
- }
1233
- if (operationId) {
1234
- await updateOperation(adapter, db.$id, operationId, {
1235
- status: "in_progress",
1236
- total: rawData.length,
1237
- });
1238
- }
1239
- // Initialize a new map for old ID to new ID mappings
1240
- const oldIdToNewIdMapNew = new Map<string, string>();
1241
- // Retrieve or initialize the collection-specific old ID to new ID map
1242
- const collectionOldIdToNewIdMap =
1243
- this.oldIdToNewIdPerCollectionMap.get(
1244
- this.getCollectionKey(collection.name)
1245
- ) ||
1246
- this.oldIdToNewIdPerCollectionMap
1247
- .set(this.getCollectionKey(collection.name), oldIdToNewIdMapNew)
1248
- .get(this.getCollectionKey(collection.name));
1249
- const isRegions = collection.name.toLowerCase() === "regions";
1250
- // Iterate through each item in the raw data
1251
- for (const item of rawData) {
1252
- // Generate a new unique ID for the item
1253
- const itemIdNew = this.getTrueUniqueId(
1254
- this.getCollectionKey(collection.name)
1255
- );
1256
- if (isRegions) {
1257
- logger.info(`Creating region: ${JSON.stringify(item, null, 2)}`);
1258
- }
1259
- // Retrieve the current collection data from the import map
1260
- const currentData = this.importMap.get(
1261
- this.getCollectionKey(collection.name)
1262
- );
1263
- // Create a context object for the item, including the new ID
1264
- let context = this.createContext(db, collection, item, itemIdNew);
1265
- // Transform the item data based on the attribute mappings
1266
- let transformedData = this.transformData(
1267
- item,
1268
- importDef.attributeMappings
1269
- );
1270
- // If a primary key field is defined, handle the ID mapping and check for duplicates
1271
- if (importDef.primaryKeyField) {
1272
- const oldId = item[importDef.primaryKeyField];
1273
- if (collectionOldIdToNewIdMap?.has(`${oldId}`)) {
1274
- logger.error(
1275
- `Collection ${collection.name} has multiple documents with the same primary key ${oldId}`
1276
- );
1277
- continue;
1278
- }
1279
- collectionOldIdToNewIdMap?.set(`${oldId}`, `${itemIdNew}`);
1280
- }
1281
- // Merge the transformed data into the context
1282
- context = { ...context, ...transformedData };
1283
- // Validate the item before proceeding
1284
- const isValid = this.importDataActions.validateItem(
1285
- transformedData,
1286
- importDef.attributeMappings,
1287
- context
1288
- );
1289
- if (!isValid) {
1290
- continue;
1291
- }
1292
- // Update the attribute mappings with any actions that need to be performed post-import
1293
- // We added the basePath to get the folder from the filePath
1294
- const mappingsWithActions = this.getAttributeMappingsWithActions(
1295
- importDef.attributeMappings,
1296
- context,
1297
- transformedData
1298
- );
1299
- // Update the import definition with the new attribute mappings
1300
- const newImportDef = {
1301
- ...importDef,
1302
- attributeMappings: mappingsWithActions,
1303
- };
1304
- // If the current collection data exists, add the item with its context and final data
1305
- if (currentData && currentData.data) {
1306
- currentData.data.push({
1307
- rawData: item,
1308
- context: context,
1309
- importDef: newImportDef,
1310
- finalData: transformedData,
1311
- });
1312
- this.importMap.set(this.getCollectionKey(collection.name), currentData);
1313
- this.oldIdToNewIdPerCollectionMap.set(
1314
- this.getCollectionKey(collection.name),
1315
- collectionOldIdToNewIdMap!
1316
- );
1317
- } else {
1318
- logger.error(
1319
- `No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`
1320
- );
1321
- continue;
1322
- }
1323
- }
1324
- }
1325
-
1326
- /**
1327
- * Prepares the data for updating documents within a collection.
1328
- * This method loads the raw data based on the import definition, transforms it according to the attribute mappings,
1329
- * finds the new ID for each item based on the primary key or update mapping, and then validates the transformed data.
1330
- * If the data is valid, it updates the import definition with any post-import actions and adds the item to the current collection data.
1331
- *
1332
- * @param db - The database configuration.
1333
- * @param collection - The collection configuration.
1334
- * @param importDef - The import definition containing the attribute mappings and other relevant info.
1335
- */
1336
- async prepareUpdateData(
1337
- db: ConfigDatabase,
1338
- collection: CollectionCreate,
1339
- importDef: ImportDef
1340
- ) {
1341
- const currentData = this.importMap.get(
1342
- this.getCollectionKey(collection.name)
1343
- );
1344
- const oldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(
1345
- this.getCollectionKey(collection.name)
1346
- );
1347
-
1348
- if (
1349
- !(currentData?.data && currentData?.data.length > 0) &&
1350
- !oldIdToNewIdMap
1351
- ) {
1352
- logger.error(
1353
- `No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`
1354
- );
1355
- return;
1356
- }
1357
-
1358
- const rawData = this.loadData(importDef);
1359
- const operationId = this.collectionImportOperations.get(
1360
- this.getCollectionKey(collection.name)
1361
- );
1362
- if (!operationId) {
1363
- throw new Error(
1364
- `No import operation found for collection ${collection.name}`
1365
- );
1366
- }
1367
-
1368
- for (const item of rawData) {
1369
- let transformedData = this.transformData(
1370
- item,
1371
- importDef.attributeMappings
1372
- );
1373
- let newId: string | undefined;
1374
- let oldId: string | undefined;
1375
- let itemDataToUpdate: CollectionImportData["data"][number] | undefined;
1376
-
1377
- // Try to find itemDataToUpdate using updateMapping
1378
- if (importDef.updateMapping) {
1379
- oldId =
1380
- item[importDef.updateMapping.originalIdField] ||
1381
- transformedData[importDef.updateMapping.originalIdField];
1382
- if (oldId) {
1383
- itemDataToUpdate = currentData?.data.find(
1384
- ({ context, finalData }) => {
1385
- const targetField =
1386
- importDef.updateMapping!.targetField ??
1387
- importDef.updateMapping!.originalIdField;
1388
-
1389
- return (
1390
- `${context[targetField]}` === `${oldId}` ||
1391
- `${finalData[targetField]}` === `${oldId}`
1392
- );
1393
- }
1394
- );
1395
-
1396
- if (itemDataToUpdate) {
1397
- newId = itemDataToUpdate.context.docId;
1398
- }
1399
- }
1400
- }
1401
-
1402
- // If updateMapping is not defined or did not find the item, use primaryKeyField
1403
- if (!itemDataToUpdate && importDef.primaryKeyField) {
1404
- oldId =
1405
- item[importDef.primaryKeyField] ||
1406
- transformedData[importDef.primaryKeyField];
1407
- if (oldId && oldId.length > 0) {
1408
- newId = oldIdToNewIdMap?.get(`${oldId}`);
1409
- if (
1410
- !newId &&
1411
- this.getCollectionKey(this.config.usersCollectionName) ===
1412
- this.getCollectionKey(collection.name)
1413
- ) {
1414
- for (const [key, value] of this.mergedUserMap.entries()) {
1415
- if (value.includes(`${oldId}`)) {
1416
- newId = key;
1417
- break;
1418
- }
1419
- }
1420
- }
1421
- }
1422
-
1423
- if (oldId && !itemDataToUpdate) {
1424
- itemDataToUpdate = currentData?.data.find(
1425
- (data) =>
1426
- `${data.context[importDef.primaryKeyField]}` === `${oldId}`
1427
- );
1428
- }
1429
- }
1430
-
1431
- if (!oldId) {
1432
- logger.error(
1433
- `No old ID found (to update another document with) in prepareUpdateData for ${
1434
- collection.name
1435
- }, ${JSON.stringify(item, null, 2)}`
1436
- );
1437
- continue;
1438
- }
1439
-
1440
- if (!newId && !itemDataToUpdate) {
1441
- logger.error(
1442
- `No new id && no data found for collection ${
1443
- collection.name
1444
- } for updateDef ${JSON.stringify(
1445
- item,
1446
- null,
1447
- 2
1448
- )} but it says it's supposed to have one...`
1449
- );
1450
- continue;
1451
- } else if (itemDataToUpdate) {
1452
- newId =
1453
- itemDataToUpdate.finalData.docId || itemDataToUpdate.context.docId;
1454
- if (!newId) {
1455
- logger.error(
1456
- `No new id found for collection ${
1457
- collection.name
1458
- } for updateDef ${JSON.stringify(
1459
- item,
1460
- null,
1461
- 2
1462
- )} but has itemDataToUpdate ${JSON.stringify(
1463
- itemDataToUpdate,
1464
- null,
1465
- 2
1466
- )} but it says it's supposed to have one...`
1467
- );
1468
- continue;
1469
- }
1470
- }
1471
-
1472
- if (!itemDataToUpdate || !newId) {
1473
- logger.error(
1474
- `No data or ID (docId) found for collection ${
1475
- collection.name
1476
- } for updateDef ${JSON.stringify(
1477
- item,
1478
- null,
1479
- 2
1480
- )} but it says it's supposed to have one...`
1481
- );
1482
- continue;
1483
- }
1484
-
1485
- transformedData = this.mergeObjects(
1486
- itemDataToUpdate.finalData,
1487
- transformedData
1488
- );
1489
-
1490
- // Create a context object for the item, including the new ID and transformed data
1491
- let context = itemDataToUpdate.context;
1492
- context = this.mergeObjects(context, transformedData);
1493
-
1494
- // Validate the item before proceeding
1495
- const isValid = this.importDataActions.validateItem(
1496
- item,
1497
- importDef.attributeMappings,
1498
- context
1499
- );
1500
-
1501
- if (!isValid) {
1502
- logger.info(
1503
- `Skipping item: ${JSON.stringify(item, null, 2)} because it's invalid`
1504
- );
1505
- continue;
1506
- }
1507
-
1508
- // Update the attribute mappings with any actions that need to be performed post-import
1509
- // We added the basePath to get the folder from the filePath
1510
- const mappingsWithActions = this.getAttributeMappingsWithActions(
1511
- importDef.attributeMappings,
1512
- context,
1513
- transformedData
1514
- );
1515
-
1516
- // Update the import definition with the new attribute mappings
1517
- const newImportDef = {
1518
- ...importDef,
1519
- attributeMappings: mappingsWithActions,
1520
- };
1521
-
1522
- if (itemDataToUpdate) {
1523
- itemDataToUpdate.finalData = this.mergeObjects(
1524
- itemDataToUpdate.finalData,
1525
- transformedData
1526
- );
1527
- itemDataToUpdate.context = context;
1528
-
1529
- // Fix: Ensure we properly merge the attribute mappings and their actions
1530
- const mergedAttributeMappings = newImportDef.attributeMappings.map(
1531
- (newMapping) => {
1532
- const existingMapping =
1533
- itemDataToUpdate.importDef?.attributeMappings.find(
1534
- (m) => m.targetKey === newMapping.targetKey
1535
- );
1536
-
1537
- return {
1538
- ...newMapping,
1539
- postImportActions: [
1540
- ...(existingMapping?.postImportActions || []),
1541
- ...(newMapping.postImportActions || []),
1542
- ],
1543
- };
1544
- }
1545
- );
1546
-
1547
- itemDataToUpdate.importDef = {
1548
- ...newImportDef,
1549
- attributeMappings: mergedAttributeMappings,
1550
- };
1551
-
1552
- // Debug logging
1553
- if (
1554
- mergedAttributeMappings.some((m) => m.postImportActions?.length > 0)
1555
- ) {
1556
- logger.info(
1557
- `Post-import actions for ${collection.name}: ${JSON.stringify(
1558
- mergedAttributeMappings
1559
- .filter((m) => m.postImportActions?.length > 0)
1560
- .map((m) => ({
1561
- targetKey: m.targetKey,
1562
- actions: m.postImportActions,
1563
- })),
1564
- null,
1565
- 2
1566
- )}`
1567
- );
1568
- }
1569
- } else {
1570
- currentData!.data.push({
1571
- rawData: item,
1572
- context: context,
1573
- importDef: newImportDef,
1574
- finalData: transformedData,
1575
- });
1576
- }
1577
-
1578
- // Since we're modifying currentData in place, we ensure no duplicates are added
1579
- this.importMap.set(this.getCollectionKey(collection.name), currentData!);
1580
- }
1581
- }
1582
-
1583
- private updateReferencesBasedOnAttributeMappings() {
1584
- if (!this.config.collections) {
1585
- return;
1586
- }
1587
- this.config.collections.forEach((collectionConfig) => {
1588
- const collectionName = collectionConfig.name;
1589
- const collectionData = this.importMap.get(
1590
- this.getCollectionKey(collectionName)
1591
- );
1592
-
1593
- if (!collectionData) {
1594
- logger.error(`No data found for collection ${collectionName}`);
1595
- return;
1596
- }
1597
-
1598
- collectionData.data.forEach((dataItem) => {
1599
- collectionConfig.importDefs.forEach((importDef) => {
1600
- if (!importDef.idMappings) return; // Skip collections without idMappings
1601
- importDef.idMappings.forEach((mapping) => {
1602
- if (mapping && mapping.targetField) {
1603
- const idsToUpdate = Array.isArray(
1604
- dataItem[mapping.targetField as keyof typeof dataItem]
1605
- )
1606
- ? dataItem[mapping.targetField as keyof typeof dataItem]
1607
- : [dataItem[mapping.targetField as keyof typeof dataItem]];
1608
- const updatedIds = idsToUpdate.map((id: string) =>
1609
- this.getMergedId(id, mapping.targetCollection)
1610
- );
1611
-
1612
- // Update the dataItem with the new IDs
1613
- dataItem[mapping.targetField as keyof typeof dataItem] =
1614
- Array.isArray(
1615
- dataItem[mapping.targetField as keyof typeof dataItem]
1616
- )
1617
- ? updatedIds
1618
- : updatedIds[0];
1619
- }
1620
- });
1621
- });
1622
- });
1623
- });
1624
- }
1625
-
1626
- private getMergedId(oldId: string, relatedCollectionName: string): string {
1627
- // Retrieve the old to new ID map for the related collection
1628
- const oldToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(
1629
- this.getCollectionKey(relatedCollectionName)
1630
- );
1631
-
1632
- // If there's a mapping for the old ID, return the new ID
1633
- if (oldToNewIdMap && oldToNewIdMap.has(`${oldId}`)) {
1634
- return oldToNewIdMap.get(`${oldId}`)!; // The non-null assertion (!) is used because we checked if the map has the key
1635
- }
1636
-
1637
- // If no mapping is found, return the old ID as a fallback
1638
- return oldId;
1639
- }
1640
-
1641
- /**
1642
- * Generates attribute mappings with post-import actions based on the provided attribute mappings.
1643
- * This method checks each mapping for a fileData attribute and adds a post-import action to create a file
1644
- * and update the field with the file's ID if necessary.
1645
- *
1646
- * @param attributeMappings - The attribute mappings from the import definition.
1647
- * @param context - The context object containing information about the database, collection, and document.
1648
- * @param item - The item being imported, used for resolving template paths in fileData mappings.
1649
- * @returns The attribute mappings updated with any necessary post-import actions.
1650
- */
1651
- getAttributeMappingsWithActions(
1652
- attributeMappings: AttributeMappings,
1653
- context: any,
1654
- item: any
1655
- ) {
1656
- // Iterate over each attribute mapping to check for fileData attributes
1657
- return attributeMappings.map((mapping) => {
1658
- if (mapping.fileData) {
1659
- // Resolve the file path using the provided template, context, and item
1660
- let mappingFilePath = this.importDataActions.resolveTemplate(
1661
- mapping.fileData.path,
1662
- context,
1663
- item
1664
- );
1665
- // Ensure the file path is absolute if it doesn't start with "http"
1666
- if (!mappingFilePath.toLowerCase().startsWith("http")) {
1667
- // First try the direct path
1668
- let fullPath = path.resolve(this.appwriteFolderPath, mappingFilePath);
1669
-
1670
- // If file doesn't exist, search in subdirectories
1671
- if (!fs.existsSync(fullPath)) {
1672
- const findFileInDir = (dir: string): string | null => {
1673
- const files = fs.readdirSync(dir);
1674
-
1675
- for (const file of files) {
1676
- const filePath = path.join(dir, file);
1677
- const stat = fs.statSync(filePath);
1678
-
1679
- if (stat.isDirectory()) {
1680
- // Recursively search subdirectories
1681
- const found = findFileInDir(filePath);
1682
- if (found) return found;
1683
- } else if (file === path.basename(mappingFilePath)) {
1684
- return filePath;
1685
- }
1686
- }
1687
- return null;
1688
- };
1689
-
1690
- const foundPath = findFileInDir(this.appwriteFolderPath);
1691
- if (foundPath) {
1692
- mappingFilePath = foundPath;
1693
- } else {
1694
- logger.warn(
1695
- `File not found in any subdirectory: ${mappingFilePath}`
1696
- );
1697
- // Keep the original resolved path as fallback
1698
- mappingFilePath = fullPath;
1699
- }
1700
- } else {
1701
- mappingFilePath = fullPath;
1702
- }
1703
- }
1704
- // Define the after-import action to create a file and update the field
1705
- const afterImportAction = {
1706
- action: "createFileAndUpdateField",
1707
- params: [
1708
- "{dbId}",
1709
- "{collId}",
1710
- "{docId}",
1711
- mapping.targetKey,
1712
- `${this.config!.documentBucketId}_${context.dbName
1713
- .toLowerCase()
1714
- .replace(" ", "")}`, // Assuming 'images' is your bucket ID
1715
- mappingFilePath,
1716
- mapping.fileData.name,
1717
- ],
1718
- };
1719
- // Add the after-import action to the mapping's postImportActions array
1720
- const postImportActions = mapping.postImportActions
1721
- ? [...mapping.postImportActions, afterImportAction]
1722
- : [afterImportAction];
1723
- return { ...mapping, postImportActions };
1724
- }
1725
- // Return the mapping unchanged if no fileData attribute is found
1726
- return mapping;
1727
- });
1728
- }
1729
- }