All files / src/pages/api statistic.ts

100% Statements 55/55
91.66% Branches 11/12
100% Functions 1/1
100% Lines 55/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 56 57 58 59 60 61 62 63 64  1x     1x 1x   1x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   4x 4x   6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   3x   2x 2x 6x 1x 1x 6x 6x 6x 1x 1x 1x 1x 1x 6x  
// Services
import { lunchStatsService } from '@/services/lunchStats';
 
// Constants
import { STATUS_ERROR_CODE } from '@/constants/status';
import { STATUS_CODE, STATUS_MESSAGES } from '@shared/constants';
 
export const POST = async ({ request }: { request: Request }) => {
  try {
    const authHeader = request.headers.get('Authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      return new Response(
        JSON.stringify({
          success: false,
          error: {
            code: STATUS_ERROR_CODE.UNAUTHORIZED,
            status: STATUS_CODE.UNAUTHORIZED,
            message: STATUS_MESSAGES[STATUS_CODE.UNAUTHORIZED],
          },
        }),
        {
          status: STATUS_CODE.UNAUTHORIZED,
          headers: { 'Content-Type': 'application/json' },
        },
      );
    }
 
    const token = authHeader.replace('Bearer ', '').trim();
    const { time } = await request.json();
 
    if (!time) {
      return new Response(
        JSON.stringify({
          success: false,
          error: {
            code: STATUS_ERROR_CODE.BAD_REQUEST,
            status: STATUS_CODE.BAD_REQUEST,
            message: STATUS_MESSAGES[STATUS_CODE.BAD_REQUEST],
          },
        }),
        {
          status: STATUS_CODE.BAD_REQUEST,
          headers: { 'Content-Type': 'application/json' },
        },
      );
    }
 
    const { data, error } = await lunchStatsService.list(token, time);
 
    return new Response(JSON.stringify({ data, error }), {
      status:
        data && !error
          ? STATUS_CODE.OK
          : error?.status || STATUS_CODE.UNAUTHORIZED,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (err) {
    return new Response(JSON.stringify({ success: false, error: err }), {
      status: STATUS_CODE.INTERNAL_SERVER_ERROR,
      headers: { 'Content-Type': 'application/json' },
    });
  }
};