All files / packages/services/src effectRequest.ts

95.52% Statements 64/67
91.52% Branches 54/59
100% Functions 11/11
100% Lines 59/59

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 1842x       2x             2x                     3x       1x     5x                                     2x 20x                 2x 16x   16x 1x     15x 13x 13x 13x       2x     2x     1x   1x 1x 2x     1x     2x 6x   6x 5x 5x             1x     12x 20x 16x 16x 16x   16x       3x     13x 2x     11x       2x     9x 1x             8x     4x 2x     2x     13x       15x 18x       15x 9x 9x       1x         15x 5x     6x         15x     2x       2x    
import { Effect } from "effect";
 
import type { ApiErrorBody, HttpError } from "@repo/types/http";
 
import { createError, type DomainError } from "@repo/effect-utils";
 
export interface EffectRequestPolicy {
  timeoutMs?: number;
  retries?: number;
}
 
export const HTTP_STATUS_CODE = {
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  REQUEST_TIMEOUT: 408,
  TOO_MANY_REQUESTS: 429,
  UNPROCESSABLE_ENTITY: 422,
  INTERNAL_SERVER_ERROR: 500,
  GATEWAY_TIMEOUT: 504,
} as const;
 
export const API_ERROR_TEXT = {
  REQUEST_FAILED: "Request failed",
  UNKNOWN_ERROR: "Unknown error",
  requestTimedOut: (timeoutMs: number) =>
    `Request timed out after ${timeoutMs}ms`,
} as const;
 
export const REQUEST_POLICY = {
  READ: {
    timeoutMs: 15_000,
    retries: 2,
  },
  WRITE: {
    timeoutMs: 15_000,
    retries: 0,
  },
  IDEMPOTENT_WRITE: {
    timeoutMs: 15_000,
    retries: 1,
  },
} as const;
 
type ApiErrorWithShape = ApiErrorBody & {
  errors?: Record<string, string[] | string>;
};
 
const isHttpErrorLike = (error: unknown): error is HttpError<unknown> => {
  return (
    typeof error === "object" &&
    error !== null &&
    "ok" in error &&
    (error as Record<string, unknown>).ok === false &&
    "status" in error
  );
};
 
const getErrorMessage = (error: HttpError<unknown>): string => {
  const body = error.data as ApiErrorWithShape | string | undefined;
 
  if (typeof body === "string" && body.length > 0) {
    return body;
  }
 
  if (body && typeof body === "object" && "message" in body) {
    const message = body.message;
    Eif (typeof message === "string" && message.length > 0) {
      return message;
    }
  }
 
  return error.statusText || API_ERROR_TEXT.REQUEST_FAILED;
};
 
const normalizeValidationErrors = (
  errors: Record<string, string[] | string> | undefined,
): Record<string, string> | undefined => {
  Iif (!errors) return undefined;
 
  const normalized: Record<string, string> = {};
  for (const [key, value] of Object.entries(errors)) {
    normalized[key] = Array.isArray(value) ? (value[0] ?? "") : value;
  }
 
  return normalized;
};
 
const isRetryable = (error: DomainError): boolean => {
  Iif (error._tag === "TimeoutError") return true;
 
  if (error._tag === "NetworkError") {
    const statusCode = error.statusCode;
    return (
      statusCode == null ||
      statusCode >= HTTP_STATUS_CODE.INTERNAL_SERVER_ERROR ||
      statusCode === HTTP_STATUS_CODE.TOO_MANY_REQUESTS
    );
  }
 
  return false;
};
 
export const toDomainError = (error: unknown): DomainError => {
  if (isHttpErrorLike(error)) {
    const status = error.status;
    const message = getErrorMessage(error);
    const body = error.data as ApiErrorWithShape | undefined;
 
    if (
      status === HTTP_STATUS_CODE.UNAUTHORIZED ||
      status === HTTP_STATUS_CODE.FORBIDDEN
    ) {
      return createError.auth(message, body?.code);
    }
 
    if (status === HTTP_STATUS_CODE.NOT_FOUND) {
      return createError.notFound(message);
    }
 
    if (
      status === HTTP_STATUS_CODE.REQUEST_TIMEOUT ||
      status === HTTP_STATUS_CODE.GATEWAY_TIMEOUT
    ) {
      return createError.timeout(message);
    }
 
    if (status === HTTP_STATUS_CODE.UNPROCESSABLE_ENTITY) {
      return createError.validation(
        message,
        undefined,
        normalizeValidationErrors(body?.errors),
      );
    }
 
    return createError.network(message, status);
  }
 
  if (error instanceof Error) {
    return createError.app(error.message, error);
  }
 
  return createError.app(API_ERROR_TEXT.UNKNOWN_ERROR, error);
};
 
export const createRequestEffect = <A>(
  operation: () => Promise<A> | A,
  policy: EffectRequestPolicy = {},
): Effect.Effect<A, DomainError> => {
  let requestEffect: Effect.Effect<A, DomainError> = Effect.tryPromise({
    try: () => Promise.resolve(operation()),
    catch: toDomainError,
  });
 
  if (policy.timeoutMs && policy.timeoutMs > 0) {
    const timeout = policy.timeoutMs;
    requestEffect = requestEffect.pipe(
      Effect.timeoutFail({
        duration: timeout,
        onTimeout: () =>
          createError.timeout(API_ERROR_TEXT.requestTimedOut(timeout), timeout),
      }),
    );
  }
 
  if (policy.retries && policy.retries > 0) {
    requestEffect = requestEffect.pipe(
      Effect.retry({
        times: policy.retries,
        until: (error) => !isRetryable(error),
      }),
    );
  }
 
  return requestEffect;
};
 
export const runRequestEffect = <A>(
  operation: () => Promise<A> | A,
  policy: EffectRequestPolicy = {},
): Promise<A> => {
  return Effect.runPromise(createRequestEffect(operation, policy));
};