Files
rice-pk-xhs/web/lib/api.js
T
codex-bot 2bf21a9f97
Verify mini program and deploy preview / verify-deploy (push) Successful in 3m0s
feat: migrate rice preview to Next.js
2026-09-20 14:22:47 +08:00

19 lines
1.2 KiB
JavaScript

'use client';
export async function apiRequest(path, options = {}) {
const token = typeof window === 'undefined' ? null : localStorage.getItem('rice_token');
const headers = { Accept: 'application/json', ...(options.headers || {}) };
if (options.body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers.Authorization = `Bearer ${token}`;
const response = await fetch(path, { method: options.method || 'GET', headers, body: options.body === undefined ? undefined : JSON.stringify(options.body), cache: 'no-store' });
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(typeof data.detail === 'string' ? data.detail : '请求失败');
return data;
}
export async function ensureLogin() {
if (localStorage.getItem('rice_token')) return;
let previewId = localStorage.getItem('rice_preview_id');
if (!previewId) { previewId = `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`; localStorage.setItem('rice_preview_id', previewId); }
const session = await apiRequest('/api/v1/auth/xhs', { method: 'POST', body: { app_key: 'rice', code: `dev:web-${previewId}` } });
localStorage.setItem('rice_token', session.token);
}