All files / api/facade handleImageFromFormData.ts

18.18% Statements 10/55
100% Branches 0/0
0% Functions 0/1
18.18% Lines 10/55

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 561x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                            
import { IFile } from '@contracts/file';
import { ResultWithValue } from '@contracts/resultWithValue';
import { getImageProcessingService } from '@services/internal/imageProcessingService';
import { getLog } from '@services/internal/logService';
import { IImageRestriction, apiFileUploadRestriction } from '@validation/imageValidation';
import { processImageFromFormData } from './processImage';
import { IDatabaseFile } from '@contracts/databaseFile';
import { anyObject } from '@helpers/typescriptHacks';
 
export const handleImageFromFormData = async (props: {
  fileFromForm: IFile;
  restrictions: IImageRestriction;
  fileName: string;
  handlerName: string;
  width?: number;
  height?: number;
}): Promise<ResultWithValue<IDatabaseFile>> => {
  const imageMetaResult = await getImageProcessingService().getMetaData({
    input: props.fileFromForm.filepath,
  });
  const restriction = apiFileUploadRestriction(props.restrictions, props.fileName);
  const validationResult = restriction(imageMetaResult.value);
  if (validationResult.isValid === false) {
    getLog().w(
      `${props.handlerName} ${props.fileName} validation: `,
      validationResult.errorMessage,
    );
    return {
      isSuccess: false,
      value: anyObject,
      errorMessage: validationResult.errorMessage ?? 'validation failed',
    };
  }

  const resizedPicResult = await processImageFromFormData({
    fileFromForm: props.fileFromForm,
    handlerName: props.handlerName,
    width: props.width,
    height: props.height,
  });
  if (resizedPicResult.isSuccess == false) {
    getLog().e(`${props.handlerName} ${props.fileName} resize: `, resizedPicResult.value);
    return {
      isSuccess: false,
      value: anyObject,
      errorMessage: resizedPicResult.errorMessage,
    };
  }

  return {
    isSuccess: true,
    value: resizedPicResult.value,
    errorMessage: '',
  };
};