init
This commit is contained in:
64
web/src/api.ts
Normal file
64
web/src/api.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
const BASE = '/api';
|
||||
|
||||
function token() { return localStorage.getItem('token') || ''; }
|
||||
function authHeaders() { return { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json; charset=utf-8' }; }
|
||||
|
||||
export interface SmsMessage {
|
||||
id: number;
|
||||
user_id: number;
|
||||
phone_number: string;
|
||||
contact_name: string | null;
|
||||
content: string;
|
||||
type: 'received' | 'sent';
|
||||
sms_date: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface SmsListResponse {
|
||||
messages: SmsMessage[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
async function parseError(res: Response): Promise<string> {
|
||||
try {
|
||||
const data = await res.json();
|
||||
return data.error || `${res.status} ${res.statusText}`;
|
||||
} catch {
|
||||
return `${res.status} ${res.statusText}`;
|
||||
}
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string) {
|
||||
const res = await fetch(`${BASE}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
if (!res.ok) throw new Error(await parseError(res));
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function register(username: string, password: string) {
|
||||
const res = await fetch(`${BASE}/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json; charset=utf-8' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
if (!res.ok) throw new Error(await parseError(res));
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function fetchSms(params: Record<string, string> = {}): Promise<SmsListResponse> {
|
||||
const qs = new URLSearchParams(params).toString();
|
||||
const res = await fetch(`${BASE}/sms?${qs}`, { headers: authHeaders() });
|
||||
if (!res.ok) throw new Error('Failed to fetch');
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function deleteSms(id: number) {
|
||||
const res = await fetch(`${BASE}/sms/${id}`, { method: 'DELETE', headers: authHeaders() });
|
||||
if (!res.ok) throw new Error('Delete failed');
|
||||
}
|
||||
Reference in New Issue
Block a user