首次提交
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
|
||||
const API_URL = 'http://localhost:8080'
|
||||
const TOKEN_KEY = 'auth_token'
|
||||
const USER_KEY = 'auth_user'
|
||||
|
||||
interface ApiResponse<T> { code: number; message: string; data?: T }
|
||||
|
||||
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json', ...(options.headers as any) }
|
||||
const token = await AsyncStorage.getItem(TOKEN_KEY)
|
||||
if (token) headers['Authorization'] = 'Bearer ' + token
|
||||
|
||||
const res = await fetch(API_URL + path, { ...options, headers })
|
||||
const body: ApiResponse<T> = await res.json()
|
||||
if (body.code !== 0) throw new Error(body.message)
|
||||
return body.data as T
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(p: string) => request<T>(p),
|
||||
post: <T>(p: string, d?: unknown) => request<T>(p, { method: 'POST', body: JSON.stringify(d) }),
|
||||
put: <T>(p: string, d?: unknown) => request<T>(p, { method: 'PUT', body: JSON.stringify(d) }),
|
||||
del: <T>(p: string) => request<T>(p, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
export async function saveToken(token: string, user: any) {
|
||||
await AsyncStorage.setItem(TOKEN_KEY, token)
|
||||
await AsyncStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||
}
|
||||
|
||||
export async function getStoredUser(): Promise<any | null> {
|
||||
const raw = await AsyncStorage.getItem(USER_KEY)
|
||||
return raw ? JSON.parse(raw) : null
|
||||
}
|
||||
|
||||
export async function getStoredToken(): Promise<string | null> {
|
||||
return AsyncStorage.getItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export async function clearAuth() {
|
||||
await AsyncStorage.multiRemove([TOKEN_KEY, USER_KEY])
|
||||
}
|
||||
Reference in New Issue
Block a user