All files / src/services lunchStats.ts

100% Statements 54/54
100% Branches 9/9
80% Functions 4/5
100% Lines 54/54

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 681x 1x     1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 4x 4x   4x 4x 4x 4x   4x 4x 4x 4x   4x 4x   4x 1x 1x 1x 1x 1x   1x 4x 4x 2x 2x 2x 2x 2x 1x 1x 2x 2x 4x 4x 4x 4x 1x  
import { Effect, pipe, Schema } from 'effect';
import { createOrpcClient } from '@/libs/orpcClient';
 
// Constants
import { ERROR_MESSAGES } from '@/constants/messages';
import { STATUS_CODE, STATUS_MESSAGES } from '@shared/constants';
import { MULTIPLE_DATE_REGEX } from '@/constants/regex';
 
// Types
import { ApiError, ApiResponse } from '@/types/api';
import { StatisticsResponse } from '@/types/statistic';
 
export const LunchStatsRequestSchema = Schema.Struct({
  token: Schema.String.pipe(
    Schema.minLength(1, {
      message: () => STATUS_MESSAGES[STATUS_CODE.UNAUTHORIZED]!,
    }),
  ),
  time: Schema.String.pipe(
    Schema.pattern(MULTIPLE_DATE_REGEX, {
      message: () => STATUS_MESSAGES[STATUS_CODE.BAD_REQUEST]!,
    }),
  ),
});
 
export const lunchStatsService = {
  list: async (
    token: string,
    time: string,
  ): Promise<ApiResponse<StatisticsResponse[] | null>> =>
    Effect.runPromise(
      pipe(
        Effect.tryPromise({
          try: async () => {
            // Validate payload
            await Schema.decodeUnknown(LunchStatsRequestSchema)({
              token,
              time,
            });
 
            const orpcClient = createOrpcClient(token);
            const { data } = await orpcClient.lunchStats?.list({ time });
 
            if (!data) {
              return {
                data: null,
                error: { message: ERROR_MESSAGES.FETCH_LUNCH_STATS },
              };
            }
 
            return { data };
          },
          catch: (error) => ({
            data: null,
            error: {
              ...(error as ApiError),
              message:
                error instanceof Error
                  ? error.message
                  : ERROR_MESSAGES.FETCH_LUNCH_STATS,
            },
          }),
        }),
        Effect.catchAll((error) => Effect.succeed(error)),
      ),
    ),
};