File size: 2,321 Bytes
68f7925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { ZodError, type ZodSchema } from 'zod';

export async function parseApiResponse<T>(
  res: Response,
  schema: ZodSchema<T>,
): Promise<T> {
  if (!res.ok) {
    let errorMessage = `APIリクエストに失敗しました (${res.status})`;
    try {
      const contentType = res.headers.get('content-type');
      if (contentType?.includes('application/json')) {
        const errorData = await res.json();
        if (errorData?.error?.message) {
          errorMessage += `: ${errorData.error.message}`;
        }
      }
    } catch {
      // エラーレスポンスの読み取りに失敗
    }
    throw new Error(errorMessage);
  }

  const responseData = await res.json();

  // nullの場合はそのまま返す(NOT_FOUNDの場合)
  if (responseData === null) {
    return null as T;
  }

  // バックエンドが { data: T } 形式で返す場合の処理
  const data =
    responseData?.data !== undefined ? responseData.data : responseData;

  try {
    return schema.parse(data);
  } catch (error) {
    if (error instanceof ZodError) {
      // URLからAPIエンドポイント名を抽出
      const urlObj = new URL(res.url);
      const apiEndpoint = urlObj.pathname.replace('/api/rpc/', '');

      console.error(`[${apiEndpoint}] Zod validation error:`);
      console.error('API:', apiEndpoint);
      console.error('URL:', res.url);
      console.error('Status:', res.status);
      console.error('Schema:', (schema as any)._def?.typeName || 'unknown');
      console.error('Validation errors:');
      error.errors.forEach((err, index) => {
        console.error(`  Error ${index + 1}:`);
        console.error(`    Path: ${err.path.join('.')}`);
        console.error(`    Message: ${err.message}`);
        console.error(`    Code: ${err.code}`);
        if ('expected' in err && err.expected !== undefined) {
          console.error(`    Expected: ${err.expected}`);
        }
        if ('received' in err && err.received !== undefined) {
          console.error(`    Received: ${err.received}`);
        }
      });
      console.error('Response data:', JSON.stringify(responseData, null, 2));
      console.error('Processed data:', JSON.stringify(data, null, 2));
      throw error;
    }
    throw new Error('APIレスポンスのパースに失敗しました');
  }
}