chore: initial commit
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import axios, { AxiosHeaders } from 'axios'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ApiResponseError, getApiErrorDetails, unwrapApiResponse } from './http'
|
||||
|
||||
describe('API error diagnostics', () => {
|
||||
it('keeps business request and trace identifiers when unwrapping fails', () => {
|
||||
expect(() => unwrapApiResponse({
|
||||
code: 'A0403',
|
||||
message: '无权限',
|
||||
data: null,
|
||||
requestId: 'request-1',
|
||||
traceId: 'trace-1',
|
||||
})).toThrow(ApiResponseError)
|
||||
|
||||
try {
|
||||
unwrapApiResponse({ code: 'A0403', message: '无权限', data: null, requestId: 'request-1', traceId: 'trace-1' })
|
||||
} catch (error) {
|
||||
expect(getApiErrorDetails(error)).toEqual({
|
||||
message: '无权限',
|
||||
code: 'A0403',
|
||||
requestId: 'request-1',
|
||||
traceId: 'trace-1',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('extracts identifiers from an HTTP error envelope', () => {
|
||||
const error = new axios.AxiosError('Request failed', 'ERR_BAD_RESPONSE', undefined, undefined, {
|
||||
status: 503,
|
||||
statusText: 'Service Unavailable',
|
||||
headers: {},
|
||||
config: { headers: new AxiosHeaders() },
|
||||
data: { code: 'S0503', message: '服务不可用', requestId: 'request-2', traceId: 'trace-2' },
|
||||
})
|
||||
|
||||
expect(getApiErrorDetails(error)).toEqual({
|
||||
message: '服务不可用',
|
||||
code: 'S0503',
|
||||
requestId: 'request-2',
|
||||
traceId: 'trace-2',
|
||||
})
|
||||
})
|
||||
})
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import axios, { type InternalAxiosRequestConfig } from 'axios'
|
||||
|
||||
export interface ApiEnvelope<T> {
|
||||
code: string
|
||||
message: string
|
||||
data: T
|
||||
requestId?: string | null
|
||||
traceId?: string | null
|
||||
timestamp?: string
|
||||
}
|
||||
|
||||
export class ApiResponseError extends Error {
|
||||
readonly code: string
|
||||
readonly status?: number
|
||||
readonly details?: unknown
|
||||
readonly requestId?: string
|
||||
readonly traceId?: string
|
||||
|
||||
constructor(message: string, code: string, status?: number, details?: unknown, requestId?: string | null, traceId?: string | null) {
|
||||
super(message)
|
||||
this.name = 'ApiResponseError'
|
||||
this.code = code
|
||||
this.status = status
|
||||
this.details = details
|
||||
this.requestId = requestId || undefined
|
||||
this.traceId = traceId || undefined
|
||||
}
|
||||
}
|
||||
|
||||
export interface ApiErrorDetails {
|
||||
message: string
|
||||
code?: string
|
||||
requestId?: string
|
||||
traceId?: string
|
||||
}
|
||||
|
||||
export const http = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
||||
timeout: 15_000,
|
||||
})
|
||||
|
||||
type RetryableRequestConfig = InternalAxiosRequestConfig & { _authRetry?: boolean }
|
||||
type AuthRefreshHandler = () => Promise<string>
|
||||
|
||||
let authRefreshHandler: AuthRefreshHandler | null = null
|
||||
let activeRefresh: Promise<string> | null = null
|
||||
|
||||
export function registerAuthRefreshHandler(handler: AuthRefreshHandler) {
|
||||
authRefreshHandler = handler
|
||||
}
|
||||
|
||||
http.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('cc-admin-token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
http.interceptors.response.use(
|
||||
(response) => response.data,
|
||||
async (error) => {
|
||||
const config = error.config as RetryableRequestConfig | undefined
|
||||
const isAuthEndpoint = typeof config?.url === 'string' && config.url.startsWith('/auth/')
|
||||
if (error.response?.status !== 401 || !config || config._authRetry || isAuthEndpoint || !authRefreshHandler) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
config._authRetry = true
|
||||
try {
|
||||
if (!activeRefresh) {
|
||||
activeRefresh = authRefreshHandler().finally(() => { activeRefresh = null })
|
||||
}
|
||||
const nextToken = await activeRefresh
|
||||
config.headers.Authorization = `Bearer ${nextToken}`
|
||||
return http.request(config)
|
||||
} catch {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export function unwrapApiResponse<T>(response: ApiEnvelope<T>): T {
|
||||
if (response?.code !== '0') {
|
||||
throw new ApiResponseError(
|
||||
response?.message || '接口请求失败',
|
||||
response?.code || 'UNKNOWN',
|
||||
undefined,
|
||||
response?.data,
|
||||
response?.requestId,
|
||||
response?.traceId,
|
||||
)
|
||||
}
|
||||
return response.data
|
||||
}
|
||||
|
||||
export function getApiErrorDetails(error: unknown, fallback = '接口请求失败'): ApiErrorDetails {
|
||||
if (error instanceof ApiResponseError) {
|
||||
return { message: error.message, code: error.code, requestId: error.requestId, traceId: error.traceId }
|
||||
}
|
||||
if (axios.isAxiosError(error)) {
|
||||
const response = error.response?.data as {
|
||||
code?: string
|
||||
message?: string
|
||||
error?: string
|
||||
requestId?: string | null
|
||||
traceId?: string | null
|
||||
} | undefined
|
||||
return {
|
||||
message: response?.message || response?.error || fallback,
|
||||
code: response?.code || (error.response?.status ? `HTTP_${error.response.status}` : undefined),
|
||||
requestId: response?.requestId || undefined,
|
||||
traceId: response?.traceId || undefined,
|
||||
}
|
||||
}
|
||||
return { message: error instanceof Error ? error.message : fallback }
|
||||
}
|
||||
|
||||
export function getApiErrorMessage(error: unknown, fallback = '接口请求失败'): string {
|
||||
return getApiErrorDetails(error, fallback).message
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/api/http'
|
||||
import {
|
||||
createPlatformPermission,
|
||||
createPlatformRole,
|
||||
downloadTenantQualification,
|
||||
listTenantQualifications,
|
||||
listPlatformPermissions,
|
||||
listPlatformRoles,
|
||||
qualificationFileName,
|
||||
type PlatformPermissionResource,
|
||||
type PlatformRoleResource,
|
||||
} from './platformIam'
|
||||
|
||||
vi.mock('@/api/http', () => ({
|
||||
http: { get: vi.fn(), post: vi.fn() },
|
||||
unwrapApiResponse: <T>(response: { data: T }) => response.data,
|
||||
}))
|
||||
|
||||
const role: PlatformRoleResource = {
|
||||
id: 4000002,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
roleCode: 'CUSTOMER_REVIEWER',
|
||||
roleName: '企业审核员',
|
||||
roleType: 'SYSTEM',
|
||||
status: 'ACTIVE',
|
||||
description: '企业资料与入驻审核',
|
||||
}
|
||||
|
||||
const permission: PlatformPermissionResource = {
|
||||
id: 5100010,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'MENU',
|
||||
parentId: 5100000,
|
||||
permissionCode: 'platform:customer:list',
|
||||
permissionName: '企业客户',
|
||||
routePath: '/customers',
|
||||
httpMethod: null,
|
||||
sortNo: 10,
|
||||
status: 'ACTIVE',
|
||||
}
|
||||
|
||||
describe('platform IAM roles', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
})
|
||||
|
||||
it('loads roles from the platform IAM prefix', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '0', message: 'success', data: [role] })
|
||||
|
||||
await expect(listPlatformRoles()).resolves.toEqual([role])
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/roles')
|
||||
})
|
||||
|
||||
it('creates a platform role with the documented payload', async () => {
|
||||
const payload = {
|
||||
roleCode: 'CUSTOMER_REVIEWER',
|
||||
roleName: '企业审核员',
|
||||
description: '企业资料与入驻审核',
|
||||
}
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '0', message: 'success', data: role })
|
||||
|
||||
await expect(createPlatformRole(payload)).resolves.toEqual(role)
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/roles', payload)
|
||||
})
|
||||
|
||||
it('loads and creates permission resources under the platform IAM prefix', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '0', message: 'success', data: [permission] })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '0', message: 'success', data: permission })
|
||||
const payload = {
|
||||
type: 'MENU' as const,
|
||||
code: permission.permissionCode,
|
||||
name: permission.permissionName,
|
||||
parentId: permission.parentId,
|
||||
routePath: permission.routePath,
|
||||
httpMethod: null,
|
||||
sortNo: permission.sortNo,
|
||||
}
|
||||
|
||||
await expect(listPlatformPermissions()).resolves.toEqual([permission])
|
||||
await expect(createPlatformPermission(payload)).resolves.toEqual(permission)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/permissions')
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/permissions', payload)
|
||||
})
|
||||
|
||||
it('loads qualifications for the selected tenant', async () => {
|
||||
const qualification = {
|
||||
id: 12,
|
||||
tenantId: 8,
|
||||
qualificationType: 'BUSINESS_LICENSE',
|
||||
certificateNo: '91440300XXXXXXXXXX',
|
||||
documentUrl: '/api/merchant/v1/files/qualifications/license.png',
|
||||
status: 'PENDING' as const,
|
||||
reviewComment: null,
|
||||
}
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '0', message: 'success', data: [qualification] })
|
||||
|
||||
await expect(listTenantQualifications(8)).resolves.toEqual([qualification])
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/tenants/8/qualifications')
|
||||
})
|
||||
|
||||
it('downloads a qualification with the platform file endpoint and a safe filename', async () => {
|
||||
const blob = new Blob(['image'], { type: 'image/png' })
|
||||
vi.mocked(http.get).mockResolvedValue(blob)
|
||||
|
||||
expect(qualificationFileName('/api/merchant/v1/files/qualifications/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png?token=ignored')).toBe('营业执照.png')
|
||||
await expect(downloadTenantQualification(8, '/api/merchant/v1/files/qualifications/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png')).resolves.toBe(blob)
|
||||
expect(http.get).toHaveBeenCalledWith(
|
||||
'/platform/v1/files/qualifications/8/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png',
|
||||
{ responseType: 'blob' },
|
||||
)
|
||||
expect(() => qualificationFileName('/api/merchant/v1/files/qualifications/%2Fetc%2Fpasswd')).toThrow('资质文件地址无效')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/api/http'
|
||||
|
||||
export interface PlatformPermissionResource {
|
||||
id: number
|
||||
tenantId: number
|
||||
appCode: 'PLATFORM'
|
||||
permissionType: 'MENU' | 'BUTTON'
|
||||
parentId: number
|
||||
permissionCode: string
|
||||
permissionName: string
|
||||
routePath: string | null
|
||||
httpMethod: string | null
|
||||
sortNo: number
|
||||
status: 'ACTIVE' | 'INACTIVE'
|
||||
}
|
||||
|
||||
export interface EnterpriseReview {
|
||||
id: number
|
||||
tenantId: number
|
||||
status: 'PENDING' | 'APPROVED' | 'REJECTED'
|
||||
tenantName?: string | null
|
||||
tenantCode?: string | null
|
||||
qualificationId?: number | null
|
||||
qualificationType?: string | null
|
||||
certificateNo?: string | null
|
||||
documentUrl?: string | null
|
||||
contactName?: string | null
|
||||
contactPhone?: string | null
|
||||
contactEmail?: string | null
|
||||
submittedAt?: string | null
|
||||
createdAt?: string | null
|
||||
reviewComment?: string | null
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface PlatformTenantQualification {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
qualificationType: 'BUSINESS_LICENSE' | string
|
||||
certificateNo: string | null
|
||||
documentUrl: string
|
||||
status: 'PENDING' | 'APPROVED' | 'REJECTED'
|
||||
reviewComment: string | null
|
||||
}
|
||||
|
||||
export interface PlatformRoleResource {
|
||||
id: number
|
||||
tenantId: number
|
||||
appCode: 'PLATFORM'
|
||||
roleCode: string
|
||||
roleName: string
|
||||
roleType: 'SYSTEM' | 'CUSTOM' | string
|
||||
status: 'ACTIVE' | 'INACTIVE' | string
|
||||
description: string | null
|
||||
}
|
||||
|
||||
export interface CreatePlatformRoleRequest {
|
||||
roleCode: string
|
||||
roleName: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface CreatePlatformPermissionRequest {
|
||||
type: 'MENU' | 'BUTTON'
|
||||
code: string
|
||||
name: string
|
||||
parentId: number
|
||||
routePath: string | null
|
||||
httpMethod: null
|
||||
sortNo: number
|
||||
}
|
||||
|
||||
async function getData<T>(path: string): Promise<T> {
|
||||
const response = await http.get<ApiEnvelope<T>, ApiEnvelope<T>>(path)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
async function postData<T>(path: string, body: unknown): Promise<T> {
|
||||
const response = await http.post<ApiEnvelope<T>, ApiEnvelope<T>>(path, body)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export function listPlatformPermissions() {
|
||||
return getData<PlatformPermissionResource[]>('/platform/v1/iam/permissions')
|
||||
}
|
||||
|
||||
export function listEnterpriseReviews() {
|
||||
return getData<EnterpriseReview[]>('/platform/v1/iam/reviews')
|
||||
}
|
||||
|
||||
export function listTenantQualifications(tenantId: number | string) {
|
||||
return getData<PlatformTenantQualification[]>(`/platform/v1/iam/tenants/${tenantId}/qualifications`)
|
||||
}
|
||||
|
||||
export function qualificationFileName(documentUrl: string) {
|
||||
const path = documentUrl.split(/[?#]/, 1)[0]
|
||||
const encodedName = path.split('/').filter(Boolean).at(-1)
|
||||
if (!encodedName) throw new Error('资质文件地址无效')
|
||||
let fileName: string
|
||||
try {
|
||||
fileName = decodeURIComponent(encodedName)
|
||||
} catch {
|
||||
throw new Error('资质文件地址无效')
|
||||
}
|
||||
if (!fileName || fileName === '.' || fileName === '..' || /[\\/]/.test(fileName)) {
|
||||
throw new Error('资质文件地址无效')
|
||||
}
|
||||
return fileName
|
||||
}
|
||||
|
||||
export function downloadTenantQualification(tenantId: number | string, documentUrl: string) {
|
||||
const fileName = qualificationFileName(documentUrl)
|
||||
return http.get<Blob, Blob>(`/platform/v1/files/qualifications/${tenantId}/${encodeURIComponent(fileName)}`, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
}
|
||||
|
||||
export function listPlatformRoles() {
|
||||
return getData<PlatformRoleResource[]>('/platform/v1/iam/roles')
|
||||
}
|
||||
|
||||
export function createPlatformRole(payload: CreatePlatformRoleRequest) {
|
||||
return postData<PlatformRoleResource>('/platform/v1/iam/roles', payload)
|
||||
}
|
||||
|
||||
export function createPlatformPermission(payload: CreatePlatformPermissionRequest) {
|
||||
return postData<PlatformPermissionResource>('/platform/v1/iam/permissions', payload)
|
||||
}
|
||||
|
||||
export function approveEnterpriseReview(reviewId: number, comment: string) {
|
||||
return postData<unknown>(`/platform/v1/iam/reviews/${reviewId}/approve`, { comment })
|
||||
}
|
||||
|
||||
export function rejectEnterpriseReview(reviewId: number, comment: string) {
|
||||
return postData<unknown>(`/platform/v1/iam/reviews/${reviewId}/reject`, { comment })
|
||||
}
|
||||
Reference in New Issue
Block a user