XNSim/XNSimHtml/utils/qa-utils.js

146 lines
3.3 KiB
JavaScript
Raw Permalink Normal View History

const { getDBConnection } = require('./file-utils');
// 获取所有问题
function getQuestions() {
try {
const db = getDBConnection(true);
const questions = db.prepare(`
SELECT q.*,
COUNT(a.id) as answer_count,
MAX(a.created_at) as last_answer_time
FROM questions q
LEFT JOIN answers a ON q.id = a.question_id
GROUP BY q.id
ORDER BY q.created_at DESC
`).all();
// 获取每个问题的回答
questions.forEach(question => {
question.answers = db.prepare(`
SELECT * FROM answers
WHERE question_id = ?
ORDER BY created_at ASC
`).all(question.id);
});
return questions;
} catch (error) {
console.error('获取问题列表失败:', error);
throw error;
}
}
// 创建新问题
function createQuestion(title, content, author) {
try {
if (!title || !content) {
throw new Error('标题和内容不能为空');
}
const db = getDBConnection();
const result = db.prepare(`
INSERT INTO questions (title, content, author)
VALUES (?, ?, ?)
`).run(title, content, author || '匿名用户');
if (result.changes > 0) {
return {
success: true,
questionId: result.lastInsertRowid,
message: '问题创建成功'
};
} else {
throw new Error('问题创建失败');
}
} catch (error) {
console.error('创建问题失败:', error);
throw error;
}
}
// 添加回答
function addAnswer(questionId, content, author) {
try {
if (!content) {
throw new Error('回答内容不能为空');
}
const db = getDBConnection();
// 检查问题是否存在
const question = db.prepare('SELECT id FROM questions WHERE id = ?').get(questionId);
if (!question) {
throw new Error('问题不存在');
}
const result = db.prepare(`
INSERT INTO answers (question_id, content, author)
VALUES (?, ?, ?)
`).run(questionId, content, author || '匿名用户');
if (result.changes > 0) {
return {
success: true,
answerId: result.lastInsertRowid,
message: '回答添加成功'
};
} else {
throw new Error('回答添加失败');
}
} catch (error) {
console.error('添加回答失败:', error);
throw error;
}
}
// 删除问题
function deleteQuestion(questionId) {
try {
const db = getDBConnection();
const result = db.prepare('DELETE FROM questions WHERE id = ?').run(questionId);
if (result.changes > 0) {
return {
success: true,
message: '问题删除成功'
};
} else {
throw new Error('问题不存在');
}
} catch (error) {
console.error('删除问题失败:', error);
throw error;
}
}
// 删除回答
function deleteAnswer(answerId) {
try {
const db = getDBConnection();
const result = db.prepare('DELETE FROM answers WHERE id = ?').run(answerId);
if (result.changes > 0) {
return {
success: true,
message: '回答删除成功'
};
} else {
throw new Error('回答不存在');
}
} catch (error) {
console.error('删除回答失败:', error);
throw error;
}
}
module.exports = {
getQuestions,
createQuestion,
addAnswer,
deleteQuestion,
deleteAnswer
};