Add v2 comments support and align APIs

This commit is contained in:
LeonspaceX
2026-01-26 17:34:35 +08:00
parent ffa6c927bf
commit f6d9521f80
7 changed files with 396 additions and 29 deletions

View File

@@ -211,3 +211,70 @@ export const voteArticle = async (id: number, type: 'up' | 'down'): Promise<void
throw error;
}
};
export interface Comment {
id: number;
nickname: string;
content: string;
parent_comment_id: number;
}
export const getComments = async (id: string | number): Promise<Comment[]> => {
try {
const response = await fetch(`/api/get/comment?id=${id}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
if (json.code === 1000 && Array.isArray(json.data)) {
return json.data as Comment[];
}
throw new Error('Invalid response code or missing data');
} catch (error) {
console.error('Failed to fetch comments:', error);
throw error;
}
};
export interface PostCommentRequest {
content: string;
submission_id: number;
parent_comment_id: number;
nickname: string;
}
export interface PostCommentResponse {
id: number;
}
export const postComment = async (commentData: PostCommentRequest): Promise<PostCommentResponse> => {
try {
const identity = await get_id_token();
const response = await fetch('/api/comment', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
...commentData,
identity,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
if (json.code === 1001 && json.data?.id !== undefined) {
return { id: Number(json.data.id) };
}
if (json.code === 2005) {
throw new Error('评论包含违禁词');
}
throw new Error('Comment failed');
} catch (error) {
console.error('Failed to post comment:', error);
throw error;
}
};