토이프로젝트/banthing

newChat 리팩토링

테오구 2022. 5. 20. 19:20
728x90

기존의 코드

import axios from 'axios';
import styles from './newChat.module.css';

interface newChatType {
  roomsId: number;
}

const NewChat = ({ roomsId }: newChatType) => {
  const [chat, setChat] = useState('');
  // 방의 아이디와 덧글을 포함하여 post합니다.
  const onSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (chat !== '') {
      isCookie();
      // chats에 입력한 값을 전해줍니다.
    }
    // input의 값을 초기화 합니다.
    setChat('');
  };
    const isCookie = () => {
    let cookie: any;
    let cookieToken: any;
    let cookieList: any;
    if (typeof window !== 'undefined') {
      cookie = document.cookie;
      if (cookie.includes(';') && cookie.includes('accessToken')) {
        cookieList = cookie.split(';');
        const findAccessToken = cookieList.filter((cookie: string) => {
          return cookie.includes('accessToken');
        });
        cookieToken = findAccessToken[0].split('=')[1];
      } else if (!cookie.includes(';') && cookie.includes('accessToken')) {
        cookieToken = cookie.split('=')[1];
      }
      if (cookieToken) {
        const headers = {
          Authorization: `Bearer ${cookieToken}`,
        };
        axiosPost(headers);
      }
    }
  };

  const axiosPost = async (headers: { Authorization: string }) => {
      try {
      await axios.post(
        `${process.env.NEXT_PUBLIC_SERVER_ENDPOINT}/post/reply`,
        {
          post_id: roomsId,
          reply: chat,
        },
        {
          headers,
          withCredentials: true,
        },
      );
          } catch (err) {
      console.log(err);
    }

기존의 코드는 useEffect상에서 axios 처리를 해주었습니다.

 

리팩토링 후

전체적으로 component는 깔끔해졌습니다.

  const onSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (chat !== '') {
      axiosPost();
      // chats에 입력한 값을 전해줍니다.
    }
    // input의 값을 초기화 합니다.
    setChat('');
  };

  const axiosPost = () => {
    try {
      chatService.postChats(roomsId, chat);
      socket.emit('sendMessage', chat);
      // setAlarmNumber(alarmNumber + 1);
      // new Notification('타이틀', { body: chat });
    } catch (err) {
      console.log(err);
    }
  };

axios 요청을 하는 class를 만들어주었습니다.

import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
// axios를 사용할 수 있게 객체 지향형으로 제작을 해주었습니다.
export default class AxiosClient {
  protected baseURL: string;
  constructor(baseURL: string) {
    this.baseURL = baseURL;
  }

  async axios(url: string, options: AxiosRequestConfig) {
    try {
      const res: AxiosResponse = await axios(`${this.baseURL}${url}`, {
        ...options,
        headers: {
          ...options.headers,
        },
      });

      // 요청의 status가 200번때가 아닐 경우
      // data.message를 보내주고
      // 400번때이면 error를 보내줍니다.
      if (res.status > 299 || res.status < 200) {
        const message =
          res.data && res.data.message
            ? res.data.message
            : 'Something went wrong';
        const error = new Error(message);
        if (res.status === 401) {
          console.log(error);
        }
      }
      return res.data;
    } catch (err) {
      console.log(err);
    }
  }
}

axios class를 이용해 채팅 서비스를 보내는 클래스를 따로 만들어주었습니다.

import AxiosClient from './axios';

// axios class를 이용하여 chating을 보내줄 수 있는
export default class ChatService {
  protected http: AxiosClient;
  constructor(http: AxiosClient) {
    this.http = http;
  }

  // 채팅을 보냅니다.
  async postChats(roomId: number, chat: string) {
    return this.http.axios(`/post/reply/`, {
      method: 'post',
      data: {
        post_id: roomId,
        reply: chat,
      },
      headers: this.getHeaders(),
      withCredentials: true,
    });
  }

  // cookie의 accessToken을 받아옵니다.
  getHeaders() {
    let cookie = document.cookie;
    let cookieToken;
    let headers;
    if (cookie.includes(';') && cookie.includes('accessToken')) {
      const cookieList = cookie.split(';');
      const findAccessToken = cookieList.filter((cookie: string) => {
        return cookie.includes('accessToken');
      });
      cookieToken = findAccessToken[0].split('=')[1];
    } else if (!cookie.includes(';') && cookie.includes('accessToken')) {
      cookieToken = cookie.split('=')[1];
    }
    if (cookieToken) {
      headers = {
        Authorization: `Bearer ${cookieToken}`,
      };

      return headers;
    }
  }
}

 

chatService.postChats(roomsId, chat)

방의 아이디와 채팅 내용을 보내주게 됩니다.

728x90

'토이프로젝트 > banthing' 카테고리의 다른 글

변수명 리팩토링  (0) 2022.05.25
banthing 프로젝트 리뷰  (0) 2022.05.25