41 lines
1.3 KiB
TypeScript
Raw Normal View History

import { Injectable } from "@nestjs/common";
import { getErrorMessage } from "@bff/core/utils/error.util";
import { SimNotificationService } from "./sim-notification.service";
import type { SimNotificationContext } from "../interfaces/sim-base.interface";
interface RunOptions<T> {
baseContext: SimNotificationContext;
enrichSuccess?: (result: T) => Partial<SimNotificationContext>;
enrichError?: (error: unknown) => Partial<SimNotificationContext>;
}
@Injectable()
export class SimActionRunnerService {
constructor(private readonly simNotification: SimNotificationService) {}
async run<T>(
action: string,
options: RunOptions<T>,
handler: () => Promise<T>
): Promise<T> {
try {
const result = await handler();
const successContext = {
...options.baseContext,
...(options.enrichSuccess ? options.enrichSuccess(result) : {}),
};
await this.simNotification.notifySimAction(action, "SUCCESS", successContext);
return result;
} catch (error) {
const errorContext = {
...options.baseContext,
error: getErrorMessage(error),
...(options.enrichError ? options.enrichError(error) : {}),
};
await this.simNotification.notifySimAction(action, "ERROR", errorContext);
throw error;
}
}
}