Skip to content

Commit

Permalink
refact: API 응답 타입 처리 단순화
Browse files Browse the repository at this point in the history
  • Loading branch information
Jxxunnn committed Feb 4, 2025
1 parent fa0d112 commit f6bc45e
Show file tree
Hide file tree
Showing 13 changed files with 57 additions and 89 deletions.
24 changes: 7 additions & 17 deletions src/app/api/v1/chat/room/message/route.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,33 @@
import {
SendChatMessageRequest,
SendChatMessageResponse,
} from "@/chat/apis/sendChatMessage";
import { SendChatMessageRequest } from "@/chat/apis/sendChatMessage";
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
const body: SendChatMessageRequest = await request.json();

console.log(body);

const normalReplyMockData: SendChatMessageResponse = {
const normalReplyMockData = {
messageId: 1,
type: "SYSTEM_NORMAL_REPLY",
sender: "SYSTEM",
answers: [
"안녕 내담자",
"따듯한 마룻바닥이 그리운 겨울 밤이야",
"오늘은 어떤게 궁금해서 찾어왔어냥?",
],
answers: ["안녕 내담자", "따듯한 마룻바닥이 그리운 겨울 밤이야", "오늘은 어떤게 궁금해서 찾어왔어냥?"],
};

const invalidQuestionReplyMockData: SendChatMessageResponse = {
const invalidQuestionReplyMockData = {
messageId: 1,
type: "SYSTEM_INVALID_QUESTION_REPLY",
sender: "SYSTEM",
answers: ["잘못된 질문이네냥!", "다시 질문해보라냥!"],
};

const questionReplyMockData: SendChatMessageResponse = {
const questionReplyMockData = {
messageId: 1,
type: "SYSTEM_TAROT_QUESTION_REPLY",
sender: "SYSTEM",
answers: [
"전남친이 아직 미련이 남았는지 궁금하구낭!",
"타로카드로 그 사람의 마음을 함계 들여다 볼까냥?",
],
answers: ["전남친이 아직 미련이 남았는지 궁금하구낭!", "타로카드로 그 사람의 마음을 함계 들여다 볼까냥?"],
};

const questionAcceptanceReplyMockData: SendChatMessageResponse = {
const questionAcceptanceReplyMockData = {
messageId: 1,
type: "SYSTEM_TAROT_QUESTION_ACCEPTANCE_REPLY",
sender: "SYSTEM",
Expand Down
18 changes: 4 additions & 14 deletions src/app/api/v1/chat/room/messages/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ChatMessagesByRoomIdResponse } from "@/chat/apis/getChatMessagesByRoomId";
import { NextRequest } from "next/server";

import { NextResponse } from "next/server";
Expand All @@ -9,38 +8,29 @@ export async function GET(request: NextRequest) {

console.log(roomId);

const mockData: ChatMessagesByRoomIdResponse = {
const mockData = {
messages: [
{
messageId: 1,
type: "USER_NORMAL",
sender: "SYSTEM",
answers: [
"타로결과를 다시 보고 싶으면 카드를 눌러보라냥🐾",
"또 궁금한 거 있어냥?",
],
answers: ["타로결과를 다시 보고 싶으면 카드를 눌러보라냥🐾", "또 궁금한 거 있어냥?"],
tarotName: "M_00",
tarotResultId: 1,
},
{
messageId: 2,
type: "USER_TAROT_QUESTION",
sender: "USER",
answers: [
"이 타로 카드가 의미하는 게 뭐냐냥?",
"뭔가 다른 카드를 보고 싶다냥.",
],
answers: ["이 타로 카드가 의미하는 게 뭐냐냥?", "뭔가 다른 카드를 보고 싶다냥."],
tarotName: "M_01",
tarotResultId: 2,
},
{
messageId: 3,
type: "SYSTEM_TAROT_RESULT",
sender: "SYSTEM",
answers: [
"새로운 결과를 보고 싶다면 다른 질문을 해보라냥!",
"타로 카드 속에 숨겨진 비밀을 알려줄게냥!",
],
answers: ["새로운 결과를 보고 싶다면 다른 질문을 해보라냥!", "타로 카드 속에 숨겨진 비밀을 알려줄게냥!"],
tarotName: "M_02",
tarotResultId: 3,
},
Expand Down
3 changes: 1 addition & 2 deletions src/app/api/v1/tarot/result/[resultId]/route.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { TarotReadingResultResponse } from "@/tarot/apis/getTarotReadingResultById";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
const resultId = request.nextUrl.pathname.split("/")[4];

console.log(parseInt(resultId, 10));

const mockData: TarotReadingResultResponse = {
const mockData = {
tarot: "M_00",
type: "연애",
cardValue: {
Expand Down
12 changes: 3 additions & 9 deletions src/app/api/v1/tarot/select/route.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
import {
SelectTarotCardRequest,
SelectTarotCardResponse,
} from "@/tarot/apis/selectTarotCard";
import { SelectTarotCardRequest } from "@/tarot/apis/selectTarotCard";
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
const body: SelectTarotCardRequest = await request.json();
console.log(body);

const mockData: SelectTarotCardResponse = {
const mockData = {
messageId: 1,
type: "SYSTEM_TAROT_RESULT",
sender: "SYSTEM",
answer: [
"타로결과를 다시 보고 싶으면 카드를 눌러보라냥🐾",
"또 궁금한 거 있어냥?",
],
answer: ["타로결과를 다시 보고 싶으면 카드를 눌러보라냥🐾", "또 궁금한 거 있어냥?"],
tarotName: "M_00",
tarotResultId: 1,
};
Expand Down
12 changes: 6 additions & 6 deletions src/chat/apis/createChatRoom.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import apiClient from '@/shared/lib/axios/apiClient';
import { z } from 'zod';
import apiClient from "@/shared/lib/axios/apiClient";
import { z } from "zod";

type Response = {
type serverResponse = {
roomId: number;
};

Expand All @@ -11,14 +11,14 @@ const schema = z.object({

export type CreateChatRoomResponse = z.infer<typeof schema>;

const validate = (data: Response): CreateChatRoomResponse => {
const validate = (data: serverResponse): CreateChatRoomResponse => {
const validatedData = schema.parse(data);
return validatedData;
};

export const createChatRoom = () => {
export const createChatRoom = (): Promise<CreateChatRoomResponse> => {
return apiClient
.post<Response>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/chat/room`)
.post<serverResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/chat/room`)
.then((res) => validate(res.data))
.catch((error) => {
console.error(error);
Expand Down
10 changes: 5 additions & 5 deletions src/chat/apis/getChatMessagesByRoomId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { z } from "zod";
import { MessageCategorySchema } from "../types/messageCategory";
import { MessageSenderTypeSchema } from "../types/messageSender";

export type ChatMessagesByRoomIdResponse = {
type serverResponse = {
messages: {
messageId: number;
type: string;
Expand All @@ -28,16 +28,16 @@ const schema = z.object({
),
});

export type ChatMessagesByRoomIdData = z.infer<typeof schema>;
export type ChatMessagesByRoomIdResponse = z.infer<typeof schema>;

const validate = (data: ChatMessagesByRoomIdResponse): ChatMessagesByRoomIdData => {
const validate = (data: serverResponse): ChatMessagesByRoomIdResponse => {
const validatedData = schema.parse(data);
return validatedData;
};

export const getChatMessagesByRoomId = (roomId: number) => {
export const getChatMessagesByRoomId = (roomId: number): Promise<ChatMessagesByRoomIdResponse> => {
return apiClient
.get<ChatMessagesByRoomIdResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/chat/room/messages`, {
.get<serverResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/chat/room/messages`, {
params: {
roomId,
},
Expand Down
10 changes: 5 additions & 5 deletions src/chat/apis/sendChatMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export type SendChatMessageRequest = {
referenceQuestionId?: number;
};

export type SendChatMessageResponse = {
type serverResponse = {
messageId: number;
type: string;
sender: string;
Expand All @@ -30,16 +30,16 @@ const schema = z.object({
answers: z.array(z.string()),
});

type SendChatMessageData = z.infer<typeof schema>;
export type SendChatMessageResponse = z.infer<typeof schema>;

const validate = (data: SendChatMessageResponse): SendChatMessageData => {
const validate = (data: serverResponse): SendChatMessageResponse => {
const validatedData = schema.parse(data);
return validatedData;
};

export const sendChatMessage = (request: SendChatMessageRequest) => {
export const sendChatMessage = (request: SendChatMessageRequest): Promise<SendChatMessageResponse> => {
return apiClient
.post<SendChatMessageResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/chat/room/message`, request)
.post<serverResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/chat/room/message`, request)
.then((res) => validate(res.data))
.catch((error) => {
console.error(error);
Expand Down
4 changes: 2 additions & 2 deletions src/chat/components/QuickQuestionPickerBox.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCreateChatRoom } from "@/chat/hooks/useCreateChatRoom";
import { TarotQuestionRecommendListData } from "@/tarot/apis/getTarotQuestionRecommends";
import { TarotQuestionRecommendListResponse } from "@/tarot/apis/getTarotQuestionRecommends";
import { useTarotQuestionRecommends } from "@/tarot/hooks/useTarotQuestionRecommends";
import { useRouter } from "next/navigation";
import { useState } from "react";
Expand All @@ -16,7 +16,7 @@ export default function QuickQuestionPickerBox() {

if (!data) return null;

const adaptQuestionRecommends = (data: TarotQuestionRecommendListData) => {
const adaptQuestionRecommends = (data: TarotQuestionRecommendListResponse) => {
const colors = ["primary03", "grey10", "primary01", "grey60"] as const;
return data.questions.map((question, i) => ({
...question,
Expand Down
8 changes: 4 additions & 4 deletions src/chat/hooks/useChatMessagesStore.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createContext, useCallback, useContext, useReducer } from "react";
import { ChatMessagesByRoomIdData } from "../apis/getChatMessagesByRoomId";
import { ChatMessagesByRoomIdResponse } from "../apis/getChatMessagesByRoomId";
import { MessageType } from "../types/message";

type AddMessageAction = {
Expand All @@ -9,7 +9,7 @@ type AddMessageAction = {

type CopyServerStateAction = {
type: "COPY_SERVER_STATE";
payload: ChatMessagesByRoomIdData["messages"];
payload: ChatMessagesByRoomIdResponse["messages"];
};

type DeleteMessageAction = {
Expand Down Expand Up @@ -49,7 +49,7 @@ const chatMessagesReducer = (state: MessageType[], action: Action) => {
type ChatMessagesContextType = {
state: MessageType[];
addMessage: (message: MessageType) => void;
copyServerState: (messages: ChatMessagesByRoomIdData["messages"]) => void;
copyServerState: (messages: ChatMessagesByRoomIdResponse["messages"]) => void;
deleteMessage: (messageId: MessageType["messageId"]) => void;
editMessage: (message: MessageType) => void;
};
Expand All @@ -71,7 +71,7 @@ export const ChatMessagesProvider = ({ children }: { children: React.ReactNode }
dispatch({ type: actionTypes.ADD_MESSAGE, payload: message });
}, []);

const copyServerState = useCallback((messages: ChatMessagesByRoomIdData["messages"]) => {
const copyServerState = useCallback((messages: ChatMessagesByRoomIdResponse["messages"]) => {
dispatch({ type: actionTypes.COPY_SERVER_STATE, payload: messages });
}, []);

Expand Down
9 changes: 3 additions & 6 deletions src/shared/apis/logShareEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ export type LogShareEventRequest = {
};

export const logShareEvent = ({ resultId }: LogShareEventRequest) => {
return apiClient.post(
`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/common/share`,
{
resultId,
},
);
return apiClient.post(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/common/share`, {
resultId,
});
};
16 changes: 6 additions & 10 deletions src/tarot/apis/getTarotQuestionRecommends.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import apiClient from "@/shared/lib/axios/apiClient";
import { z } from "zod";

export type TarotQuestionRecommendListResponse = {
type serverResponse = {
questions: {
recommendQuestionId: number;
question: string;
Expand All @@ -15,24 +15,20 @@ const schema = z.object({
recommendQuestionId: z.number(),
question: z.string(),
referenceCount: z.number(),
}),
})
),
});

export type TarotQuestionRecommendListData = z.infer<typeof schema>;
export type TarotQuestionRecommendListResponse = z.infer<typeof schema>;

const validate = (
data: TarotQuestionRecommendListResponse,
): TarotQuestionRecommendListData => {
const validate = (data: serverResponse): TarotQuestionRecommendListResponse => {
const validatedData = schema.parse(data);
return validatedData;
};

export const getTarotQuestionRecommends = async () => {
export const getTarotQuestionRecommends = (): Promise<TarotQuestionRecommendListResponse> => {
return apiClient
.get<TarotQuestionRecommendListResponse>(
`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/tarot/question/recommends`,
)
.get<serverResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/tarot/question/recommends`)
.then((res) => validate(res.data))
.catch((error) => {
console.error(error);
Expand Down
10 changes: 5 additions & 5 deletions src/tarot/apis/getTarotReadingResultById.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import apiClient from "@/shared/lib/axios/apiClient";
import { z } from "zod";
import { TarotCardIdSchema } from "../types/tarotCardId";

export type TarotReadingResultResponse = {
type serverResponse = {
tarot: string;
type: string;
cardValue: {
Expand Down Expand Up @@ -38,16 +38,16 @@ const schema = z.object({
}),
});

type TarotReadingResultData = z.infer<typeof schema>;
export type TarotReadingResultResponse = z.infer<typeof schema>;

const validate = (data: TarotReadingResultResponse): TarotReadingResultData => {
const validate = (data: serverResponse): TarotReadingResultResponse => {
const validatedData = schema.parse(data);
return validatedData;
};

export const getTarotReadingResultById = async (resultId: number) => {
export const getTarotReadingResultById = async (resultId: number): Promise<TarotReadingResultResponse> => {
return apiClient
.get<TarotReadingResultResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/tarot/result/${resultId}`)
.get<serverResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/tarot/result/${resultId}`)
.then((res) => validate(res.data))
.catch((error) => {
console.error(error);
Expand Down
10 changes: 6 additions & 4 deletions src/tarot/apis/selectTarotCard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export type SelectTarotCardRequest = {
tarotName: TarotCardType["id"];
};

export type SelectTarotCardResponse = {
type serverResponse = {
messageId: number;
type: string;
sender: string;
Expand All @@ -19,6 +19,8 @@ export type SelectTarotCardResponse = {
tarotResultId: number;
};

export type SelectTarotCardResponse = z.infer<typeof schema>;

const schema = z.object({
messageId: z.number(),
type: z.literal(MessageCategorySchema.Enum.SYSTEM_TAROT_RESULT),
Expand All @@ -30,14 +32,14 @@ const schema = z.object({

type SelectTarotCardData = z.infer<typeof schema>;

const validate = (data: SelectTarotCardResponse): SelectTarotCardData => {
const validate = (data: serverResponse): SelectTarotCardData => {
const validatedData = schema.parse(data);
return validatedData;
};

export const selectTarotCard = async (request: SelectTarotCardRequest) => {
export const selectTarotCard = async (request: SelectTarotCardRequest): Promise<SelectTarotCardResponse> => {
return apiClient
.post<SelectTarotCardResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/tarot/select`, request)
.post<serverResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/tarot/select`, request)
.then((res) => validate(res.data))
.catch((error) => {
console.error(error);
Expand Down

0 comments on commit f6bc45e

Please sign in to comment.