Untitled

mail@pastecode.io avatar
unknown
plain_text
23 days ago
1.7 kB
3
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];
            try {
                let stageHistory;
                if (env.apis.common.stageHistoryAudit.enabled
                    && application
                    && (application.stage !== application.prevStage || application.status !== application.prevStatus)) {
                    stageHistory = toStageHistoryMapper(application);
                }

                // Execute the behavior originally programmed in
                const result = await originalMethod.apply(this, args);
                // then do the auditing if applicable
                if (result && stageHistory) {
                    await Container.get(StageHistoryRepository).getRepository(policyType)?.save(stageHistory);
                }
                return result;
            } catch (error) {
                log.error(`Error while persisting history of ${policyType} for origination Id : ${application.originationId}`);
            };
        };
        return descriptor;
    };
};
Leave a Comment