All files / src/decorators api.decorator.ts

82.92% Statements 34/41
78.12% Branches 25/32
92.3% Functions 12/13
88.57% Lines 31/35

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  7x 91x 91x 90x 1x 182x 91x     7x 7x   7x 7x 7x 7x 7x 7x   245x 245x 245x 91x   91x 91x 91x 91x 91x     1x 1x 1x       1x                              
import HttpStatusCode from '@/utils/HTTPStatusCodes';
import { APIError, ApiResponseBody, ResponseHandler } from '@/utils/responseHandler';
import { logger } from '@/utils/winston';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';

export function apiMethod<T>() {
  return function (_: any, __: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = async function (...args: any[]) {
      const resBody = new ApiResponseBody<T>();
      try {
        const getResBody = () => resBody;
        (this as any).getResBody = getResBody;
 
        return await originalMethod.apply(this, args);
      } catch (err) {
        logger.error(err);
        if (err instanceof PrismaClientKnownRequestError) {
          if (
            err.code === 'P2002' &&
            err.meta?.target &&
            Array.isArray(err.meta.target) &&
            err.meta.target.includes('email')
          ) {
            resBody.error = {
              code: HttpStatusCode.CONFLICT,
              message: 'Email already exists',
            };
          } else {
            resBody.error = {
              code: HttpStatusCode.INTERNAL_SERVER_ERROR,
              message: String(err),
            };
          }
        } else if (err instanceof APIError) {
          resBody.error = {
            code: err.code,
            message: err.message,
          };
        } else {
          resBody.error = {
            code: HttpStatusCode.INTERNAL_SERVER_ERROR,
            message: String(err),
          };E
        }
      } finally {
        delete (this as any).getResBody;
      }
      return resBody;
    };
    return descriptor;E
  };
}