UNPKG

@ha_tecno/react-native-sdk

Version:

React Native SDK for biometric authentication, liveness detection, and fingerprint recognition

83 lines (71 loc) 2.02 kB
import { getToken } from '../auth/tokenManager'; const BASE_URL = 'https://api.liveid.app.br'; class ApiError extends Error { status: number; constructor(status: number, message: string) { super(message); this.status = status; this.name = 'ApiError'; } } const request = async <T>( endpoint: string, options: RequestInit = {} ): Promise<T> => { const token = getToken(); if (!token) throw new Error('[HA-TECNO-SDK] Token não configurado.'); const res = await fetch(`${BASE_URL}${endpoint}`, { ...options, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, ...options.headers, }, }); if (!res.ok) { let errorMessage = ''; try { const errorBody = await res.json(); errorMessage = errorBody?.message || JSON.stringify(errorBody); } catch (e) { errorMessage = await res.text(); } throw new ApiError(res.status, errorMessage || 'Erro desconhecido'); } return res.json() as Promise<T>; }; const requestFormData = async <T>( endpoint: string, formData: FormData ): Promise<T> => { const token = getToken(); if (!token) throw new Error('[HA-TECNO-SDK] Token não configurado.'); const res = await fetch(`${BASE_URL}${endpoint}`, { method: 'POST', body: formData, headers: { Authorization: `Bearer ${token}`, }, }); if (!res.ok) { let errorMessage = ''; try { const errorBody = await res.json(); errorMessage = errorBody?.message || JSON.stringify(errorBody); } catch (e) { errorMessage = await res.text(); } throw new ApiError(res.status, errorMessage || 'Erro desconhecido'); } return res.json() as Promise<T>; }; export const api = { get: <T>(url: string) => request<T>(url), post: <T>(url: string, body: any) => request<T>(url, { method: 'POST', body: JSON.stringify(body), }), postFormData: <T>(url: string, formData: FormData) => requestFormData<T>(url, formData), };