完善配送端账户头像管理
This commit is contained in:
50
frontend/delivery_admin/src/api/avatar.ts
Normal file
50
frontend/delivery_admin/src/api/avatar.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 功能描述:提供配送点资源头像上传与鉴权读取。
|
||||
* 版本:v1.0.0。
|
||||
*/
|
||||
import { getToken } from '@/utils/auth';
|
||||
|
||||
const deliveryApiBaseURL =
|
||||
import.meta.env.VITE_API_BASE_URL || 'http://localhost:12426/heqi/delivery/v1';
|
||||
|
||||
export type AvatarUploadReply = {
|
||||
uri: string;
|
||||
original_name: string;
|
||||
content_type: string;
|
||||
size: number;
|
||||
};
|
||||
|
||||
type ApiEnvelope<T> = { code?: number; message?: string; details?: T };
|
||||
|
||||
/** 返回与现有配送点请求一致的 JWT 请求头。 */
|
||||
function authorizationHeaders(): Record<string, string> {
|
||||
const token = getToken();
|
||||
return token ? { Authorization: token } : {};
|
||||
}
|
||||
|
||||
/** 上传经过前端预检的头像文件。 */
|
||||
async function upload(file: File): Promise<AvatarUploadReply> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const baseURL = new URL(deliveryApiBaseURL, window.location.origin);
|
||||
const response = await fetch(new URL('/upload/avatar', baseURL.origin), {
|
||||
method: 'POST', headers: authorizationHeaders(), body: form,
|
||||
});
|
||||
const payload = (await response.json()) as ApiEnvelope<AvatarUploadReply>;
|
||||
if (!response.ok || payload.code !== 0 || !payload.details)
|
||||
throw new Error(payload.message || '头像上传失败');
|
||||
return payload.details;
|
||||
}
|
||||
|
||||
/** 读取配送点权限范围内的受保护头像。 */
|
||||
async function load(resource: string, identity: string): Promise<Blob | undefined> {
|
||||
const response = await fetch(
|
||||
`${deliveryApiBaseURL}${resource}/${encodeURIComponent(identity)}/avatar`,
|
||||
{ headers: authorizationHeaders() },
|
||||
);
|
||||
if (response.status === 404) return undefined;
|
||||
if (!response.ok) throw new Error('头像读取失败');
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
export const avatarApi = { upload, load };
|
||||
Reference in New Issue
Block a user