gradido/core/src/command/CommandExecutor.ts
2026-01-27 02:10:57 +01:00

69 lines
2.8 KiB
TypeScript

// core/src/command/CommandExecutor.ts
import { CommandJwtPayloadType } from 'shared';
import { interpretEncryptedTransferArgs } from '../graphql/logic/interpretEncryptedTransferArgs';
import { EncryptedTransferArgs } from '../graphql/model/EncryptedTransferArgs';
import { BaseCommand } from './BaseCommand';
import { Command } from './Command';
import { getLogger } from 'log4js';
import { LOG4JS_BASE_CATEGORY_NAME } from '../config/const';
import { CommandFactory } from './CommandFactory';
import { CommandResult } from '../graphql/model/CommandResult';
const createLogger = (method: string) =>
getLogger(`${LOG4JS_BASE_CATEGORY_NAME}.command.CommandExecutor.${method}`)
export class CommandExecutor {
async executeCommand<T>(command: Command<T>): Promise<CommandResult> {
const methodLogger = createLogger(`executeCommand`)
try {
if (command.validate && !command.validate()) {
return { success: false, error: 'Command validation failed' };
}
methodLogger.debug(`executeCommand() executing command=${command.constructor.name}`)
const result = await command.execute();
methodLogger.debug(`executeCommand() executed result=${JSON.stringify(result)}`)
return { success: true, data: result };
} catch (error) {
methodLogger.error(`executeCommand() error=${error}`)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}
async executeEncryptedCommand<T>(
encryptedArgs: EncryptedTransferArgs
): Promise<CommandResult> {
const methodLogger = createLogger(`executeEncryptedCommand`)
try {
// Decrypt the command data
const commandArgs = (await interpretEncryptedTransferArgs(encryptedArgs)) as CommandJwtPayloadType
if (!commandArgs) {
const errmsg = `invalid commandArgs payload of requesting community with publicKey=${encryptedArgs.publicKey}`
methodLogger.error(errmsg)
throw new Error(errmsg)
}
if (methodLogger.isDebugEnabled()) {
methodLogger.debug(`executeEncryptedCommand() commandArgs=${JSON.stringify(commandArgs)}`)
}
const command = CommandFactory.getInstance().createCommand(commandArgs.commandName, commandArgs.params);
// Execute the command
const result = await this.executeCommand(command);
if (methodLogger.isDebugEnabled()) {
methodLogger.debug(`executeCommand() result=${JSON.stringify(result)}`)
}
return result
} catch (error) {
methodLogger.error(`executeEncryptedCommand() error=${error}`)
const errorResult: CommandResult = {
success: false,
error: error instanceof Error ? error.message : 'Failed to process command'
};
return errorResult;
}
}
}