Browse Source

修复蛋吧页面获取所有动态数据

pull/18/head
徐飞洋 1 month ago
parent
commit
b90ade750e
  1. 40
      server-example/server-mysql.js

40
server-example/server-mysql.js

@ -194,17 +194,26 @@ app.get('/api/eggbar/posts', async (req, res) => {
offset offset
}); });
// 使用新的 Sequelize 实例查询 eggbar 数据库
const tempSequelize = new Sequelize('eggbar', dbConfig.user, dbConfig.password, {
host: dbConfig.host,
port: dbConfig.port,
dialect: 'mysql',
logging: console.log,
timezone: '+08:00'
});
// 从数据库获取帖子列表 // 从数据库获取帖子列表
const [posts, metadata] = await eggbarSequelize.query( const posts = await tempSequelize.query(
`SELECT * FROM eggbar_posts 'SELECT * FROM eggbar_posts ORDER BY created_at DESC',
ORDER BY created_at DESC
LIMIT ? OFFSET ?`,
{ {
replacements: [pageSize, offset], type: tempSequelize.QueryTypes.SELECT
type: eggbarSequelize.QueryTypes.SELECT
} }
); );
// 关闭临时连接
await tempSequelize.close();
console.log('原始查询结果:', posts); console.log('原始查询结果:', posts);
console.log('查询结果类型:', typeof posts); console.log('查询结果类型:', typeof posts);
console.log('是否为数组:', Array.isArray(posts)); console.log('是否为数组:', Array.isArray(posts));
@ -212,18 +221,19 @@ app.get('/api/eggbar/posts', async (req, res) => {
// 确保查询结果为数组 // 确保查询结果为数组
const postsArray = Array.isArray(posts) ? posts : (posts ? [posts] : []); const postsArray = Array.isArray(posts) ? posts : (posts ? [posts] : []);
// 获取总帖子数 // 手动处理分页
const [[totalCount]] = await eggbarSequelize.query( const totalCount = postsArray.length;
'SELECT COUNT(*) as count FROM eggbar_posts' const startIndex = (page - 1) * pageSize;
); const endIndex = startIndex + pageSize;
const paginatedPosts = postsArray.slice(startIndex, endIndex);
console.log('查询结果:', { console.log('查询结果:', {
postCount: postsArray.length, postCount: paginatedPosts.length,
totalCount: totalCount.count totalCount: totalCount
}); });
// 格式化响应数据 // 格式化响应数据
const formattedPosts = postsArray.map(post => ({ const formattedPosts = paginatedPosts.map(post => ({
id: post.id, id: post.id,
user_id: post.user_id, user_id: post.user_id,
phone: post.phone, phone: post.phone,
@ -247,8 +257,8 @@ app.get('/api/eggbar/posts', async (req, res) => {
pagination: { pagination: {
page, page,
pageSize, pageSize,
total: totalCount.count, total: totalCount,
totalPages: Math.ceil(totalCount.count / pageSize) totalPages: Math.ceil(totalCount / pageSize)
} }
} }
}); });

Loading…
Cancel
Save