Skip to content

Commit

Permalink
refactor: separate API and query logic for rental details
Browse files Browse the repository at this point in the history
  • Loading branch information
nxnaxx committed Dec 8, 2024
1 parent 6c767eb commit 163b017
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 91 deletions.
26 changes: 24 additions & 2 deletions src/api/rental.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import axios from 'axios';

import { endPoint } from 'constants/endPoint';
import type { PageParam } from 'queries/rent/useRentList';
import type { RentalListResponse } from 'types';
import { API_URL } from 'constants/url';
import type { PageParam } from 'queries/rent/useGetRentList';
import type { RentalAccountResponse, RentalDetailResponse, RentalListResponse } from 'types';
import { publicAxios } from 'utils';

export const tokenTestAxios = axios.create({
baseURL: API_URL,
withCredentials: true,
timeout: 15000,
headers: {
Authorization: `Bearer ${import.meta.env.VITE_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
});

export const createRentalQuery = (filterQuery: string, pageParam: PageParam) => {
const { lastId, lastEndDate } = pageParam;
let pageQuery = lastId ? `lastId=${lastId}` : '';
Expand All @@ -18,3 +31,12 @@ export const requestGetRentalList = async (query: string) => {
return (await publicAxios.get<RentalListResponse>(`${endPoint.GET_RENT_LIST}?${query}`)).data
.result;
};

export const requestGetRentalDetails = (id: string) => {
return publicAxios.get<RentalDetailResponse>(endPoint.GET_RENT_DETAIL(id));
};

export const requestGetDepositAccount = (id: string) => {
// 추후 수정
return tokenTestAxios.get<RentalAccountResponse>(endPoint.GET_DEPOSIT_ACCOUNT(id));
};
35 changes: 0 additions & 35 deletions src/hooks/useRentalDetails.ts

This file was deleted.

88 changes: 45 additions & 43 deletions src/mocks/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,49 @@
import { http, HttpResponse } from 'msw';

import { API_URL } from 'constants/url';

export const handlers = [
http.get('/api/v1/rents/1', () => {
return HttpResponse.json({
timeStamp: '2024-12-03T00:13:56.217Z',
code: '200',
message: 'Success',
result: {
concertName: 'DAY6 3RD WORLD TOUR, FOREVER YOUNG [인천]',
imageUrl: 'https://img1.newsis.com/2024/03/18/NISI20240318_0001504432_web.jpg',
title: '데이식스(DAY6) FOREVER YOUNG 콘서트 청주 차대절 🎸',
artistName: 'DAY6',
region: '청주',
boardingArea: '스타벅스 청주터미널점',
dropOffArea: '인스파이어리조트 (아레나)',
upTime: '09:00',
downTime: '23:00',
rentBoardingDates: ['2024-09-20', '2024-09-21', '2024-09-22'],
busSize: 'LARGE',
busType: 'DELUXE',
maxPassenger: 28,
roundPrice: 45000,
upTimePrice: 45000,
downTimePrice: 45000,
recruitmentCount: 25,
participants: [25, 12, 18],
endDate: '2024-12-26',
chatUrl: 'https://open.kakao.com/o/abcDeF',
refundType: 'ADDITIONAL_DEPOSIT',
information: `❗입금 후 폼 작성 부탁드립니다.❗\n\n 왕복, 편도 가격 동일합니다.
양도나 분할 탑승 신청자분들은 직접 짝 구해주시고 신청해주시길 바랍니다. (입금은 한분께서 일괄 입금 부탁드리며 오픈카톡을 통해 확인 내용 알려주시길 바랍니다.)\n
📌 개인이 진행하는 차대절이기 때문에 인원 미달, 13번 이후 입금자를 제외한 환불은 절대 불가하오며 이 부분을 숙지하지 못한 사항에 대해서 생기는 불이익은 책임지지 않습니다.이점 유의하시고 신청 바랍니다.`,
},
});
}),
http.get('/api/v1/rents/1/deposit-account', () => {
return HttpResponse.json({
timeStamp: '2024-12-03T02:38:22.994Z',
code: '200',
message: 'success',
result: {
depositAccount: '우리은행 1242264211943 김데식',
},
});
}),
// http.get(`${API_URL}/api/v1/rents/12`, () => {
// return HttpResponse.json({
// timeStamp: '2024-12-03T00:13:56.217Z',
// code: '200',
// message: 'Success',
// result: {
// concertName: 'DAY6 3RD WORLD TOUR, FOREVER YOUNG [인천]',
// imageUrl: 'https://img1.newsis.com/2024/03/18/NISI20240318_0001504432_web.jpg',
// title: '데이식스(DAY6) FOREVER YOUNG 콘서트 청주 차대절 🎸',
// artistName: 'DAY6',
// region: '청주',
// boardingArea: '스타벅스 청주터미널점',
// dropOffArea: '인스파이어리조트 (아레나)',
// upTime: '09:00',
// downTime: '23:00',
// rentBoardingDates: ['2024-09-20', '2024-09-21', '2024-09-22'],
// busSize: 'LARGE',
// busType: 'DELUXE',
// maxPassenger: 28,
// roundPrice: 45000,
// upTimePrice: 45000,
// downTimePrice: 45000,
// recruitmentCount: 25,
// participants: [25, 12, 18],
// endDate: '2024-12-26',
// chatUrl: 'https://open.kakao.com/o/abcDeF',
// refundType: 'ADDITIONAL_DEPOSIT',
// information: `❗입금 후 폼 작성 부탁드립니다.❗\n\n 왕복, 편도 가격 동일합니다.
// 양도나 분할 탑승 신청자분들은 직접 짝 구해주시고 신청해주시길 바랍니다. (입금은 한분께서 일괄 입금 부탁드리며 오픈카톡을 통해 확인 내용 알려주시길 바랍니다.)\n
// 📌 개인이 진행하는 차대절이기 때문에 인원 미달, 13번 이후 입금자를 제외한 환불은 절대 불가하오며 이 부분을 숙지하지 못한 사항에 대해서 생기는 불이익은 책임지지 않습니다.이점 유의하시고 신청 바랍니다.`,
// },
// });
// }),
// http.get(`${API_URL}/api/v1/rents/12/deposit-account`, () => {
// return HttpResponse.json({
// timeStamp: '2024-12-03T02:38:22.994Z',
// code: '200',
// message: 'success',
// result: {
// depositAccount: '우리은행 1242264211943 김데식',
// },
// });
// }),
];
4 changes: 2 additions & 2 deletions src/pages/busRental/BusRental.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import FAB from 'components/buttons/FAB';
import FilterChip from 'components/chips/FilterChip';
import { RENTAL_FILTER } from 'constants/filterTypes';
import { useIntersectionObserver } from 'hooks/useIntersectionObserver';
import { useRentalList } from 'queries/rent/useRentList';
import { useGetRentalList } from 'queries/rent';
import { useModalStore } from 'stores';
import { useRentalFilterStore } from 'stores/useRentalFilterStore';
import { BodyRegularText } from 'styles/Typography';
Expand Down Expand Up @@ -59,7 +59,7 @@ const BusRental = () => {
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useRentalList();
} = useGetRentalList();

const handleFilterChipClick = (type: RentalFilterType) => {
openModal('bottomSheet', 'list', <RentalFilterSheet filterType={type} />);
Expand Down
2 changes: 1 addition & 1 deletion src/pages/busRental/components/RentalPostItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ const RentalPostItem = ({
<SmallText>{boardingArea}</SmallText>
</BoardingArea>
</RentalContent>
<RentalItemLink to={endPoint.GET_RENT_DETAIL(String(rentId))} />
<RentalItemLink to={`/bus-rental/${rentId}`} />
</RentalItemContainer>
);
};
Expand Down
13 changes: 8 additions & 5 deletions src/pages/busRentalDetail/BusRentalDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import ParticipantsStatus from './components/ParticipantsStatus';
import Badge from 'components/badge/Badge';
import BaseButton from 'components/buttons/BaseButton';
import SimpleChip from 'components/chips/SimpleChip';
import { useRentalDetails } from 'hooks/useRentalDetails';
import { useGetRentalDetails } from 'queries/rent';
import { BodyRegularText, TitleText1, TitleText2 } from 'styles/Typography';
import { formatDateWithDay, getDday } from 'utils';

Expand Down Expand Up @@ -88,7 +88,7 @@ const InfoSection = ({ title, children }: { title: string; children: React.React

const BusRentalDetail = () => {
const { id } = useParams();
const { data: details, error, isLoading } = useRentalDetails(id as string);
const { data: details, error, isLoading } = useGetRentalDetails(id as string);

if (isLoading) return <div>로딩중</div>;
if (error) return <div>Error 발생: {error.message}</div>;
Expand All @@ -103,7 +103,7 @@ const BusRentalDetail = () => {
endDate,
rentBoardingDates,
recruitmentCount,
participants,
currentRecruitmentCounts,
boardingArea,
dropOffArea,
busSize,
Expand Down Expand Up @@ -139,7 +139,7 @@ const BusRentalDetail = () => {
<SimpleChip>{artistName}</SimpleChip>
</ChipWrapper>
<ParticipantsStatus
participants={participants}
participants={currentRecruitmentCounts}
recruitmentCount={recruitmentCount}
rentDates={rentDates}
/>
Expand Down Expand Up @@ -172,7 +172,10 @@ const BusRentalDetail = () => {
<BottomButtonWrapper>
<BaseButton
color="primary"
isDisabled={every(participants, (participant) => participant === recruitmentCount)}
isDisabled={every(
currentRecruitmentCounts,
(participant) => participant === recruitmentCount
)}
onClick={() => {}}
size="medium"
variant="fill"
Expand Down
2 changes: 1 addition & 1 deletion src/pages/busRentalDetail/components/BusTime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const BusTime = ({ upTime, downTime, boardingArea, dropOffArea }: BusTimeProps)
return (
<TimeContainer>
{timeData.map(({ label, time, area }) => (
<TimeItem>
<TimeItem key={label}>
<Label>{label}</Label>
<Time>{time}</Time>
<BodyRegularText>{area}</BodyRegularText>
Expand Down
2 changes: 2 additions & 0 deletions src/queries/rent/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './useGetRentalDetails';
export * from './useGetRentList';
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export interface PageParam {
lastEndDate: string | null;
}

export const useRentalList = () => {
export const useGetRentalList = () => {
const { filters, getFilterQuery } = useRentalFilterStore(['filters', 'getFilterQuery']);

const fetchFilteredList = async (pageParam: PageParam): Promise<RentalList[]> => {
Expand Down
26 changes: 26 additions & 0 deletions src/queries/rent/useGetRentalDetails.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useQuery } from '@tanstack/react-query';

import { requestGetDepositAccount, requestGetRentalDetails } from 'api';
import type { AllRentalDetail } from 'types';

export const useGetRentalDetails = (id: string) => {
// 로그인 여부 (추후 수정)
const isLoggedIn = false;

const fetchDetails = async (): Promise<AllRentalDetail> => {
const detailPromise = await requestGetRentalDetails(id);
const accountPromise = isLoggedIn ? requestGetDepositAccount(id) : Promise.resolve(null);

const [detailResponse, accountResponse] = await Promise.all([detailPromise, accountPromise]);
const rentalDetails = detailResponse.data.result;
const depositAccount = accountResponse?.data.result.depositAccount ?? null;

return { ...rentalDetails, depositAccount };
};

return useQuery<AllRentalDetail>({
queryKey: ['rentalDetail', id],
queryFn: fetchDetails,
enabled: !!id,
});
};
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './modal';
export * from './rental';
export * from './survey';
export * from './user';
export * from './api';
2 changes: 1 addition & 1 deletion src/types/rental.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export interface RentalDetail {
upTimePrice: number;
downTimePrice: number;
recruitmentCount: number;
participants: number[];
currentRecruitmentCounts: number[];
endDate: string;
chatUrl: string;
refundType: RefundType;
Expand Down

0 comments on commit 163b017

Please sign in to comment.