본문 바로가기
Svelte

Rest API method 관련 코드 utils로 생성하여 관리하기

by 1two13 2023. 10. 30.
728x90
반응형

제목 그대로 Rest API 관련 코드들을 method 별로 정리하여 관리하면 추후에 fetch를 통한 통신을 할 때 관리하기에 매우 유용하다. 

 

import { API_URLS } from '../constants/apis';

/* eslint-disable class-methods-use-this */
class FetchService {
  private baseUrl = API_URLS.BASE;

  private async handleResponse(response: Response) {
    if (!response.ok) {
      const message = await response.text();
      throw new Error(message);
    }
    return response.json();
  }

  async get<T>(endpoint: string): Promise<T> {
    const url = new URL(`${this.baseUrl}${endpoint}`);
    try {
      const response = await fetch(url.toString());
      return await this.handleResponse(response);
    } catch (error) {
      console.error(`Error in GET ${url}: `, error);
      throw error;
    }
  }

  async post<T>(endpoint: string, body?: T) {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      return await this.handleResponse(response);
    } catch (error) {
      console.error(`Error in POST ${this.baseUrl}${endpoint}: `, error);
      throw error;
    }
  }

  async patch<T>(endpoint: string, body?: T) {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      return await this.handleResponse(response);
    } catch (error) {
      console.error(`Error in PATCH ${this.baseUrl}${endpoint}: `, error);
      throw error;
    }
  }

  async delete<T>(endpoint: string, body?: T) {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      return await this.handleResponse(response);
    } catch (error) {
      console.error(`Error in DELETE ${this.baseUrl}${endpoint}: `, error);
      throw error;
    }
  }
}

export default FetchService;

 

다른 컴포넌트에서 사용할 때는 아래와 같은 방식으로 사용해주면 된다. 

import { API_URLS } from '../constants/apis';
import type { EventType } from '../types/Event';
import FetchService from '../utils/fetch';

const Fetch = new FetchService();

const getDetectedEvent = async (id?: number): Promise<EventType[]> => {
  const result: EventType[] = await Fetch.get<EventType[]>(
    `${API_URLS.EVENT.DETECTION}${id ? `/${id}` : ''}`,
  );
  return result;
};

export default getDetectedEvent;
728x90
반응형

'Svelte' 카테고리의 다른 글

Svelte 파헤치기  (2) 2023.11.06
[svelte] $app/stores에서 제공되는 Page 활용하기  (0) 2023.10.30

댓글