feat: 登录联调
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
export type LoginRole = 'super_admin' | 'doctor'
|
||||
|
||||
export interface LoginPayload {
|
||||
account: string
|
||||
password: string
|
||||
role: LoginRole
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
token: string
|
||||
raw: unknown
|
||||
}
|
||||
|
||||
function getTokenFromResponse(data: unknown): string {
|
||||
if (!data || typeof data !== 'object') {
|
||||
return ''
|
||||
}
|
||||
|
||||
const record = data as Record<string, unknown>
|
||||
const directToken = record.token || record.access_token || record.accessToken
|
||||
if (typeof directToken === 'string') {
|
||||
return directToken
|
||||
}
|
||||
|
||||
const nested = record.data
|
||||
if (nested && typeof nested === 'object') {
|
||||
return getTokenFromResponse(nested)
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
function getMessageFromResponse(data: unknown): string {
|
||||
if (!data || typeof data !== 'object') {
|
||||
return ''
|
||||
}
|
||||
|
||||
const record = data as Record<string, unknown>
|
||||
const message = record.message || record.msg || record.detail
|
||||
if (typeof message === 'string') {
|
||||
return message
|
||||
}
|
||||
|
||||
return getMessageFromResponse(record.data)
|
||||
}
|
||||
|
||||
function parseResponseText(text: string): unknown {
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(text)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function login(payload: LoginPayload): Promise<LoginResult> {
|
||||
const response = await fetch('/server/api/user/auth/login/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
|
||||
const text = await response.text()
|
||||
const data = parseResponseText(text)
|
||||
|
||||
if (!response.ok) {
|
||||
const message = getMessageFromResponse(data) || '登录失败,请检查账号、密码和角色'
|
||||
throw new Error(message)
|
||||
}
|
||||
|
||||
return {
|
||||
token: getTokenFromResponse(data),
|
||||
raw: data
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user