All files / services/internal imageProcessingService.ts

100% Statements 70/70
100% Branches 7/7
100% Functions 4/4
100% Lines 70/70

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 711x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 3x 3x 3x 3x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 3x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 4x 1x 1x  
import sharp, { ResizeOptions } from 'sharp';
import { Container, Service } from 'typedi';
 
import {
  IImageMetaDataProps,
  IImageProcessingOutputProps,
  IImageProcessingProps,
} from '@contracts/image';
import { ResultWithValue } from '@contracts/resultWithValue';
import { anyObject } from '@helpers/typescriptHacks';
 
@Service()
export class ImageProcessingService {
  getMetaData = async (
    props: IImageProcessingProps,
  ): Promise<ResultWithValue<IImageMetaDataProps>> => {
    try {
      const metadata = await sharp(props.input).metadata();
      return {
        isSuccess: true,
        value: metadata,
        errorMessage: '',
      };
    } catch (ex) {
      return {
        isSuccess: false,
        errorMessage: `Image metadata failed, ${ex?.toString?.()}`,
        value: anyObject,
      };
    }
  };
 
  resize = async (
    props: IImageProcessingProps & {
      output?: IImageProcessingOutputProps;
      resize: ResizeOptions;
    },
  ): Promise<ResultWithValue<Buffer>> => {
    const { input, output, resize } = props;
 
    let sharpTasks = sharp(input);
    if (resize.fit == null) resize.fit = 'outside';
    if (resize.position == null) resize.position = 'centre';
    sharpTasks = sharpTasks.resize({ ...resize });
 
    if (output?.outputType != null) {
      sharpTasks = sharpTasks.toFormat(output.outputType);
    }
 
    try {
      const result = await sharpTasks
        .withExif({}) // remove exif and metadata
        .withMetadata({})
        .toBuffer();
      return {
        isSuccess: true,
        value: result,
        errorMessage: '',
      };
    } catch (ex) {
      return {
        isSuccess: false,
        errorMessage: `Image resize failed, ${ex?.toString?.()}`,
        value: anyObject,
      };
    }
  };
}
 
export const getImageProcessingService = () => Container.get(ImageProcessingService);