|

Day 60 of 100: TS Capstone Part 1 — The Typed, Guarded API Client

Day 60 of 100 — 100 Days of Playwright with TypeScript Challenge. Phase: TypeScript. JavaScript (Days 1-33) → TypeScript (Days 34-63) → Playwright (Days 64-96) → AI Framework Capstone (Days 97-100).

🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.


TypeScript phase capstone part 1: rebuild Day 33’s suite as a typed API client with guards, generics, and custom errors.

Contents

The Typed Client

// api-client.ts
export class ApiError extends Error {
  constructor(readonly status: number, readonly url: string) {
    super(`${status} from ${url}`);
    this.name = 'ApiError';
  }
}

export class ApiClient {
  constructor(private readonly baseUrl: string) {}

  async get(path: string, guard: (v: unknown) => v is T): Promise {
    const url = this.baseUrl + path;
    const res = await fetch(url);
    if (!res.ok) throw new ApiError(res.status, url);
    const body: unknown = await res.json();
    if (!guard(body)) throw new Error(`Unexpected shape from ${url}`);
    return body;
  }

  async post(path: string, payload: TReq,
    guard: (v: unknown) => v is TRes): Promise {
    const url = this.baseUrl + path;
    const res = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new ApiError(res.status, url);
    const body: unknown = await res.json();
    if (!guard(body)) throw new Error(`Unexpected shape from ${url}`);
    return body;
  }
}

🚀 Level Up Your Playwright

From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.

Types and Guards

// types.ts
export type User = { id: number; name: string; email: string };
export type NewUser = Omit;

export function isUser(v: unknown): v is User {
  return typeof v === 'object' && v !== null &&
    typeof (v as any).id === 'number' &&
    typeof (v as any).name === 'string' &&
    typeof (v as any).email === 'string';
}

export function isUserArray(v: unknown): v is User[] {
  return Array.isArray(v) && v.every(isUser);
}

Everything From the Phase, In Use

  • Generics + guards: get(path, guard) — Days 41, 47
  • Omit for creation payloads — Day 45
  • Custom error classes with readonly fields — Days 43, 54
  • unknown discipline at the boundary — Day 48
  • strict tsconfig keeps it all honest — Day 50

Tomorrow (Day 61): TS capstone part 2 — typed data factories and suite assembly.

🎓 Master Playwright End to End

Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.