All files / src/Batch MailstepUnsubscribeWebhooksBatch.ts

90.9% Statements 20/22
75% Branches 3/4
100% Functions 2/2
90.9% Lines 20/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 6022x   22x 22x   22x   22x 22x   22x   22x     22x       2x 2x 2x       2x         2x 1x             1x   1x                     1x 1x     2x        
import Webhook from '@orchesty/nodejs-sdk/dist/lib/Application/Database/Webhook';
import { IWebhookQueryFilter } from '@orchesty/nodejs-sdk/dist/lib/Application/Database/WebhookRepository';
import ABatchNode from '@orchesty/nodejs-sdk/dist/lib/Batch/ABatchNode';
import OnRepeatException from '@orchesty/nodejs-sdk/dist/lib/Exception/OnRepeatException';
import { IPaging, ISorter } from '@orchesty/nodejs-sdk/dist/lib/Storage/Database/Repository';
import { HttpMethods } from '@orchesty/nodejs-sdk/dist/lib/Transport/HttpMethods';
import BatchProcessDto from '@orchesty/nodejs-sdk/dist/lib/Utils/BatchProcessDto';
import { StatusCodes } from 'http-status-codes';
import MailstepApplication, { NAME as APPLICATION_NAME } from '../MailstepApplication';
 
export const NAME = `${APPLICATION_NAME}-unsubscribe-webhooks-batch`;
 
export default class MailstepUnsubscribeWebhooksBatch extends ABatchNode {
 
    public getName(): string {
        return NAME;
    }
 
    public async processAction(dto: BatchProcessDto): Promise<BatchProcessDto> {
        const application = this.getApplication<MailstepApplication>();
        const applicationInstall = await this.getApplicationInstallFromProcess(dto, null);
        const webhookRepository = this
            .getDbClient()
            .getRepository<Webhook, IWebhookQueryFilter, ISorter, IPaging>(Webhook);
 
        const subscribedWebhook = await webhookRepository.findOne({
            users: [applicationInstall.getUser()],
            apps: [applicationInstall.getName()],
        });
 
        if (subscribedWebhook) {
            const requestDto = await application.getRequestDto(
                dto,
                applicationInstall,
                HttpMethods.DELETE,
                `eshop-webhook/${subscribedWebhook.getWebhookId()}`,
            );
 
            const responseDto = await this.getSender().send(requestDto);
 
            Iif (![
                StatusCodes.OK,
                StatusCodes.NO_CONTENT,
                StatusCodes.NOT_FOUND,
                StatusCodes.GONE,
            ].includes(responseDto.getResponseCode())) {
                await webhookRepository.update(subscribedWebhook.setUnsubscribeFailed(true));
 
                throw new OnRepeatException(300, 12, responseDto.getBody());
            }
 
            await webhookRepository.remove(subscribedWebhook);
            dto.setBatchCursor('1', true);
        }
 
        return dto;
    }
 
}