Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.3 kB
5
Indexable
Never
import Container from 'typedi';
import { env } from '../../env';
import { PolicyType } from '../../api/interface/internal/PolicyData';
import { toStageHistoryMapper } from '../dataMappers/entity/ApplicationMapper';
import { StageHistoryRepository } from '../../api/repository/StageHistoryRepository';
import { Logger, LoggerInterface } from '@enbdleap/node-logger';

export const StageAndStatusAudit = (policyType: PolicyType) => {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        const originalMethod = descriptor.value;

        const log: LoggerInterface = new Logger(__filename);
        descriptor.value = async function (...args: any[]) {
            const application = args[0];
            let stageHistory;
            if (env.apis.common.stageHistoryAudit.enabled &&
                application &&
                (application.stage !== application.prevStage || application.status !== application.prevStatus)) {
                stageHistory = toStageHistoryMapper(application);
            }

            // Execute the original method and handle the promise chain
            return new Promise((resolve, reject) => {
                originalMethod.apply(this, args)
                    .then((result: any) => {
                        if (result && stageHistory) {
                            Container.get(StageHistoryRepository).getRepository(policyType)?.save(stageHistory)
                                .then(() => resolve(result))
                                .catch((saveError: any) => {
                                    log.error(`Error while saving history of ${policyType} for origination Id : ${application.originationId}`, saveError);
                                    resolve(result); // Continue without failing the main operation
                                });
                        } else {
                            resolve(result);
                        }
                    })
                    .catch((error: any) => {
                        log.error(`Error in original method execution for ${policyType} for origination Id : ${application.originationId}`, error);
                        reject(error);
                    });
            });
        };
        return descriptor;
    };
};
Leave a Comment