示例工程 32-capstone-quality-gates
32-capstone-quality-gates/02-api-client/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
export interface User {
id: number;
name: string;
}
export function isUser(value: unknown): value is User {
if (typeof value !== 'object' || value === null) return false;
const record = value as Record<string, unknown>;
return typeof record['id'] === 'number' && typeof record['name'] === 'string';
}
export interface HttpResponseLike {
ok: boolean;
status: number;
json(): Promise<unknown>;
}
export type Fetcher = (url: string, init?: RequestInit) => Promise<HttpResponseLike>;
export async function fetchUser(fetcher: Fetcher, path: string): Promise<User> {
const response = await fetcher(path);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data: unknown = await response.json();
if (!isUser(data)) throw new Error('invalid user payload');
return data;
}
export async function run(log: (msg: string) => void = console.log): Promise<string[]> {
if (typeof fetch === 'undefined' || typeof location === 'undefined') {
throw new Error('本示例需要浏览器环境');
}
const user = await fetchUser((url, init) => fetch(url, init), './data/user.json');
const lines = [`${user.id}:${user.name}`];
for (const line of lines) {
log(line);
}
return lines;
}