Parçacıklara Dön
TypeScriptTypeScript

TypeScript Genel API İstemcisi

Jenerikler ve interceptor'lar ile tip güvenli, yeniden kullanılabilir HTTP istemcisi.

typescriptapifetchgeneric
interface ApiResponse<T> {
  data: T
  status: number
}

class ApiClient {
  constructor(private baseUrl: string, private headers: Record<string, string> = {}) {}

  private async request<T>(endpoint: string, options?: RequestInit): Promise<ApiResponse<T>> {
    const res = await fetch(class="text-emerald-400">`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: { class=class="text-emerald-400">"text-emerald-400">'Content-Type': class=class="text-emerald-400">"text-emerald-400">'application/json', ...this.headers, ...options?.headers },
    })
    if (!res.ok) throw new Error(class="text-emerald-400">`HTTP ${res.status}: ${res.statusText}`)
    const data = await res.json()
    return { data, status: res.status }
  }

  get<T>(endpoint: string) {
    return this.request<T>(endpoint)
  }

  post<T>(endpoint: string, body: unknown) {
    return this.request<T>(endpoint, { method: class=class="text-emerald-400">"text-emerald-400">'POST', body: JSON.stringify(body) })
  }

  put<T>(endpoint: string, body: unknown) {
    return this.request<T>(endpoint, { method: class=class="text-emerald-400">"text-emerald-400">'PUT', body: JSON.stringify(body) })
  }

  delete<T>(endpoint: string) {
    return this.request<T>(endpoint, { method: class=class="text-emerald-400">"text-emerald-400">'DELETE' })
  }
}

export const api = new ApiClient(class=class="text-emerald-400">"text-emerald-400">'/api', { Authorization: class=class="text-emerald-400">"text-emerald-400">'Bearer token' })

Nasıl Kullanılır

Bir instance oluşturun ve tipli metodları çağırın: const { data } = await api.get<User[]>('/users'). TypeScript yanıt tipini otomatik olarak çıkarır. Yapıcıda kimlik doğrulama token'ları gibi varsayılan başlıkları ayarlayın.

İlgili Teknoloji

TypeScript

Aklınızda Bir Proje mi Var?

Fikrinizi birlikte hayata geçirelim. 50+ teslim edilmiş projeyle sizi konseptten yayına hazır bir ürüne taşıyor; sabit fiyatlı tekliflerle özel yazılım geliştirme sunuyoruz. Hiçbir taahhüt olmadan ücretsiz danışmanlık alın.

veya ücretsiz görüşme ayarlayın