- Spring Boot 后端服务 (hss-home-service) - delivery-miniapp 配送小程序 - website 官网 (Nuxt) - docs 架构设计文档 - Docker 容器化部署配置 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
type ApiResponse<T> = {
|
|
code: number | string
|
|
message: string
|
|
data: T
|
|
requestId?: string
|
|
timestamp?: number
|
|
}
|
|
|
|
const BASE = typeof window !== 'undefined'
|
|
? window.location.protocol + '//' + window.location.host + '/api/hss'
|
|
: '/api/hss'
|
|
|
|
export function useApi() {
|
|
function headers(extra?: Record<string, string>): Record<string, string> {
|
|
const h: Record<string, string> = { 'Content-Type': 'application/json', 'X-Tenant-Id': '1', 'X-Org-Id': '1' }
|
|
if (typeof window !== 'undefined') {
|
|
const stored = localStorage.getItem('hss_platform_user')
|
|
if (stored) {
|
|
try {
|
|
const u = JSON.parse(stored)
|
|
h['X-User-Id'] = u.userId
|
|
h['X-User-Role'] = u.userRole
|
|
h['X-Tenant-Id'] = u.tenantId
|
|
h['X-Org-Id'] = u.orgId
|
|
} catch {}
|
|
}
|
|
}
|
|
return { ...h, ...extra }
|
|
}
|
|
|
|
async function get<T>(path: string): Promise<T> {
|
|
const res = await $fetch<ApiResponse<T>>(BASE + path, { headers: headers() })
|
|
if (typeof res.code === 'string' ? (res.code !== '200' && res.code !== 'SUCCESS') : res.code !== 200) {
|
|
throw new Error(res.message || 'API error')
|
|
}
|
|
return res.data
|
|
}
|
|
|
|
async function post<T>(path: string, body?: any): Promise<T> {
|
|
const h = headers()
|
|
if (body) h['Idempotency-Key'] = 'web-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8)
|
|
const res = await $fetch<ApiResponse<T>>(BASE + path, { method: 'POST', headers: h, body: body ? JSON.stringify(body) : undefined })
|
|
if (typeof res.code === 'string' ? (res.code !== '200' && res.code !== 'SUCCESS') : res.code !== 200) {
|
|
throw new Error(res.message || 'API error')
|
|
}
|
|
return res.data
|
|
}
|
|
|
|
async function rawGet<T>(path: string): Promise<ApiResponse<T>> {
|
|
return await $fetch<ApiResponse<T>>(BASE + path, { headers: headers() })
|
|
}
|
|
|
|
return { get, post, rawGet }
|
|
}
|