gradido/core/src/command/CommandExecutor.ts
clauspeterhuebner 3ce4b92d0f linting
2026-02-19 02:30:53 +01:00

78 lines
3.0 KiB
TypeScript

// core/src/command/CommandExecutor.ts
import { getLogger } from 'log4js'
import { CommandJwtPayloadType } from 'shared'
import { LOG4JS_BASE_CATEGORY_NAME } from '../config/const'
import { interpretEncryptedTransferArgs } from '../graphql/logic/interpretEncryptedTransferArgs'
import { CommandResult } from '../graphql/model/CommandResult'
import { EncryptedTransferArgs } from '../graphql/model/EncryptedTransferArgs'
import { Command } from './Command'
import { CommandFactory } from './CommandFactory'
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`)
methodLogger.debug(`executeCommand() command=${command.constructor.name}`)
try {
if (command.validate && !command.validate()) {
const errmsg = `Command validation failed for command=${command.constructor.name}`
methodLogger.error(errmsg)
return { success: false, error: errmsg }
}
methodLogger.debug(`executeCommand() executing command=${command.constructor.name}`)
const result = await command.execute()
methodLogger.debug(`executeCommand() executed result=${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.commandArgs,
)
if (methodLogger.isDebugEnabled()) {
methodLogger.debug(`executeEncryptedCommand() command=${JSON.stringify(command)}`)
}
// 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
}
}
}