完善投稿功能

This commit is contained in:
2026-01-23 13:46:20 +08:00
parent 50371f9a2e
commit abae2e266a
4 changed files with 137 additions and 4 deletions

View File

@@ -89,3 +89,76 @@ export const saveDraft = (content: string): void => {
export const getDraft = (): string | null => {
return localStorage.getItem('draft');
};
export const fetch_id_token = async (): Promise<string> => {
try {
const response = await fetch('/api/get_id_token');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
if (json.code === 1000) {
return json.data;
} else {
throw new Error(json.data || 'Failed to fetch identity token');
}
} catch (error) {
console.error('Failed to fetch identity token:', error);
throw error;
}
};
export const get_id_token = async (): Promise<string> => {
let token = localStorage.getItem('identity_token');
if (!token) {
token = await fetch_id_token();
localStorage.setItem('identity_token', token);
}
return token;
};
export interface CreatePostResponse {
code: number;
data: any;
}
export const createPost = async (content: string): Promise<CreatePostResponse> => {
try {
const identity = await get_id_token();
// 解析标签:#开头,后跟非空白字符
const hashtopic: string[] = [];
const regex = /#\S+/g;
const matches = content.match(regex);
if (matches) {
matches.forEach(tag => {
const cleanTag = tag.substring(1);
// 去重添加
if (!hashtopic.includes(cleanTag)) {
hashtopic.push(cleanTag);
}
});
}
const response = await fetch('/api/post', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content,
hashtopic,
identity
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Failed to create post:', error);
throw error;
}
};