프로그래머스 커피 주문 페이지 만들기 - 개발 (API)

Z6su3·2022년 5월 9일
0

구조는 다음과 같습니다.

/api ← api.js

제시된 기본 API_END_POINT는 다음과 같습니다

[https://uikt6pohhh.execute-api.ap-northeast-2.amazonaws.com/dev/products](https://uikt6pohhh.execute-api.ap-northeast-2.amazonaws.com/dev/products)

이에 productId가 존재할 때, 추가하여 요청하면 다음과 같이 구현할 수 있습니다.

api.js

const API_END_POINT =
  "https://uikt6pohhh.execute-api.ap-northeast-2.amazonaws.com/dev/products";

export const request = async (state) => {
  const res = await fetch(`
    ${API_END_POINT}
    ${state.productId ? `/${state.productId}` : ""}
  `);
  switch (res.status / 100) {
    case 5:
      throw new Error(`Server error with status code ${res.status}`);
    case 4:
      throw new Error(`Client error with status code ${res.status}`);
    case 3:
      throw new Error(`Redirect error with status code ${res.status}`);
    default:
      return res.json();
  }
};

API요청 상태에 따른 결과를 인지할 수 있도록 위와 같이 구현하였습니다.

state로 넘어오는 값은, history.state를 통해 data가 json object로 들어와 state의 productId를 활용해줍니다.

한가지 문제점은, programmers의 vscode환경을 제외한 곳에서 API를 요청하면 CORS Error가 나오게됩니다. local 환경에서 개발을 하고 테스트를 진행하시려면, 다음과 같이 진행하시면 될 것 같습니다.

  • /api ← product.json = products data
  • /api ← product-details.json = product detail datas

product.json

[
	{
		"id": ?,
		"name": ?,
		"imageUrl": ?,
		"price": ?,
	},
	...
]

product-details.json

{
  "1": {
    "id": ?,
    "name": ?,
    "price": ?,
    "imageUrl": ?,
    "productOptions": [
      {
        "id": ?,
        "name": ?,
        "price": ?,
        "stock": ?,
        "created_at": ?,
        "updated_at": ?
      },
			...
		]
	},
	...
}

api.js

import product from "./product.json" assert { type: "json" };
import details from "./product-details.json" assert { type: "json" };

export const request = async (state) => {
  const res = !state ? product : details[state.productId];

  return res;
};

json 데이터는 단순 데이터가 아니라 JavaScript가 될 수 있고 실행될 수 있다는 가정이 걸려있습니다.

json파일을 index.html내 모듈로 삽입하거나, 위와같이 ES모듈로 인식하고 import할 수 있게 assert { type: "json" };을 추가하여 json데이터를 가져올 수 있다.

추가 정보로 json모듈은 동적으로도 가져올 수 있다.

const { default: jsonObject } = await import("./data.json, {
	assert: {
		type: "json"
	}
});
profile
기억은 기록을 이길수 없다

0개의 댓글