Files
nl-blogs/client/src/services/api.ts
2026-01-15 13:51:44 +08:00

857 lines
22 KiB
TypeScript

export const API_BASE = 'http://localhost:8081/api'
// 通用请求头配置
export const getAuthHeaders = () => {
const token = localStorage.getItem('token')
return {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {})
}
}
// 认证相关类型
export interface User {
id: number
username: string
email: string
role: string
isActive: number
createdAt: string
updatedAt: string
}
export interface LoginRequest {
username: string
password: string
}
export interface LoginResponse {
token: string
user: User
expire: number
}
// 角色相关类型
export interface Role {
id: number
name: string
description: string
createdAt: string
updatedAt: string
}
// 作品相关类型
export interface Work {
id: string
title: string
category: string
year: string
heroImg: string
desc: string
techStack: { category: string; items: string[] }[]
gallery: string[]
links: { live: string }
next: string
}
// 文章相关类型
export interface Post {
id: string
title: string
category: string
date: string
excerpt?: string
content?: string
isPublished?: number
}
export interface PostHistory {
id: number
postId: string
version: number
title: string
category: string
excerpt?: string
content: string
isPublished: number
modifiedBy: number
modifiedAt: string
createdAt: string
}
// 代码片段相关类型
export interface Snippet {
id: string
title: string
code: string
type: string
description?: string
viewCount?: number
}
// 系统配置相关类型
export interface Setting {
id: number
keyName: string
value: string
description: string
createdAt: string
updatedAt: string
}
// 操作日志相关类型
export interface OperationLog {
id: number
userId: number
username: string
ip: string
path: string
method: string
params: string
status: number
duration: number
createdAt: string
}
// 分页响应类型
export interface PaginationResponse<T> {
list: T[]
total: number
page: number
size: number
}
// 登录API
export const login = async (credentials: LoginRequest): Promise<LoginResponse> => {
try {
const response = await fetch(`${API_BASE}/admin/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '登录失败')
}
return await response.json()
} catch (error) {
console.error('Login error:', error)
throw error
}
}
// 用户管理API
export const getUsers = async (): Promise<User[]> => {
try {
const response = await fetch(`${API_BASE}/admin/users`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取用户列表失败')
}
return await response.json()
} catch (error) {
console.error('Get users error:', error)
throw error
}
}
export const fetchUser = async (id: number): Promise<User> => {
try {
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取用户详情失败')
}
return await response.json()
} catch (error) {
console.error(`Error fetching user ${id}:`, error)
throw error
}
}
export const createUser = async (userData: Omit<User, 'id' | 'createdAt' | 'updatedAt'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/users`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(userData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '创建用户失败')
}
} catch (error) {
console.error('Create user error:', error)
throw error
}
}
export const updateUser = async (id: number, userData: Omit<User, 'id' | 'createdAt' | 'updatedAt'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(userData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '更新用户失败')
}
} catch (error) {
console.error('Update user error:', error)
throw error
}
}
export const deleteUser = async (id: number): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '删除用户失败')
}
} catch (error) {
console.error('Delete user error:', error)
throw error
}
}
// 角色管理API
export const getRoles = async (): Promise<Role[]> => {
try {
const response = await fetch(`${API_BASE}/admin/roles`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取角色列表失败')
}
return await response.json()
} catch (error) {
console.error('Get roles error:', error)
throw error
}
}
export const createRole = async (roleData: Omit<Role, 'id' | 'createdAt' | 'updatedAt'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/roles`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(roleData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '创建角色失败')
}
} catch (error) {
console.error('Create role error:', error)
throw error
}
}
export const updateRole = async (id: number, roleData: Omit<Role, 'id' | 'createdAt' | 'updatedAt'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/roles/${id}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(roleData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '更新角色失败')
}
} catch (error) {
console.error('Update role error:', error)
throw error
}
}
export const deleteRole = async (id: number): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/roles/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '删除角色失败')
}
} catch (error) {
console.error('Delete role error:', error)
throw error
}
}
export const fetchRole = async (id: number): Promise<Role> => {
try {
const response = await fetch(`${API_BASE}/admin/roles/${id}`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取角色详情失败')
}
return await response.json()
} catch (error) {
console.error(`Error fetching role ${id}:`, error)
throw error
}
}
// 作品管理API
export const getAdminWorks = async (): Promise<Work[]> => {
try {
const response = await fetch(`${API_BASE}/admin/works`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取作品列表失败')
}
return await response.json()
} catch (error) {
console.error('Get admin works error:', error)
throw error
}
}
export const fetchWorks = async (): Promise<Work[]> => {
try {
const response = await fetch(`${API_BASE}/works`)
if (!response.ok) throw new Error('Failed to fetch works')
return await response.json()
} catch (error) {
console.error('Error fetching works:', error)
return []
}
}
export const fetchWork = async (id: string): Promise<Work> => {
try {
const response = await fetch(`${API_BASE}/works/${id}`)
if (!response.ok) throw new Error('Failed to fetch work')
return await response.json()
} catch (error) {
console.error(`Error fetching work ${id}:`, error)
return {
id: 'default',
title: '默认作品',
category: '默认分类',
year: '2024',
heroImg: '',
desc: '',
techStack: [],
gallery: [],
links: { live: '#' },
next: ''
}
}
}
export const createWork = async (workData: Omit<Work, 'id' | 'next'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/works`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(workData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '创建作品失败')
}
} catch (error) {
console.error('Create work error:', error)
throw error
}
}
export const updateWork = async (id: string, workData: Omit<Work, 'id' | 'next'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/works/${id}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(workData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '更新作品失败')
}
} catch (error) {
console.error('Update work error:', error)
throw error
}
}
export const deleteWork = async (id: string): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/works/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '删除作品失败')
}
} catch (error) {
console.error('Delete work error:', error)
throw error
}
}
// 文章管理API
export const getAdminPosts = async (): Promise<Post[]> => {
try {
const response = await fetch(`${API_BASE}/admin/posts`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取文章列表失败')
}
return await response.json()
} catch (error) {
console.error('Get admin posts error:', error)
throw error
}
}
export const fetchPosts = async (): Promise<Post[]> => {
try {
const response = await fetch(`${API_BASE}/posts`)
if (!response.ok) throw new Error('Failed to fetch posts')
return await response.json()
} catch (error) {
console.error('Error fetching posts:', error)
return []
}
}
export const fetchPost = async (id: string): Promise<Post> => {
try {
const response = await fetch(`${API_BASE}/posts/${id}`)
if (!response.ok) throw new Error('Failed to fetch post')
return await response.json()
} catch (error) {
console.error(`Error fetching post ${id}:`, error)
return {
id: id,
title: '默认文章',
category: '默认分类',
date: '2024-01-01'
}
}
}
export const createPost = async (postData: Omit<Post, 'id'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/posts`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(postData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '创建文章失败')
}
} catch (error) {
console.error('Create post error:', error)
throw error
}
}
export const updatePost = async (id: string, postData: Omit<Post, 'id'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/posts/${id}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(postData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '更新文章失败')
}
} catch (error) {
console.error('Update post error:', error)
throw error
}
}
export const deletePost = async (id: string): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/posts/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '删除文章失败')
}
} catch (error) {
console.error('Delete post error:', error)
throw error
}
}
// 文章历史记录API
export const getPostHistory = async (postId: string): Promise<PostHistory[]> => {
try {
const response = await fetch(`${API_BASE}/admin/posts/${postId}/history`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取文章历史失败')
}
return await response.json()
} catch (error) {
console.error('Get post history error:', error)
throw error
}
}
export const getPostHistoryByVersion = async (postId: string, version: number): Promise<PostHistory> => {
try {
const response = await fetch(`${API_BASE}/admin/posts/${postId}/history/${version}`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取指定版本文章历史失败')
}
return await response.json()
} catch (error) {
console.error('Get post history by version error:', error)
throw error
}
}
// 代码片段管理API
export const getAdminSnippets = async (): Promise<Snippet[]> => {
try {
const response = await fetch(`${API_BASE}/admin/snippets`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取代码片段列表失败')
}
return await response.json()
} catch (error) {
console.error('Get admin snippets error:', error)
throw error
}
}
export const fetchSnippets = async (): Promise<Snippet[]> => {
try {
const response = await fetch(`${API_BASE}/snippets`)
if (!response.ok) throw new Error('Failed to fetch snippets')
return await response.json()
} catch (error) {
console.error('Error fetching snippets:', error)
return []
}
}
export const fetchSnippet = async (id: string): Promise<Snippet> => {
try {
const response = await fetch(`${API_BASE}/snippets/${id}`)
if (!response.ok) throw new Error('Failed to fetch snippet')
return await response.json()
} catch (error) {
console.error(`Error fetching snippet ${id}:`, error)
return {
id: id,
title: '默认代码片段',
code: 'console.log("Hello World");',
type: 'js'
}
}
}
export const createSnippet = async (snippetData: Omit<Snippet, 'id' | 'viewCount'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/snippets`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(snippetData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '创建代码片段失败')
}
} catch (error) {
console.error('Create snippet error:', error)
throw error
}
}
export const updateSnippet = async (id: string, snippetData: Omit<Snippet, 'id' | 'viewCount'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/snippets/${id}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(snippetData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '更新代码片段失败')
}
} catch (error) {
console.error('Update snippet error:', error)
throw error
}
}
export const deleteSnippet = async (id: string): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/snippets/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '删除代码片段失败')
}
} catch (error) {
console.error('Delete snippet error:', error)
throw error
}
}
// 系统配置API
export const getSettings = async (): Promise<Setting[]> => {
try {
const response = await fetch(`${API_BASE}/admin/settings`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取系统配置失败')
}
return await response.json()
} catch (error) {
console.error('Get settings error:', error)
throw error
}
}
export const createSetting = async (settingData: Omit<Setting, 'id' | 'createdAt' | 'updatedAt'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/settings`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(settingData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '创建系统配置失败')
}
} catch (error) {
console.error('Create setting error:', error)
throw error
}
}
export const updateSetting = async (settingData: Omit<Setting, 'createdAt' | 'updatedAt'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/settings`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(settingData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '更新系统配置失败')
}
} catch (error) {
console.error('Update setting error:', error)
throw error
}
}
export const deleteSetting = async (keyName: string): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/settings/${keyName}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '删除系统配置失败')
}
} catch (error) {
console.error('Delete setting error:', error)
throw error
}
}
// 操作日志API
export const getOperationLogs = async (page: number = 1, pageSize: number = 10): Promise<PaginationResponse<OperationLog>> => {
try {
const response = await fetch(`${API_BASE}/admin/operation-logs?page=${page}&pageSize=${pageSize}`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取操作日志失败')
}
return await response.json()
} catch (error) {
console.error('Get operation logs error:', error)
throw error
}
}
// 仪表盘数据类型
export interface DashboardStats {
users: number
posts: number
works: number
snippets: number
}
// 最近活动类型
export interface RecentActivity {
id: number
icon: string
text: string
time: string
}
// 仪表盘API
export const getDashboardStats = async (): Promise<DashboardStats> => {
try {
const response = await fetch(`${API_BASE}/admin/dashboard/stats`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取仪表盘统计数据失败')
}
return await response.json()
} catch (error) {
console.error('Get dashboard stats error:', error)
throw error
}
}
// 获取最近活动
export const getRecentActivities = async (): Promise<RecentActivity[]> => {
try {
const response = await fetch(`${API_BASE}/admin/dashboard/activities`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取最近活动失败')
}
return await response.json()
} catch (error) {
console.error('Get recent activities error:', error)
throw error
}
}
// 标签相关类型
export interface Tag {
id: number
name: string
description: string
createdAt: string
updatedAt: string
}
// 标签管理API
export const adminGetTags = async (): Promise<Tag[]> => {
try {
const response = await fetch(`${API_BASE}/admin/tags`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取标签列表失败')
}
return await response.json()
} catch (error) {
console.error('Get admin tags error:', error)
throw error
}
}
export const adminGetTag = async (id: number): Promise<Tag> => {
try {
const response = await fetch(`${API_BASE}/admin/tags/${id}`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取标签详情失败')
}
return await response.json()
} catch (error) {
console.error('Get admin tag error:', error)
throw error
}
}
export const createTag = async (tagData: Omit<Tag, 'id' | 'createdAt' | 'updatedAt'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/tags`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify(tagData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '创建标签失败')
}
} catch (error) {
console.error('Create tag error:', error)
throw error
}
}
export const updateTag = async (id: number, tagData: Omit<Tag, 'id' | 'createdAt' | 'updatedAt'>): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/tags/${id}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify(tagData)
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '更新标签失败')
}
} catch (error) {
console.error('Update tag error:', error)
throw error
}
}
export const deleteTag = async (id: number): Promise<void> => {
try {
const response = await fetch(`${API_BASE}/admin/tags/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '删除标签失败')
}
} catch (error) {
console.error('Delete tag error:', error)
throw error
}
}