TypeScript โปรเจกต์: typed API client



สร้าง HTTP client ที่ (1) validate response ด้วย zod (2) infer type จาก schema (3) error ที่ type ชัด

เป้าหมาย

const api = new ApiClient("https://api.example.com");

const user = await api.get("/users/1", UserSchema);
//    ^ User (validated!)

const created = await api.post("/users", CreateUserSchema, { name: "อร", email: "a@b.com" });

setup

npm init -y && npm pkg set type=module
npm install zod
npm install --save-dev typescript tsx @types/node vitest

src/errors.ts

export type ApiError =
  | { kind: "network"; message: string; cause: unknown }
  | { kind: "http"; status: number; body: unknown }
  | { kind: "validation"; issues: string[]; body: unknown }
  | { kind: "parse"; message: string };

export class ApiClientError extends Error {
  constructor(public readonly error: ApiError) {
    super(describe(error));
    this.name = "ApiClientError";
  }
}

function describe(error: ApiError): string {
  switch (error.kind) {
    case "network": return `เชื่อมต่อไม่ได้: ${error.message}`;
    case "http": return `HTTP ${error.status}`;
    case "validation": return `response ไม่ตรง schema: ${error.issues.join(", ")}`;
    case "parse": return `parse response ไม่ได้: ${error.message}`;
  }
}

src/client.ts

import { z, type ZodType } from "zod";
import { ApiClientError, type ApiError } from "./errors.js";

interface RequestOptions {
  headers?: Record<string, string>;
  signal?: AbortSignal;
  timeoutMs?: number;
}

export class ApiClient {
  constructor(
    private readonly baseUrl: string,
    private readonly defaultHeaders: Record<string, string> = {},
  ) {}

  async get<T>(path: string, schema: ZodType<T>, options?: RequestOptions): Promise<T> {
    return this.request("GET", path, schema, undefined, options);
  }

  async post<T, B>(
    path: string,
    responseSchema: ZodType<T>,
    body: B,
    options?: RequestOptions,
  ): Promise<T> {
    return this.request("POST", path, responseSchema, body, options);
  }

  async put<T, B>(
    path: string,
    responseSchema: ZodType<T>,
    body: B,
    options?: RequestOptions,
  ): Promise<T> {
    return this.request("PUT", path, responseSchema, body, options);
  }

  async delete<T>(path: string, schema: ZodType<T>, options?: RequestOptions): Promise<T> {
    return this.request("DELETE", path, schema, undefined, options);
  }

  private async request<T>(
    method: string,
    path: string,
    schema: ZodType<T>,
    body: unknown,
    options: RequestOptions = {},
  ): Promise<T> {
    const url = new URL(path, this.baseUrl).toString();
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 10_000);

    let response: Response;
    try {
      response = await fetch(url, {
        method,
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          ...this.defaultHeaders,
          ...options.headers,
        },
        body: body === undefined ? undefined : JSON.stringify(body),
        signal: options.signal ?? controller.signal,
      });
    } catch (cause) {
      throw this.fail({
        kind: "network",
        message: cause instanceof Error ? cause.message : String(cause),
        cause,
      });
    } finally {
      clearTimeout(timeout);
    }

    let json: unknown;
    try {
      const text = await response.text();
      json = text ? JSON.parse(text) : null;
    } catch (cause) {
      throw this.fail({
        kind: "parse",
        message: cause instanceof Error ? cause.message : String(cause),
      });
    }

    if (!response.ok) {
      throw this.fail({ kind: "http", status: response.status, body: json });
    }

    const result = schema.safeParse(json);
    if (!result.success) {
      throw this.fail({
        kind: "validation",
        issues: result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`),
        body: json,
      });
    }
    return result.data;
  }

  private fail(error: ApiError): ApiClientError {
    return new ApiClientError(error);
  }
}

src/api.ts — endpoint schemas

import { z } from "zod";
import { ApiClient } from "./client.js";

export const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
});
export type User = z.infer<typeof UserSchema>;

export const UserListSchema = z.array(UserSchema);

const CreateUserSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
});
type CreateUser = z.infer<typeof CreateUserSchema>;

// typed API layer — ปิด schema เป็น method ที่อ่านง่าย
export class UserApi {
  constructor(private client: ApiClient) {}

  list(): Promise<User[]> {
    return this.client.get("/users", UserListSchema);
  }

  getById(id: number): Promise<User> {
    return this.client.get(`/users/${id}`, UserSchema);
  }

  create(data: CreateUser): Promise<User> {
    // validate input ก่อนส่ง
    const validated = CreateUserSchema.parse(data);
    return this.client.post("/users", UserSchema, validated);
  }
}

ใช้งาน

import { ApiClient } from "./client.js";
import { UserApi } from "./api.js";
import { ApiClientError } from "./errors.js";

const client = new ApiClient("https://jsonplaceholder.typicode.com");
const users = new UserApi(client);

try {
  const list = await users.list();
  console.log(`มี ${list.length} users`);

  const user = await users.getById(1);
  console.log(user.name, user.email);   // typed + validated
} catch (error) {
  if (error instanceof ApiClientError) {
    switch (error.error.kind) {
      case "network":
        console.error("เครือข่ายมีปัญหา ลองใหม่");
        break;
      case "http":
        console.error(`server ตอบ ${error.error.status}`);
        break;
      case "validation":
        console.error("response ไม่ตรงที่คาด:", error.error.issues);
        break;
      case "parse":
        console.error("response ไม่ใช่ JSON");
        break;
    }
  }
}

test — ด้วย mock fetch

import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiClient } from "./client.js";
import { z } from "zod";

const Schema = z.object({ id: z.number(), name: z.string() });

describe("ApiClient", () => {
  beforeEach(() => vi.restoreAllMocks());

  it("validate + return typed data", async () => {
    vi.stubGlobal("fetch", vi.fn().mockResolvedValue(
      new Response(JSON.stringify({ id: 1, name: "อร" }), { status: 200 }),
    ));

    const client = new ApiClient("https://x.test");
    const result = await client.get("/item/1", Schema);
    expect(result).toEqual({ id: 1, name: "อร" });
  });

  it("throw validation error เมื่อ shape ผิด", async () => {
    vi.stubGlobal("fetch", vi.fn().mockResolvedValue(
      new Response(JSON.stringify({ id: "not-a-number" }), { status: 200 }),
    ));

    const client = new ApiClient("https://x.test");
    await expect(client.get("/item/1", Schema)).rejects.toThrow(/schema/);
  });

  it("throw http error เมื่อ 404", async () => {
    vi.stubGlobal("fetch", vi.fn().mockResolvedValue(
      new Response("Not Found", { status: 404 }),
    ));

    const client = new ApiClient("https://x.test");
    await expect(client.get("/item/999", Schema)).rejects.toMatchObject({
      error: { kind: "http", status: 404 },
    });
  });
});

จุดที่ใช้ความรู้จากบทก่อน

ส่วนบท
generic method <T>(path, schema: ZodType<T>): Promise<T>11, 12
zod safeParse + z.infer30
discriminated union ApiError + exhaustive switch7, 27
custom error class extends Error27
catch (cause: unknown) narrowing26
AbortController timeout26
fetch + response handling33
mock fetch ในเทสต์34

ต่อยอด

  • retry 5xx / network ด้วย exponential backoff
  • auth — interceptor เพิ่ม Authorization header, refresh token
  • query params helper (URLSearchParams)
  • request/response logging
  • Result type แทน throw (บทที่ 27): Promise<Result<T, ApiError>>
  • openapi-typescript ถ้ามี OpenAPI spec (บทที่ 40)

เรื่องที่คนมักพลาด

  • fetch แล้วไม่ validate — as User; ต้อง schema.safeParse
  • ไม่แยก error kind — “something went wrong” ทั้งหมด; discriminated union ให้ caller จัดการต่าง
  • ไม่มี timeout — request ค้าง; AbortController + setTimeout
  • response.json() โดยตรง — throw ถ้าไม่ใช่ JSON (404 HTML); text() แล้ว JSON.parse ใน try
  • validate response ก่อนเช็ค response.ok — error body ({error: ...}) ไม่ตรง success schema; เช็ค .ok ก่อน
  • generic <T, B> แล้ว B ไม่ถูกใช้ — B แค่ช่วย infer type ของ body argument

สรุป

  • generic method: get<T>(path, schema: ZodType<T>): Promise<T> — schema กำหนดทั้ง validate และ type
  • flow: fetch (catch → network) → text + JSON.parse (catch → parse) → เช็ค .ok (→ http) → schema.safeParse (→ validation) → return result.data
  • error เป็น discriminated union (ApiError) — caller switch (error.kind) จัดการต่างกัน
  • typed API layer (UserApi) ปิด schema เป็น method อ่านง่าย + validate input ก่อนส่ง
  • test: vi.stubGlobal("fetch", ...) mock response, rejects.toMatchObject

บทถัดไป โปรเจกต์ REST API — Express + TS + SQLite, typed end to end + Vitest