-
-
Save resultakak/b20ab7c754e41a0ef81f09c0d8dbecb4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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