appwrite-utils-cli 0.10.86 → 1.0.2
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.
- package/.appwrite/.yaml_schemas/appwrite-config.schema.json +380 -0
- package/.appwrite/.yaml_schemas/collection.schema.json +255 -0
- package/.appwrite/collections/Categories.yaml +182 -0
- package/.appwrite/collections/ExampleCollection.yaml +36 -0
- package/.appwrite/collections/Posts.yaml +227 -0
- package/.appwrite/collections/Users.yaml +149 -0
- package/.appwrite/config.yaml +109 -0
- package/.appwrite/import/README.md +148 -0
- package/.appwrite/import/categories-import.yaml +129 -0
- package/.appwrite/import/posts-import.yaml +208 -0
- package/.appwrite/import/users-import.yaml +130 -0
- package/.appwrite/importData/categories.json +194 -0
- package/.appwrite/importData/posts.json +270 -0
- package/.appwrite/importData/users.json +220 -0
- package/.appwrite/schemas/categories.json +128 -0
- package/.appwrite/schemas/exampleCollection.json +52 -0
- package/.appwrite/schemas/posts.json +173 -0
- package/.appwrite/schemas/users.json +125 -0
- package/README.md +264 -33
- package/dist/collections/attributes.js +3 -2
- package/dist/collections/methods.js +56 -38
- package/dist/config/yamlConfig.d.ts +501 -0
- package/dist/config/yamlConfig.js +452 -0
- package/dist/databases/setup.d.ts +6 -0
- package/dist/databases/setup.js +119 -0
- package/dist/functions/methods.d.ts +1 -1
- package/dist/functions/methods.js +5 -2
- package/dist/functions/openapi.d.ts +4 -0
- package/dist/functions/openapi.js +60 -0
- package/dist/interactiveCLI.d.ts +5 -0
- package/dist/interactiveCLI.js +194 -49
- package/dist/main.js +91 -30
- package/dist/migrations/afterImportActions.js +2 -2
- package/dist/migrations/appwriteToX.d.ts +10 -0
- package/dist/migrations/appwriteToX.js +15 -4
- package/dist/migrations/backup.d.ts +16 -16
- package/dist/migrations/dataLoader.d.ts +83 -1
- package/dist/migrations/dataLoader.js +4 -4
- package/dist/migrations/importController.js +25 -18
- package/dist/migrations/importDataActions.js +2 -2
- package/dist/migrations/logging.d.ts +9 -1
- package/dist/migrations/logging.js +41 -22
- package/dist/migrations/migrationHelper.d.ts +4 -4
- package/dist/migrations/relationships.js +1 -1
- package/dist/migrations/services/DataTransformationService.d.ts +55 -0
- package/dist/migrations/services/DataTransformationService.js +158 -0
- package/dist/migrations/services/FileHandlerService.d.ts +75 -0
- package/dist/migrations/services/FileHandlerService.js +236 -0
- package/dist/migrations/services/ImportOrchestrator.d.ts +97 -0
- package/dist/migrations/services/ImportOrchestrator.js +488 -0
- package/dist/migrations/services/RateLimitManager.d.ts +138 -0
- package/dist/migrations/services/RateLimitManager.js +279 -0
- package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
- package/dist/migrations/services/RelationshipResolver.js +332 -0
- package/dist/migrations/services/UserMappingService.d.ts +109 -0
- package/dist/migrations/services/UserMappingService.js +277 -0
- package/dist/migrations/services/ValidationService.d.ts +74 -0
- package/dist/migrations/services/ValidationService.js +260 -0
- package/dist/migrations/transfer.d.ts +0 -6
- package/dist/migrations/transfer.js +16 -132
- package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +384 -0
- package/dist/migrations/yaml/YamlImportConfigLoader.js +375 -0
- package/dist/migrations/yaml/YamlImportIntegration.d.ts +87 -0
- package/dist/migrations/yaml/YamlImportIntegration.js +330 -0
- package/dist/migrations/yaml/generateImportSchemas.d.ts +17 -0
- package/dist/migrations/yaml/generateImportSchemas.js +575 -0
- package/dist/schemas/authUser.d.ts +9 -9
- package/dist/shared/attributeManager.d.ts +17 -0
- package/dist/shared/attributeManager.js +273 -0
- package/dist/shared/confirmationDialogs.d.ts +75 -0
- package/dist/shared/confirmationDialogs.js +236 -0
- package/dist/shared/functionManager.d.ts +48 -0
- package/dist/shared/functionManager.js +322 -0
- package/dist/shared/indexManager.d.ts +24 -0
- package/dist/shared/indexManager.js +150 -0
- package/dist/shared/jsonSchemaGenerator.d.ts +51 -0
- package/dist/shared/jsonSchemaGenerator.js +313 -0
- package/dist/shared/logging.d.ts +10 -0
- package/dist/shared/logging.js +46 -0
- package/dist/shared/messageFormatter.d.ts +37 -0
- package/dist/shared/messageFormatter.js +152 -0
- package/dist/shared/migrationHelpers.d.ts +173 -0
- package/dist/shared/migrationHelpers.js +142 -0
- package/dist/shared/operationLogger.d.ts +3 -0
- package/dist/shared/operationLogger.js +25 -0
- package/dist/shared/operationQueue.d.ts +13 -0
- package/dist/shared/operationQueue.js +79 -0
- package/dist/shared/progressManager.d.ts +62 -0
- package/dist/shared/progressManager.js +215 -0
- package/dist/shared/schemaGenerator.d.ts +18 -0
- package/dist/shared/schemaGenerator.js +523 -0
- package/dist/storage/methods.d.ts +3 -1
- package/dist/storage/methods.js +144 -55
- package/dist/storage/schemas.d.ts +56 -16
- package/dist/types.d.ts +2 -2
- package/dist/types.js +1 -1
- package/dist/users/methods.d.ts +16 -0
- package/dist/users/methods.js +276 -0
- package/dist/utils/configMigration.d.ts +1 -0
- package/dist/utils/configMigration.js +262 -0
- package/dist/utils/dataConverters.d.ts +46 -0
- package/dist/utils/dataConverters.js +139 -0
- package/dist/utils/loadConfigs.d.ts +15 -4
- package/dist/utils/loadConfigs.js +379 -51
- package/dist/utils/schemaStrings.js +2 -1
- package/dist/utils/setupFiles.d.ts +2 -1
- package/dist/utils/setupFiles.js +723 -28
- package/dist/utils/validationRules.d.ts +43 -0
- package/dist/utils/validationRules.js +42 -0
- package/dist/utils/yamlConverter.d.ts +48 -0
- package/dist/utils/yamlConverter.js +98 -0
- package/dist/utilsController.js +65 -43
- package/package.json +19 -15
- package/src/collections/attributes.ts +3 -2
- package/src/collections/methods.ts +85 -51
- package/src/config/yamlConfig.ts +488 -0
- package/src/{migrations/setupDatabase.ts → databases/setup.ts} +11 -5
- package/src/functions/methods.ts +8 -4
- package/src/functions/templates/count-docs-in-collection/package.json +25 -0
- package/src/functions/templates/count-docs-in-collection/tsconfig.json +28 -0
- package/src/functions/templates/typescript-node/package.json +24 -0
- package/src/functions/templates/typescript-node/tsconfig.json +28 -0
- package/src/functions/templates/uv/README.md +31 -0
- package/src/functions/templates/uv/pyproject.toml +29 -0
- package/src/interactiveCLI.ts +226 -61
- package/src/main.ts +111 -37
- package/src/migrations/afterImportActions.ts +2 -2
- package/src/migrations/appwriteToX.ts +17 -4
- package/src/migrations/dataLoader.ts +4 -4
- package/src/migrations/importController.ts +30 -22
- package/src/migrations/importDataActions.ts +2 -2
- package/src/migrations/relationships.ts +1 -1
- package/src/migrations/services/DataTransformationService.ts +196 -0
- package/src/migrations/services/FileHandlerService.ts +311 -0
- package/src/migrations/services/ImportOrchestrator.ts +669 -0
- package/src/migrations/services/RateLimitManager.ts +363 -0
- package/src/migrations/services/RelationshipResolver.ts +461 -0
- package/src/migrations/services/UserMappingService.ts +345 -0
- package/src/migrations/services/ValidationService.ts +349 -0
- package/src/migrations/transfer.ts +22 -228
- package/src/migrations/yaml/YamlImportConfigLoader.ts +427 -0
- package/src/migrations/yaml/YamlImportIntegration.ts +419 -0
- package/src/migrations/yaml/generateImportSchemas.ts +589 -0
- package/src/shared/attributeManager.ts +429 -0
- package/src/shared/confirmationDialogs.ts +327 -0
- package/src/shared/functionManager.ts +515 -0
- package/src/shared/indexManager.ts +253 -0
- package/src/shared/jsonSchemaGenerator.ts +403 -0
- package/src/shared/logging.ts +74 -0
- package/src/shared/messageFormatter.ts +195 -0
- package/src/{migrations/migrationHelper.ts → shared/migrationHelpers.ts} +22 -4
- package/src/{migrations/helper.ts → shared/operationLogger.ts} +7 -2
- package/src/{migrations/queue.ts → shared/operationQueue.ts} +1 -1
- package/src/shared/progressManager.ts +278 -0
- package/src/{migrations/schemaStrings.ts → shared/schemaGenerator.ts} +71 -17
- package/src/storage/methods.ts +199 -78
- package/src/types.ts +2 -2
- package/src/{migrations/users.ts → users/methods.ts} +2 -2
- package/src/utils/configMigration.ts +349 -0
- package/src/utils/loadConfigs.ts +416 -52
- package/src/utils/schemaStrings.ts +2 -1
- package/src/utils/setupFiles.ts +742 -40
- package/src/{migrations → utils}/validationRules.ts +1 -1
- package/src/utils/yamlConverter.ts +131 -0
- package/src/utilsController.ts +75 -54
- package/src/functions/templates/poetry/README.md +0 -30
- package/src/functions/templates/poetry/pyproject.toml +0 -16
- package/src/migrations/attributes.ts +0 -561
- package/src/migrations/backup.ts +0 -205
- package/src/migrations/databases.ts +0 -39
- package/src/migrations/dbHelpers.ts +0 -92
- package/src/migrations/indexes.ts +0 -40
- package/src/migrations/logging.ts +0 -29
- package/src/migrations/storage.ts +0 -538
- /package/src/{migrations → functions}/openapi.ts +0 -0
- /package/src/functions/templates/{poetry → uv}/src/__init__.py +0 -0
- /package/src/functions/templates/{poetry → uv}/src/index.py +0 -0
- /package/src/{migrations/converters.ts → utils/dataConverters.ts} +0 -0
@@ -1,12 +1,14 @@
|
|
1
1
|
import { AppwriteException, ID, Query, } from "node-appwrite";
|
2
2
|
import { areCollectionNamesSame, tryAwaitWithRetry } from "../utils/index.js";
|
3
3
|
import { resolveAndUpdateRelationships } from "./relationships.js";
|
4
|
-
import { UsersController } from "
|
5
|
-
import { logger } from "
|
6
|
-
import { updateOperation } from "
|
7
|
-
import { BatchSchema, OperationCreateSchema, OperationSchema, } from "
|
4
|
+
import { UsersController } from "../users/methods.js";
|
5
|
+
import { logger } from "../shared/logging.js";
|
6
|
+
import { updateOperation } from "../shared/migrationHelpers.js";
|
7
|
+
import { BatchSchema, OperationCreateSchema, OperationSchema, } from "../storage/schemas.js";
|
8
8
|
import { DataLoader } from "./dataLoader.js";
|
9
9
|
import { transferDatabaseLocalToLocal, transferStorageLocalToLocal, } from "./transfer.js";
|
10
|
+
import { MessageFormatter } from "../shared/messageFormatter.js";
|
11
|
+
import { ProgressManager } from "../shared/progressManager.js";
|
10
12
|
export class ImportController {
|
11
13
|
config;
|
12
14
|
database;
|
@@ -43,12 +45,10 @@ export class ImportController {
|
|
43
45
|
let dataLoader;
|
44
46
|
let databaseRan;
|
45
47
|
for (let db of databasesToProcess) {
|
46
|
-
if (db.name.toLowerCase().trim().replace(" ", "") === "migrations") {
|
48
|
+
if (!this.config.useMigrations && db.name.toLowerCase().trim().replace(" ", "") === "migrations") {
|
47
49
|
continue;
|
48
50
|
}
|
49
|
-
|
50
|
-
console.log(`Starting import data for database: ${db.name}`);
|
51
|
-
console.log(`---------------------------------`);
|
51
|
+
MessageFormatter.banner(`Starting import data for database: ${db.name}`, "Database Import");
|
52
52
|
if (!databaseRan) {
|
53
53
|
databaseRan = db;
|
54
54
|
dataLoader = new DataLoader(this.appwriteFolderPath, this.importDataActions, this.database, this.config, this.setupOptions.shouldWriteFile);
|
@@ -172,10 +172,13 @@ export class ImportController {
|
|
172
172
|
// Skip further processing if no import operation is found
|
173
173
|
continue;
|
174
174
|
}
|
175
|
-
|
176
|
-
|
177
|
-
|
178
|
-
|
175
|
+
let importOperation = null;
|
176
|
+
if (this.config.useMigrations) {
|
177
|
+
importOperation = await this.database.getDocument("migrations", "currentOperations", importOperationId);
|
178
|
+
await updateOperation(this.database, importOperation.$id, {
|
179
|
+
status: "in_progress",
|
180
|
+
}, this.config.useMigrations);
|
181
|
+
}
|
179
182
|
const collectionData = dataLoader.importMap.get(dataLoader.getCollectionKey(collection.name));
|
180
183
|
console.log(`Processing collection: ${collection.name}...`);
|
181
184
|
if (!collectionData) {
|
@@ -212,14 +215,18 @@ export class ImportController {
|
|
212
215
|
// Wait for all promises in the current batch to resolve
|
213
216
|
await Promise.all(batchPromises);
|
214
217
|
console.log(`Completed batch ${i + 1} of ${dataSplit.length}`);
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
+
if (this.config.useMigrations && importOperation) {
|
219
|
+
await updateOperation(this.database, importOperation.$id, {
|
220
|
+
progress: processedItems,
|
221
|
+
}, this.config.useMigrations);
|
222
|
+
}
|
218
223
|
}
|
219
224
|
// After all batches are processed, update the operation status to completed
|
220
|
-
|
221
|
-
|
222
|
-
|
225
|
+
if (this.config.useMigrations && importOperation) {
|
226
|
+
await updateOperation(this.database, importOperation.$id, {
|
227
|
+
status: "completed",
|
228
|
+
}, this.config.useMigrations);
|
229
|
+
}
|
223
230
|
}
|
224
231
|
}
|
225
232
|
}
|
@@ -1,10 +1,10 @@
|
|
1
1
|
import {} from "node-appwrite";
|
2
2
|
import { validationRules, } from "appwrite-utils";
|
3
3
|
import { converterFunctions } from "appwrite-utils";
|
4
|
-
import { convertObjectBySchema } from "
|
4
|
+
import { convertObjectBySchema } from "../utils/dataConverters.js";
|
5
5
|
import {} from "appwrite-utils";
|
6
6
|
import { afterImportActions } from "./afterImportActions.js";
|
7
|
-
import { logger } from "
|
7
|
+
import { logger } from "../shared/logging.js";
|
8
8
|
import { tryAwaitWithRetry } from "../utils/helperFunctions.js";
|
9
9
|
export class ImportDataActions {
|
10
10
|
db;
|
@@ -1,2 +1,10 @@
|
|
1
1
|
import winston from "winston";
|
2
|
-
export
|
2
|
+
export interface LoggingConfig {
|
3
|
+
enabled: boolean;
|
4
|
+
level: string;
|
5
|
+
logDirectory?: string;
|
6
|
+
console: boolean;
|
7
|
+
}
|
8
|
+
export declare const configureLogging: (config?: Partial<LoggingConfig>) => void;
|
9
|
+
export declare let logger: winston.Logger;
|
10
|
+
export declare const updateLogger: () => void;
|
@@ -1,27 +1,46 @@
|
|
1
1
|
import winston from "winston";
|
2
2
|
import fs from "fs";
|
3
3
|
import path from "path";
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
}
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
4
|
+
const DEFAULT_LOGGING_CONFIG = {
|
5
|
+
enabled: false,
|
6
|
+
level: "info",
|
7
|
+
console: false,
|
8
|
+
};
|
9
|
+
let loggingConfig = DEFAULT_LOGGING_CONFIG;
|
10
|
+
export const configureLogging = (config = {}) => {
|
11
|
+
loggingConfig = { ...DEFAULT_LOGGING_CONFIG, ...config };
|
12
|
+
};
|
13
|
+
const createLogger = () => {
|
14
|
+
const transports = [];
|
15
|
+
// Add console transport if enabled
|
16
|
+
if (loggingConfig.console) {
|
17
|
+
transports.push(new winston.transports.Console({
|
18
|
+
format: winston.format.combine(winston.format.colorize(), winston.format.simple())
|
19
|
+
}));
|
20
|
+
}
|
21
|
+
// Add file transports if logging is enabled
|
22
|
+
if (loggingConfig.enabled) {
|
23
|
+
const logDir = loggingConfig.logDirectory || path.join(process.cwd(), "zlogs");
|
24
|
+
if (!fs.existsSync(logDir)) {
|
25
|
+
fs.mkdirSync(logDir, { recursive: true });
|
26
|
+
}
|
27
|
+
transports.push(new winston.transports.File({
|
15
28
|
filename: path.join(logDir, "error.log"),
|
16
29
|
level: "error",
|
17
|
-
}),
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
});
|
30
|
+
}), new winston.transports.File({
|
31
|
+
filename: path.join(logDir, "combined.log"),
|
32
|
+
}));
|
33
|
+
}
|
34
|
+
return winston.createLogger({
|
35
|
+
level: loggingConfig.level,
|
36
|
+
format: winston.format.combine(winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json()),
|
37
|
+
defaultMeta: { service: "appwrite-utils-cli" },
|
38
|
+
transports,
|
39
|
+
silent: !loggingConfig.enabled && !loggingConfig.console,
|
40
|
+
});
|
41
|
+
};
|
42
|
+
export let logger = createLogger();
|
43
|
+
// Recreate logger when config changes
|
44
|
+
export const updateLogger = () => {
|
45
|
+
logger = createLogger();
|
46
|
+
};
|
@@ -142,11 +142,11 @@ export type ContextObject = z.infer<typeof ContextObject>;
|
|
142
142
|
export declare const createOrFindAfterImportOperation: (database: Databases, collectionId: string, context: ContextObject) => Promise<void>;
|
143
143
|
export declare const addBatch: (database: Databases, data: string) => Promise<string>;
|
144
144
|
export declare const getAfterImportOperations: (database: Databases, collectionId: string) => Promise<{
|
145
|
+
status: "error" | "pending" | "ready" | "in_progress" | "completed" | "cancelled";
|
146
|
+
error: string;
|
145
147
|
$id: string;
|
146
148
|
$createdAt: string;
|
147
149
|
$updatedAt: string;
|
148
|
-
status: "error" | "pending" | "ready" | "in_progress" | "completed" | "cancelled";
|
149
|
-
error: string;
|
150
150
|
collectionId: string;
|
151
151
|
operationType: string;
|
152
152
|
progress: number;
|
@@ -155,11 +155,11 @@ export declare const getAfterImportOperations: (database: Databases, collectionI
|
|
155
155
|
batches?: string[] | undefined;
|
156
156
|
}[]>;
|
157
157
|
export declare const findOrCreateOperation: (database: Databases, collectionId: string, operationType: string, additionalQueries?: string[]) => Promise<{
|
158
|
+
status: "error" | "pending" | "ready" | "in_progress" | "completed" | "cancelled";
|
159
|
+
error: string;
|
158
160
|
$id: string;
|
159
161
|
$createdAt: string;
|
160
162
|
$updatedAt: string;
|
161
|
-
status: "error" | "pending" | "ready" | "in_progress" | "completed" | "cancelled";
|
162
|
-
error: string;
|
163
163
|
collectionId: string;
|
164
164
|
operationType: string;
|
165
165
|
progress: number;
|
@@ -1,6 +1,6 @@
|
|
1
1
|
import { Databases, Query } from "node-appwrite";
|
2
2
|
import { fetchAllCollections } from "../collections/methods.js";
|
3
|
-
import { logger } from "
|
3
|
+
import { logger } from "../shared/logging.js";
|
4
4
|
/**
|
5
5
|
* Finds collections that have defined relationship attributes.
|
6
6
|
*/
|
@@ -0,0 +1,55 @@
|
|
1
|
+
import type { AttributeMappings, ConfigDatabase, CollectionCreate } from "appwrite-utils";
|
2
|
+
import type { ImportDataActions } from "../importDataActions.js";
|
3
|
+
/**
|
4
|
+
* Service responsible for data transformation during import.
|
5
|
+
* Extracted from DataLoader to provide focused, testable transformation logic.
|
6
|
+
*/
|
7
|
+
export declare class DataTransformationService {
|
8
|
+
private importDataActions;
|
9
|
+
constructor(importDataActions: ImportDataActions);
|
10
|
+
/**
|
11
|
+
* Transforms the given item based on the provided attribute mappings.
|
12
|
+
* This method applies conversion rules to the item's attributes as defined in the attribute mappings.
|
13
|
+
*
|
14
|
+
* Preserves existing transformation logic from DataLoader.
|
15
|
+
*
|
16
|
+
* @param item - The item to be transformed.
|
17
|
+
* @param attributeMappings - The mappings that define how each attribute should be transformed.
|
18
|
+
* @returns The transformed item.
|
19
|
+
*/
|
20
|
+
transformData(item: any, attributeMappings: AttributeMappings): any;
|
21
|
+
/**
|
22
|
+
* Creates a context object for data transformation.
|
23
|
+
* Preserves existing context creation logic from DataLoader.
|
24
|
+
*
|
25
|
+
* @param db - The database configuration
|
26
|
+
* @param collection - The collection configuration
|
27
|
+
* @param item - The raw item data
|
28
|
+
* @param docId - The document ID
|
29
|
+
* @returns Context object for transformation
|
30
|
+
*/
|
31
|
+
createContext(db: ConfigDatabase, collection: CollectionCreate, item: any, docId: string): any;
|
32
|
+
/**
|
33
|
+
* Merges two objects by updating the source object with the target object's values.
|
34
|
+
* Preserves existing merge logic from DataLoader.
|
35
|
+
*
|
36
|
+
* It iterates through the target object's keys and updates the source object if:
|
37
|
+
* - The source object has the key.
|
38
|
+
* - The target object's value for that key is not null, undefined, or an empty string.
|
39
|
+
* - If the target object has an array value, it concatenates the values and removes duplicates.
|
40
|
+
*
|
41
|
+
* @param source - The source object to be updated.
|
42
|
+
* @param update - The target object with values to update the source object.
|
43
|
+
* @returns The updated source object.
|
44
|
+
*/
|
45
|
+
mergeObjects(source: any, update: any): any;
|
46
|
+
/**
|
47
|
+
* Validates the transformed data item using existing validation logic.
|
48
|
+
*
|
49
|
+
* @param transformedData - The transformed data to validate
|
50
|
+
* @param attributeMappings - The attribute mappings containing validation rules
|
51
|
+
* @param context - The context for validation
|
52
|
+
* @returns True if valid, false otherwise
|
53
|
+
*/
|
54
|
+
validateTransformedData(transformedData: any, attributeMappings: AttributeMappings, context: any): boolean;
|
55
|
+
}
|
@@ -0,0 +1,158 @@
|
|
1
|
+
import { convertObjectByAttributeMappings } from "../../utils/dataConverters.js";
|
2
|
+
import { logger } from "../../shared/logging.js";
|
3
|
+
/**
|
4
|
+
* Service responsible for data transformation during import.
|
5
|
+
* Extracted from DataLoader to provide focused, testable transformation logic.
|
6
|
+
*/
|
7
|
+
export class DataTransformationService {
|
8
|
+
importDataActions;
|
9
|
+
constructor(importDataActions) {
|
10
|
+
this.importDataActions = importDataActions;
|
11
|
+
}
|
12
|
+
/**
|
13
|
+
* Transforms the given item based on the provided attribute mappings.
|
14
|
+
* This method applies conversion rules to the item's attributes as defined in the attribute mappings.
|
15
|
+
*
|
16
|
+
* Preserves existing transformation logic from DataLoader.
|
17
|
+
*
|
18
|
+
* @param item - The item to be transformed.
|
19
|
+
* @param attributeMappings - The mappings that define how each attribute should be transformed.
|
20
|
+
* @returns The transformed item.
|
21
|
+
*/
|
22
|
+
transformData(item, attributeMappings) {
|
23
|
+
try {
|
24
|
+
// Convert the item using the attribute mappings provided
|
25
|
+
const convertedItem = convertObjectByAttributeMappings(item, attributeMappings);
|
26
|
+
// Run additional converter functions on the converted item, if any
|
27
|
+
return this.importDataActions.runConverterFunctions(convertedItem, attributeMappings);
|
28
|
+
}
|
29
|
+
catch (error) {
|
30
|
+
logger.error(`Error transforming data for item: ${JSON.stringify(item, null, 2)}`, error);
|
31
|
+
throw error;
|
32
|
+
}
|
33
|
+
}
|
34
|
+
/**
|
35
|
+
* Creates a context object for data transformation.
|
36
|
+
* Preserves existing context creation logic from DataLoader.
|
37
|
+
*
|
38
|
+
* @param db - The database configuration
|
39
|
+
* @param collection - The collection configuration
|
40
|
+
* @param item - The raw item data
|
41
|
+
* @param docId - The document ID
|
42
|
+
* @returns Context object for transformation
|
43
|
+
*/
|
44
|
+
createContext(db, collection, item, docId) {
|
45
|
+
return {
|
46
|
+
...item, // Spread the item data for easy access to its properties
|
47
|
+
dbId: db.$id,
|
48
|
+
dbName: db.name,
|
49
|
+
collId: collection.$id,
|
50
|
+
collName: collection.name,
|
51
|
+
docId: docId,
|
52
|
+
createdDoc: {}, // Initially empty, to be updated when the document is created
|
53
|
+
};
|
54
|
+
}
|
55
|
+
/**
|
56
|
+
* Merges two objects by updating the source object with the target object's values.
|
57
|
+
* Preserves existing merge logic from DataLoader.
|
58
|
+
*
|
59
|
+
* It iterates through the target object's keys and updates the source object if:
|
60
|
+
* - The source object has the key.
|
61
|
+
* - The target object's value for that key is not null, undefined, or an empty string.
|
62
|
+
* - If the target object has an array value, it concatenates the values and removes duplicates.
|
63
|
+
*
|
64
|
+
* @param source - The source object to be updated.
|
65
|
+
* @param update - The target object with values to update the source object.
|
66
|
+
* @returns The updated source object.
|
67
|
+
*/
|
68
|
+
mergeObjects(source, update) {
|
69
|
+
// Create a new object to hold the merged result
|
70
|
+
const result = { ...source };
|
71
|
+
// Loop through the keys of the object we care about
|
72
|
+
for (const [key, value] of Object.entries(source)) {
|
73
|
+
// Check if the key exists in the target object
|
74
|
+
if (!Object.hasOwn(update, key)) {
|
75
|
+
// If the key doesn't exist, we can just skip it
|
76
|
+
continue;
|
77
|
+
}
|
78
|
+
if (update[key] === value) {
|
79
|
+
continue;
|
80
|
+
}
|
81
|
+
// If the value ain't here, we can just do whatever man
|
82
|
+
if (value === undefined || value === null || value === "") {
|
83
|
+
// If the update key is defined
|
84
|
+
if (update[key] !== undefined &&
|
85
|
+
update[key] !== null &&
|
86
|
+
update[key] !== "") {
|
87
|
+
// might as well use it eh?
|
88
|
+
result[key] = update[key];
|
89
|
+
}
|
90
|
+
// ELSE if the value is an array, because it would then not be === to those things above
|
91
|
+
}
|
92
|
+
else if (Array.isArray(value)) {
|
93
|
+
// Get the update value
|
94
|
+
const updateValue = update[key];
|
95
|
+
// If the update value is an array, concatenate and remove duplicates
|
96
|
+
// and poopy data
|
97
|
+
if (Array.isArray(updateValue)) {
|
98
|
+
result[key] = [...new Set([...value, ...updateValue])].filter((item) => item !== null && item !== undefined && item !== "");
|
99
|
+
}
|
100
|
+
else {
|
101
|
+
// If the update value is not an array, just use it
|
102
|
+
result[key] = [...value, updateValue].filter((item) => item !== null && item !== undefined && item !== "");
|
103
|
+
}
|
104
|
+
}
|
105
|
+
else if (typeof value === "object" && !Array.isArray(value)) {
|
106
|
+
// If the value is an object, we need to merge it
|
107
|
+
if (typeof update[key] === "object" && !Array.isArray(update[key])) {
|
108
|
+
result[key] = this.mergeObjects(value, update[key]);
|
109
|
+
}
|
110
|
+
}
|
111
|
+
else {
|
112
|
+
// Finally, the source value is defined, and not an array, so we don't care about the update value
|
113
|
+
continue;
|
114
|
+
}
|
115
|
+
}
|
116
|
+
// Because the objects should technically always be validated FIRST, we can assume the update keys are also defined on the source object
|
117
|
+
for (const [key, value] of Object.entries(update)) {
|
118
|
+
if (value === undefined || value === null || value === "") {
|
119
|
+
continue;
|
120
|
+
}
|
121
|
+
else if (!Object.hasOwn(source, key)) {
|
122
|
+
result[key] = value;
|
123
|
+
}
|
124
|
+
else if (typeof source[key] === "object" &&
|
125
|
+
typeof value === "object" &&
|
126
|
+
!Array.isArray(source[key]) &&
|
127
|
+
!Array.isArray(value)) {
|
128
|
+
result[key] = this.mergeObjects(source[key], value);
|
129
|
+
}
|
130
|
+
else if (Array.isArray(source[key]) && Array.isArray(value)) {
|
131
|
+
result[key] = [...new Set([...source[key], ...value])].filter((item) => item !== null && item !== undefined && item !== "");
|
132
|
+
}
|
133
|
+
else if (source[key] === undefined ||
|
134
|
+
source[key] === null ||
|
135
|
+
source[key] === "") {
|
136
|
+
result[key] = value;
|
137
|
+
}
|
138
|
+
}
|
139
|
+
return result;
|
140
|
+
}
|
141
|
+
/**
|
142
|
+
* Validates the transformed data item using existing validation logic.
|
143
|
+
*
|
144
|
+
* @param transformedData - The transformed data to validate
|
145
|
+
* @param attributeMappings - The attribute mappings containing validation rules
|
146
|
+
* @param context - The context for validation
|
147
|
+
* @returns True if valid, false otherwise
|
148
|
+
*/
|
149
|
+
validateTransformedData(transformedData, attributeMappings, context) {
|
150
|
+
try {
|
151
|
+
return this.importDataActions.validateItem(transformedData, attributeMappings, context);
|
152
|
+
}
|
153
|
+
catch (error) {
|
154
|
+
logger.error(`Validation error for transformed data: ${JSON.stringify(transformedData, null, 2)}`, error);
|
155
|
+
return false;
|
156
|
+
}
|
157
|
+
}
|
158
|
+
}
|
@@ -0,0 +1,75 @@
|
|
1
|
+
import type { AttributeMappings, AppwriteConfig } from "appwrite-utils";
|
2
|
+
import type { ImportDataActions } from "../importDataActions.js";
|
3
|
+
import { RateLimitManager } from "./RateLimitManager.js";
|
4
|
+
/**
|
5
|
+
* Service responsible for file handling during import.
|
6
|
+
* Preserves all existing file handling capabilities including URL support.
|
7
|
+
* Extracted from DataLoader to provide focused, testable file operations.
|
8
|
+
*/
|
9
|
+
export declare class FileHandlerService {
|
10
|
+
private appwriteFolderPath;
|
11
|
+
private config;
|
12
|
+
private importDataActions;
|
13
|
+
private rateLimitManager;
|
14
|
+
constructor(appwriteFolderPath: string, config: AppwriteConfig, importDataActions: ImportDataActions, rateLimitManager?: RateLimitManager);
|
15
|
+
/**
|
16
|
+
* Generates attribute mappings with post-import actions based on the provided attribute mappings.
|
17
|
+
* This method checks each mapping for a fileData attribute and adds a post-import action to create a file
|
18
|
+
* and update the field with the file's ID if necessary.
|
19
|
+
*
|
20
|
+
* Preserves existing file handling logic from DataLoader.
|
21
|
+
*
|
22
|
+
* @param attributeMappings - The attribute mappings from the import definition.
|
23
|
+
* @param context - The context object containing information about the database, collection, and document.
|
24
|
+
* @param item - The item being imported, used for resolving template paths in fileData mappings.
|
25
|
+
* @returns The attribute mappings updated with any necessary post-import actions.
|
26
|
+
*/
|
27
|
+
getAttributeMappingsWithFileActions(attributeMappings: AttributeMappings, context: any, item: any): AttributeMappings;
|
28
|
+
/**
|
29
|
+
* Resolves local file path, searching in subdirectories if needed.
|
30
|
+
* Preserves existing file search logic from DataLoader.
|
31
|
+
*
|
32
|
+
* @param mappingFilePath - The relative file path from the mapping
|
33
|
+
* @returns Resolved absolute file path
|
34
|
+
*/
|
35
|
+
private resolveLocalFilePath;
|
36
|
+
/**
|
37
|
+
* Executes file-related post-import actions with rate limiting.
|
38
|
+
* Wraps the existing createFileAndUpdateField action with proper error handling and rate limiting.
|
39
|
+
*
|
40
|
+
* @param context - The context containing document and collection information
|
41
|
+
* @param postImportActions - The post-import actions to execute
|
42
|
+
*/
|
43
|
+
executeFileActions(context: any, postImportActions: any[]): Promise<void>;
|
44
|
+
/**
|
45
|
+
* Executes a single file action with proper error handling.
|
46
|
+
*
|
47
|
+
* @param action - The file action to execute
|
48
|
+
* @param context - The context for template resolution
|
49
|
+
*/
|
50
|
+
private executeFileAction;
|
51
|
+
/**
|
52
|
+
* Validates that file paths exist before import begins.
|
53
|
+
* Provides early validation to catch file issues before processing starts.
|
54
|
+
*
|
55
|
+
* @param attributeMappings - The attribute mappings to validate
|
56
|
+
* @param context - The context for template resolution
|
57
|
+
* @param item - The item for template resolution
|
58
|
+
* @returns Array of validation errors (empty if all valid)
|
59
|
+
*/
|
60
|
+
validateFilePaths(attributeMappings: AttributeMappings, context: any, item: any): string[];
|
61
|
+
/**
|
62
|
+
* Gets file statistics for import planning.
|
63
|
+
* Helps estimate import time and resource requirements.
|
64
|
+
*
|
65
|
+
* @param attributeMappings - The attribute mappings to analyze
|
66
|
+
* @param items - The items that will be imported
|
67
|
+
* @returns File statistics object
|
68
|
+
*/
|
69
|
+
getFileStatistics(attributeMappings: AttributeMappings, items: any[]): {
|
70
|
+
totalFiles: number;
|
71
|
+
urlFiles: number;
|
72
|
+
localFiles: number;
|
73
|
+
estimatedSize: number;
|
74
|
+
};
|
75
|
+
}
|