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
});
// 使用新的 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(
`SELECT * FROM eggbar_posts
ORDER BY created_at DESC
LIMIT ? OFFSET ?`,
const posts = await tempSequelize.query(
'SELECT * FROM eggbar_posts ORDER BY created_at DESC',
{
replacements: [pageSize, offset],
type: eggbarSequelize.QueryTypes.SELECT
type: tempSequelize.QueryTypes.SELECT
}
);
// 关闭临时连接
await tempSequelize.close();
console.log('原始查询结果:', posts);
console.log('查询结果类型:', typeof 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 [[totalCount]] = await eggbarSequelize.query(
'SELECT COUNT(*) as count FROM eggbar_posts'
);
// 手动处理分页
const totalCount = postsArray.length;
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const paginatedPosts = postsArray.slice(startIndex, endIndex);
console.log('查询结果:', {
postCount: postsArray.length,
totalCount: totalCount.count
postCount: paginatedPosts.length,
totalCount: totalCount
});
// 格式化响应数据
const formattedPosts = postsArray.map(post => ({
const formattedPosts = paginatedPosts.map(post => ({
id: post.id,
user_id: post.user_id,
phone: post.phone,
@ -247,8 +257,8 @@ app.get('/api/eggbar/posts', async (req, res) => {
pagination: {
page,
pageSize,
total: totalCount.count,
totalPages: Math.ceil(totalCount.count / pageSize)
total: totalCount,
totalPages: Math.ceil(totalCount / pageSize)
}
}
});

Loading…
Cancel
Save