Skip to content

Instantly share code, notes, and snippets.

@resultakak
Forked from mehmetext/defensive-programming.ts
Created December 19, 2025 13:04
Show Gist options
  • Select an option

  • Save resultakak/b20ab7c754e41a0ef81f09c0d8dbecb4 to your computer and use it in GitHub Desktop.

Select an option

Save resultakak/b20ab7c754e41a0ef81f09c0d8dbecb4 to your computer and use it in GitHub Desktop.
import { z } from "zod";
// 1. Şemayı Tanımla
// Zod, veriyi hem doğrular hem de dönüştürür
const UserSchema = z.object({
id: z.number(),
name: z.string().min(2),
email: z.string().email(),
// Backend null dönse bile biz fallback değer atıyoruz
role: z.enum(["admin", "user"]).default("user"),
isActive: z.boolean(),
});
// 2. Manuel interface yazmaya gerek yok! (DRY)
type User = z.infer<typeof UserSchema>;
async function fetchUserData(userId: number) {
const response = await fetch(`/api/users/${userId}`);
const rawData = await response.json();
// 3. Runtime Kontrolü
// Veriyi doğrudan kullanmak yerine şemadan geçiriyoruz.
const result = UserSchema.safeParse(rawData);
if (!result.success) {
// Veri beklediğimiz gibi değil!
console.error("API Contract Hatası:", result.error.format());
// Uygulamayı patlatmak yerine null dön veya hata mesajı göster
return null;
}
// 4. Artık %100 eminiz ki bu data güvenli.
// TypeScript de mutlu, biz de mutluyuz.
return result.data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment