본문 바로가기

카테고리 없음

ky란?

반응형

ky

  • fetch 보다 API를 훨씬 간편하게 불러올 수 있음
  • 메서드를 짧게 쓸 수 있음(ky.post())
  • redirect해보고, 2xx가 아닌 상태 코드는 모두 오류로 처리함
  • request에 실패하면 재요청함
  • JSON 옵션
  • 시간 초과 지원
  • URL prefix 옵션
  • default 값을 커스텀할 수 있음
  • hooks

 

예시

import ky from 'ky';

const json = await ky.post('<https://example.com>', {json: {foo: true}}).json();

console.log(json);
//=> `{data: '🦄'}`

위의 코드를 fetch 로 나타내면 이렇게 작성해야 한다.

class HTTPError extends Error {}

const response = await fetch('<https://example.com>', {
	method: 'POST',
	body: JSON.stringify({foo: true}),
	headers: {
		'content-type': 'application/json'
	}
});

if (!response.ok) {
	throw new HTTPError(`Fetch error: ${response.statusText}`);
}

const json = await response.json();

console.log(json);
//=> `{data: '🦄'}`

 

 

작성법

ky.get(input,options?) = ky(input,options)

ky.post(input,options?)

ky.put(input,options?)

ky.patch(input,options?)

ky.head(input,options?)

ky.delete(input,options?)

  • Response object가 반환된다. 그래서 Response를 기다리지 않고, ky.get(input)**.json()** 으로 직접 응답값을 가져올 수 있음.
  • 메서드를 작성하지 않으면 default 값은 get 임 (ky(input, options?))

 

프로젝트

  • hooks/api 파일에서 사용. 아래는 프로젝트 예시.
const getWorkspaces = async (): Promise<IGetWorkspacesResponse> => {
  const WorkspaceItems: IWorkspace[] = await ky(
    `${process.env.NEXT_PUBLIC_NEXT_API_URL}/workspaces/list`,
  ).json()

  return {
    WorkspaceItems,
  }
}

 

 


Tips

Sending form data

Sending form data in Ky is identical to fetch. Just pass a [FormData](<https://developer.mozilla.org/en-US/docs/Web/API/FormData>) instance to the body option. The Content-Type header will be automatically set to multipart/form-data.

import ky from 'ky';

// `multipart/form-data`
const formData = new FormData();
formData.append('food', 'fries');
formData.append('drink', 'icetea');

const response = await ky.post(url, {body: formData});

⇒ body에 FormData를 넣으면 자동으로 헤더에 multipart/form-data가 들어간다. 개꿀!

 

 

 

반응형