コードレビュー中級15

レビュー: API応答の処理

typescriptapierror-handlingvalidation

コードレビュー課題

以下のTypeScriptコードをレビューしてください。

背景

外部APIからデータを取得して処理する関数です。エラーハンドリングとデータ検証に問題があります。

レビュー観点

  • HTTPステータスコードの処理
  • レスポンスデータの検証
  • エラーハンドリング
  • ネットワークエラーへの対応

あなたの回答

productApi.tstypescript
interface Product {
id: number;
name: string;
price: number;
stock: number;
}
async function fetchProducts(): Promise<Product[]> {
const response = await fetch('/api/products');
const data = await response.json() as Product[];
return data;
}
async function getProductById(id: number): Promise<Product> {
const response = await fetch(`/api/products/${id}`);
const product = await response.json();
return product;
}
export { fetchProducts, getProductById };
行番号をクリックしてコメントを追加(Shift+クリックで範囲選択)

最低100文字必要です

0

コメントを追加し、サマリーを100文字以上入力してください

模範解答

回答を送信するか、「表示する」をクリックすると模範解答が表示されます。