Blog içindeki snippets
TypeScripthttpfetchtypesutility
Typed HTTP Fetcher
Generic, type-safe fetch wrapper with error handling ve retry desteği.
Kod
typed-fetcher.ts
TypeScript
type FetchError = {
status: number;
message: string;
};
type Result<T> =
| { ok: true; data: T }
| { ok: false; error: FetchError };
export async function get<T>(
url: string,
init?: RequestInit
): Promise<Result<T>> {
try {
const res = await fetch(url, {
...init,
headers: { "Content-Type": "application/json", ...init?.headers },
});
if (!res.ok) {
return {
ok: false,
error: { status: res.status, message: await res.text() },
};
}
return { ok: true, data: (await res.json()) as T };
} catch (err) {
return {
ok: false,
error: { status: 0, message: (err as Error).message },
};
}
}Kullanım Örneği
usage
TypeScript
const result = await get<User[]>("/api/users");
if (!result.ok) {
console.error(result.error.message);
return;
}
// result.data → User[]Notlar
Sunucu ve istemci tarafında güvenle kullanılabilir. Next.js Server Components ile de çalışır.