All files / api/routes baseFormHandler.ts

100% Statements 184/184
95.83% Branches 23/24
100% Functions 1/1
100% Lines 184/184

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 1851x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 3x 9x 2x 2x 2x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import Koa from 'koa';
 
import { hasCaptcha } from '@api/guard/hasCaptcha';
import { errorResponse } from '@api/misc/httpResponse/errorResponse';
import { successResponse } from '@api/misc/httpResponse/successResponse';
import { IApiModule, IRecordRequirements } from '@api/types/baseModule';
import { ApiStatusErrorCode } from '@constants/api';
import { ApprovalStatus, colourFromApprovalStatus } from '@constants/enum/approvalStatus';
import { FormDataKey } from '@constants/form';
import { IFormResponse } from '@contracts/response/formResponse';
import {
  baseSubmissionMessageBuilder,
  baseSubmissionMessageEmbed,
  getDescriptionLines,
} from '@helpers/discordMessageHelper';
import { uuidv4 } from '@helpers/guidHelper';
import { anyObject } from '@helpers/typescriptHacks';
import { getDiscordService } from '@services/external/discord/discordService';
import { getConfig } from '@services/internal/configService';
import { getLog } from '@services/internal/logService';
import { validateObj } from '@validation/baseValidation';
 
export const baseFormHandler =
  <TD, TF, TP>(module: IApiModule<TD, TF, TP>) =>
  async (ctx: Koa.DefaultContext, next: () => Promise<Koa.BaseResponse>) => {
    const handlerName = `formHandler-${module.segment}-${uuidv4()}`;
    getLog().i(handlerName);
 
    const formDataFiles = ctx.request?.files ?? anyObject;
    const formDataBody = ctx.request?.body ?? anyObject;
 
    const isCaptchaEnabled = getConfig().getCaptchaEnabled();
    if (isCaptchaEnabled === true) {
      const captchaString = formDataBody[FormDataKey.captcha];
      const captchaTest = hasCaptcha(captchaString);
      const captchaIsValid = await captchaTest(ctx, next);
      if (captchaIsValid === false) {
        const errMsg = `${handlerName} - Captcha test: could not verify result`;
        getLog().i(errMsg);
        await errorResponse({
          ctx,
          next,
          statusCode: ApiStatusErrorCode.badCaptcha.code,
          message: errMsg,
        });
        return;
      }
    }
 
    const fileObjResult = await module.handleFilesInFormData(formDataFiles);
    if (fileObjResult.isSuccess === false) {
      const errMsg = `${handlerName} - handle files: ${fileObjResult.errorMessage}`;
      getLog().e(errMsg);
      await errorResponse({
        ctx,
        next,
        statusCode: ApiStatusErrorCode.invalidFormFiles.code,
        message: errMsg,
      });
      return;
    }
 
    let data: TD = anyObject;
    try {
      const dataString = formDataBody[FormDataKey.data];
      data = JSON.parse(dataString);
    } catch (ex) {
      const errMsg = `${handlerName} - formData mapping: ${ex?.toString?.()}`;
      getLog().e(errMsg);
      await errorResponse({
        ctx,
        next,
        statusCode: ApiStatusErrorCode.invalidFormData.code,
        message: errMsg,
      });
      return;
    }
 
    const failedValidationMsgs = validateObj<TD>({
      data: data,
      validationObj: module.dtoMeta,
    }).filter((v) => v.isValid === false);
 
    if (failedValidationMsgs.length > 0) {
      getLog().e(`${handlerName} - Validation failed. Num errors ${failedValidationMsgs.length}`);
      await errorResponse({
        ctx,
        next,
        statusCode: ApiStatusErrorCode.validation.code,
        message: `Validation failed: ${failedValidationMsgs.map((v) => v.errorMessage).join(',\n')}`,
      });
      return;
    }
 
    const persistence = module.mapDtoWithImageToPersistence(data, fileObjResult.value);
    const createdRecordResult = await module.createRecord(persistence);
    if (createdRecordResult.isSuccess == false) {
      const errMsg = `${handlerName} - create db record - ${createdRecordResult.errorMessage}`;
      getLog().e(errMsg);
      await errorResponse({
        ctx,
        next,
        statusCode: ApiStatusErrorCode.couldNotPersistData.code,
        message: errMsg,
      });
      return;
    }
 
    if (module.createRecordRelationships != null) {
      const createRelationshipsResult = await module.createRecordRelationships(
        data,
        createdRecordResult.value,
      );
      if (createRelationshipsResult.isSuccess == false) {
        const errMsg = `${handlerName} - create db record relationships - ${createRelationshipsResult.errorMessage}`;
        getLog().e(errMsg);
        await errorResponse({
          ctx,
          next,
          statusCode: ApiStatusErrorCode.couldNotPersistData.code,
          message: errMsg,
        });
        return;
      }
    }
 
    const persistenceWithImgUrls = module.getPublicUrlsOfUploads(createdRecordResult.value);
    const authorName = module.getName(persistenceWithImgUrls);
    const iconUrl = module.getIcon?.(persistenceWithImgUrls);
    const msgColour = colourFromApprovalStatus(ApprovalStatus.pending);
 
    const formResult: IFormResponse = {
      id: createdRecordResult.value.id,
      name: authorName,
      iconUrl: iconUrl ?? undefined,
    };
 
    const tempDto = module.mapPersistenceToDto(persistenceWithImgUrls);
    let dtoForDiscord = { ...tempDto };
    if (module.mapRecordRelationshipsToDto != null) {
      const dtoResult = await module.mapRecordRelationshipsToDto(
        persistenceWithImgUrls.id,
        tempDto,
      );
      dtoForDiscord = dtoResult.value;
    }
 
    if (module.sendDiscordMessageOnSubmission != true) {
      await successResponse({ ctx, body: formResult, next });
      return;
    }
 
    const discordUrl = getConfig().getDiscordWebhookUrl();
    const webhookPayload = baseSubmissionMessageBuilder({
      content: '',
      authorName: authorName,
      iconUrl: iconUrl ?? undefined,
      colour: msgColour,
      descripLines: await getDescriptionLines({
        data: dtoForDiscord,
        dtoMeta: module.dtoMeta,
      }),
      additionalEmbeds: [
        baseSubmissionMessageEmbed(
          createdRecordResult.value.id,
          module.calculateCheck(createdRecordResult.value),
          module.segment,
        ),
      ],
    });
    const discordResponse = await getDiscordService().sendDiscordMessage(
      discordUrl,
      webhookPayload,
    );
    if (discordResponse.isSuccess) {
      await module.updateRecord(createdRecordResult.value.id, {
        ...persistenceWithImgUrls,
        id: createdRecordResult.value.id,
        discordWebhookId: discordResponse.value.id,
      } as TP & IRecordRequirements);
    }
 
    await successResponse({ ctx, body: formResult, next });
  };