TIL_2023_08_15

이종현·2023년 8월 16일
0

Today_I_Learned

목록 보기
82/145
post-thumbnail

Today 요약

  1. 프로젝트 리팩토링, 피드백 답변

1. What I did?

1. 1 프로젝트 리팩토링, 피드백 답변

  • interceptors를 이용한 ApiClient 리팩토링

    import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
    
    class APIClient {
      private readonly api: AxiosInstance
      headers: Record<string, string>
      baseURL: string
    
      constructor(
        baseURL: string,
        localToken: string,
        config?: AxiosRequestConfig
      ) {
        this.baseURL = baseURL
        this.api = axios.create({ baseURL, ...config })
        this.headers = {
          Authorization: `Bearer ${localToken}`,
          'Content-Type': 'application/json'
        }
    
        this.api.defaults.headers.common = this.headers
    
        this.api.interceptors.response.use(
          (response) => response,
          (error) => {
            throw new Error(error.message)
          }
        )
      }
    
      get(endpoint: string) {
        return this.api.get(endpoint)
      }
    
      post(endpoint: string, body: Record<string, string>) {
        return this.api.post(endpoint, body)
      }
    
      put(endpoint: string, body: Record<string, string | boolean>) {
        return this.api.put(endpoint, body)
      }
    
      delete(endpoint: string) {
        return this.api.delete(endpoint)
      }
    }
    
    export default APIClient
    • 좀 헤맸던 부분은 interceptors를 사용하게 되면 인스턴스 객체 구조가 바뀔 수 있기 때문에 기존에 api통신해서 res로 받아왔던 데이터를 res.data로 받아와야지만 사용이 가능했다. 그래서 auth관련 todo 관련 api로직도 수정해서 해결했다.

1.2 슬랙 질문에 피드백 답변하기

  • var의 호이스팅과 함수 호이스팅의 차이점에 대해 좀 더 자세하게 설명하기
    • 자바스크립트는 코드 실행을 위해 평가와 실행 단계를 거칩니다. 평가 단계에서는 변수 및 함수 선언문을 메모리에 등록하여 스코프와 관련된 작업을 수행합니다. 이 때, 코드 실행 전에 선언문이 마치 끌어올려진 것처럼 보이기 때문에 호이스팅이라고 합니다.
      함수 선언문은 평가 단계에서 전체가 메모리에 등록되므로 선언 이전에 함수를 호출할 수 있습니다. 이에 반해, var 변수 선언은 선언 부분만 평가 단계에서 등록되며 할당은 실행 단계에서 이루어지기 때문에 호이스팅 동작이 조금 다릅니다.
      예를 들어 var a = 1; 의 경우 var a 는 선언 부분이 평가 단계에서 등록되며, a = 1 은 실행 단계에서 할당됩니다. 이로 인해 a는 선언 단계에서 메모리에 등록되어 undefined 로 초기화되며, 실행 단계에서 실제 값인 1로 할당됩니다.

profile
데이터리터러시를 중요하게 생각하는 프론트엔드 개발자

1개의 댓글

comment-user-thumbnail
2023년 8월 16일

좋은 글이네요. 공유해주셔서 감사합니다.

답글 달기