Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…i-Front into deploy-1.1
  • Loading branch information
rwaeng committed Dec 2, 2024
2 parents 0615509 + 8c22e59 commit 965d5d2
Show file tree
Hide file tree
Showing 19 changed files with 394 additions and 111 deletions.
23 changes: 20 additions & 3 deletions src/apis/channel.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { AxiosResponse } from 'axios';
import type { Channel, Message } from '@src/types/apis/channel.d';
import type { Channel } from '@src/types/apis/channel.d';
import { authClient } from '@src/apis/index';
import { ChannelMessagesRes } from '@src/types/domain/channel';

/** 채널 생성 */
export const postChannel = async <Res = void, Req = Channel>(
Expand Down Expand Up @@ -48,9 +49,25 @@ export const deleteChannel = async <Res = void>(
* 채널 채팅 내역 조회
* @ 백엔드 구현 미완료
*/
export const getMessageList = async <Res = Message[]>(
export const getChannelMessages = async <Res = ChannelMessagesRes>(
channelId: number,
page?: number,
size?: number,
): Promise<Res> => {
const response = await authClient.get<Res>(`/channels/${channelId}/messages`);
const queryParams = new URLSearchParams({
channelId: String(channelId),
});

if (page !== undefined) {
queryParams.append('page', String(page));
}

if (size !== undefined) {
queryParams.append('size', String(size));
}

const response = await authClient.get(
`/channelMessages?${queryParams.toString()}`,
);
return response.data;
};
6 changes: 2 additions & 4 deletions src/apis/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@ import { Client, Frame, IMessage } from '@stomp/stompjs';
const WEBSOCKET_URL = process.env.REACT_APP_WEBSOCKET_URL!;

let stompClient: Client | null = null;
type MessageHandler<T extends ChatEvent | MessageRequest> = (
message: T,
) => void;
type MessageHandler<T extends ChatEvent> = (message: T) => void;

// WebSocket 연결 & 구독
export const connectHandler = <T extends ChatEvent | MessageRequest>(
export const connectHandler = <T extends ChatEvent>(
onMessage: MessageHandler<T>,
subscribeUrl: string,
) => {
Expand Down
2 changes: 1 addition & 1 deletion src/apis/member.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const patchProfile = async (body: FormData) => {

/* 개별 프로필 조회 */
export const getProfile = async (
memberId?: number,
memberId?: number | null,
): Promise<ProfileResponse> => {
const res = await authClient.get(`members/${memberId ?? 'me'}`);
return res.data;
Expand Down
2 changes: 1 addition & 1 deletion src/apis/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const getServers = async <
};

export const getServerOne = async <Res = Omit<Server, 'serverId'>>(
serverId: number,
serverId: number | null,
headers?: Record<string, string>,
): Promise<Res> => {
const response = await authClient.get<Res, AxiosResponse<Res>>(
Expand Down
84 changes: 84 additions & 0 deletions src/components/channel/ChannelChatBar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import styled from 'styled-components';
import React, { useState } from 'react';
import { sendHandler } from '@src/apis/chat';
import { ReactComponent as Send } from '@src/assets/icons/send.svg';
import { ReactComponent as SendGreen } from '@src/assets/icons/send_green.svg';

interface ChannelChatBarProps {
channelName: string;
channelId: number;
}

const ChannelChatBar = ({ channelName, channelId }: ChannelChatBarProps) => {
const [chat, setChat] = useState('');

const handleChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
setChat(e.target.value);
};

const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
handleSendMessage();
}
};

const handleSendMessage = async () => {
if (!chat.trim()) return;

const message: MessageRequest = {
channelId,
type: 'text',
content: chat,
};

try {
await sendHandler(message, '/pub/channel/send');
console.log('Message sent successfully');
setChat('');
} catch (error) {
console.error('Failed to send message:', error);
}
};
return (
<SLayout>
<SInput
type='text'
value={chat}
onChange={handleChangeInput}
placeholder={`${channelName}에 문자 보내기`}
onKeyDown={handleKeyDown}
/>
<SButton type='button' onClick={handleSendMessage}>
{chat ? <SendGreen /> : <Send />}
</SButton>
</SLayout>
);
};

export default ChannelChatBar;

const SLayout = styled.div`
display: flex;
gap: 0.625rem;
position: sticky;
bottom: 0;
width: 100%;
padding: 0.9375rem;
background-color: ${({ theme }) => theme.colors.white};
`;
const SInput = styled.input`
padding: 0 0.625rem;
width: 100%;
border-radius: 1.875rem;
${({ theme }) => theme.fonts.body};
background-color: ${({ theme }) => theme.colors.black300};
`;
const SButton = styled.button`
display: flex;
justify-content: center;
align-itmes: center;
`;
3 changes: 2 additions & 1 deletion src/components/chatting/ChatItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import Profile from '@src/assets/images/userSettings/background_default.svg';
import { DM } from '@src/types/domain/messageRoom';
import { SyntheticEvent, useMemo } from 'react';
import { formatChatItemTime } from '@src/utils/formatters';
import { ChannelMessage } from '@src/types/domain/channel';

interface ChatItemProps {
chatItem: DM;
chatItem: DM | ChannelMessage;
imgUrl?: string;
nickname: string;
createdAt: string;
Expand Down
10 changes: 3 additions & 7 deletions src/components/communitysidebar/CommunitySideBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,13 @@ import useDialog from '@src/hooks/useDialog';
import ProfileModal from '@src/components/communitysidebar/ProfileModal';
import useSideBar from '@src/hooks/useSideBar';
import useSideBarData from '@src/hooks/query/useSideBarData';
import { useNavigate } from 'react-router-dom';
import { useNavigate, useParams } from 'react-router-dom';
import { ROUTE_PATH } from '@src/constants/routePath';

const CommunitySideBar = () => {
const { sideBar, closeSideBar } = useSideBar();
// const { id: serverId } = useLoaderData<{ id: number }>();
// const { serverId: id } = useParams<{ serverId: string }>();
const serverId = 11;
// if (!id)
// throw new Error('CommunityInfoSettingPage: serverId is not provided');
// const serverId = parseInt(id, 10);
const { serverId: id } = useParams<{ serverId: string }>();
const serverId = Number(id);
const { serverInfo, memberList, copyText } = useSideBarData(serverId);
const { isCopied, handleCopy } = useCopyToClipboard(copyText);
const { openDialog } = useDialog();
Expand Down
23 changes: 23 additions & 0 deletions src/hooks/query/useChattingLog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useInfiniteQuery } from '@tanstack/react-query';
import { getChannelMessages } from '@src/apis/channel';

const SIZE = 10;

const useChattingLog = (channelId: number) => {
return useInfiniteQuery({
queryKey: ['getChannelMessages', channelId],
queryFn: ({ pageParam = 0 }) =>
getChannelMessages(channelId, pageParam, SIZE),
initialPageParam: 0,
getNextPageParam: (lastPage, allPages) => {
if (!lastPage || !lastPage.messages || lastPage.messages.length < SIZE) {
return undefined;
}

const isLastPage = lastPage.messages.length < SIZE;
return isLastPage ? undefined : allPages.length;
},
});
};

export default useChattingLog;
4 changes: 2 additions & 2 deletions src/hooks/query/useMember.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ProfileResponse } from '@src/types/domain/member';
import { deleteAccount } from '@src/apis/auth';
import { ROUTE_PATH } from '@src/constants/routePath';

const useMember = (userId?: number) => {
const useMember = (userId?: number | null) => {
const {
data: profileData,
isLoading,
Expand Down Expand Up @@ -36,7 +36,7 @@ const useMember = (userId?: number) => {
isError,
isSuccess,
editProfile,
delAccount
delAccount,
};
};

Expand Down
6 changes: 6 additions & 0 deletions src/hooks/query/useServer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { AxiosError } from 'axios';
import { useQuery } from '@tanstack/react-query';
import { Server } from '@src/types/apis/server';
import { getServerOne } from '@src/apis/server';

const useChannel = (channelId: number) => {};
5 changes: 5 additions & 0 deletions src/hooks/query/useSideBarData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@ import { Server, ServerMembersResponse } from '@src/types/apis/server.d';
import { AxiosError } from 'axios';

const useSideBarData = (serverId: number) => {
const isValidServerId = serverId > 0;

// 서버 정보
const { data: serverInfo } = useQuery<Omit<Server, 'serverId'>, AxiosError>({
queryKey: ['getServerOne', serverId],
queryFn: () => getServerOne(serverId),
enabled: isValidServerId,
});

// 서버 멤버 정보
Expand All @@ -21,13 +24,15 @@ const useSideBarData = (serverId: number) => {
>({
queryKey: ['getServerMembers', serverId],
queryFn: () => getServerMembers(serverId),
enabled: isValidServerId,
});

// 서버 초대장 코드
const { data: copyText } = useQuery<string, AxiosError>({
queryKey: ['postServerCode', serverId],
queryFn: () => postServerCode(serverId),
initialData: 'bookWOORI1234',
enabled: isValidServerId,
});

return {
Expand Down
Loading

0 comments on commit 965d5d2

Please sign in to comment.