63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
import type { FontListItem } from '../types/font'
|
||
|
||
interface FontMutationSuccessResponse {
|
||
success: true
|
||
fontList: FontListItem[]
|
||
}
|
||
|
||
interface FontMutationErrorResponse {
|
||
success: false
|
||
message?: string
|
||
}
|
||
|
||
type FontMutationResponse = FontMutationSuccessResponse | FontMutationErrorResponse
|
||
|
||
async function requestFontMutation(
|
||
endpoint: string,
|
||
payload: Record<string, string>,
|
||
): Promise<FontListItem[]> {
|
||
const response = await fetch(endpoint, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
body: JSON.stringify(payload),
|
||
})
|
||
|
||
let body: FontMutationResponse | null = null
|
||
try {
|
||
body = (await response.json()) as FontMutationResponse
|
||
} catch {
|
||
// ignore parse errors and fallback to status text
|
||
}
|
||
|
||
if (!response.ok || !body || body.success !== true) {
|
||
const message =
|
||
body && body.success === false && body.message
|
||
? body.message
|
||
: `请求失败(${response.status})`
|
||
throw new Error(message)
|
||
}
|
||
|
||
return body.fontList
|
||
}
|
||
|
||
/**
|
||
* 重命名字体文件并返回最新字体列表。
|
||
*/
|
||
export function renameFontFile(fontPath: string, newName: string): Promise<FontListItem[]> {
|
||
return requestFontMutation('/api/fonts/rename', {
|
||
path: fontPath,
|
||
newName,
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 删除字体文件并返回最新字体列表。
|
||
*/
|
||
export function deleteFontFile(fontPath: string): Promise<FontListItem[]> {
|
||
return requestFontMutation('/api/fonts/delete', {
|
||
path: fontPath,
|
||
})
|
||
}
|