修正資料即時呈現

This commit is contained in:
2025-10-07 11:46:05 +08:00
parent 01bc5e57f6
commit 4482f6c3c7
13 changed files with 573 additions and 283 deletions

View File

@@ -1,6 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import { execSync } from 'child_process'
const prisma = new PrismaClient()
@@ -48,16 +47,6 @@ export async function POST(request: NextRequest) {
updated_at: wish.updatedAt.toISOString()
}
// 創建成功後,更新數據文件
try {
console.log('🔄 更新數據文件...')
execSync('node scripts/get-real-data.js', { stdio: 'pipe' })
console.log('✅ 數據文件更新完成')
} catch (updateError) {
console.warn('⚠️ 數據文件更新失敗:', updateError)
// 不影響創建結果,只是警告
}
return NextResponse.json({ success: true, data: formattedWish })
} catch (error) {
console.error('API Error:', error)

View File

@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const wishId = searchParams.get('wishId')
if (!wishId) {
return NextResponse.json(
{ success: false, error: 'Wish ID is required' },
{ status: 400 }
)
}
// 獲取指定困擾案例的點讚數
const likeCount = await prisma.wishLike.count({
where: {
wishId: Number(wishId)
}
})
return NextResponse.json({
success: true,
data: {
wishId: Number(wishId),
likeCount: likeCount
}
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to get like count' },
{ status: 500 }
)
}
}

View File

@@ -1,43 +1,97 @@
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 讀取真實數據: type=${type}`)
console.log(`🔍 從資料庫即時獲取數據: type=${type}`)
// 讀取對應的 JSON 文件
let dataFile
// 使用原始 SQL 查詢避免 Prisma 的排序問題
let wishes
if (type === 'public') {
dataFile = path.join(process.cwd(), 'data', 'public-wishes.json')
wishes = await prisma.$queryRaw`
SELECT id, title, current_pain, expected_solution, expected_effect,
is_public, email, images, user_session, status, category, priority,
created_at, updated_at
FROM wishes
WHERE is_public = true AND status = 'active'
LIMIT 100
`
} else {
dataFile = path.join(process.cwd(), 'data', 'all-wishes.json')
wishes = await prisma.$queryRaw`
SELECT id, title, current_pain, expected_solution, expected_effect,
is_public, email, images, user_session, status, category, priority,
created_at, updated_at
FROM wishes
WHERE status = 'active'
LIMIT 100
`
}
// 檢查文件是否存在
if (!fs.existsSync(dataFile)) {
console.log('❌ 數據文件不存在,正在生成...')
return NextResponse.json(
{ success: false, error: 'Data file not found, please run get-real-data.js first' },
{ status: 404 }
)
console.log(`✅ 成功獲取 ${(wishes as any[]).length} 筆困擾案例 (type: ${type})`)
// 獲取所有困擾案例的點讚數
const wishIds = (wishes as any[]).map(w => w.id)
const likeCountMap = {}
if (wishIds.length > 0) {
// 使用 Prisma 的 findMany 而不是原始 SQL 查詢
const likes = await prisma.wishLike.findMany({
where: {
wishId: { in: wishIds }
},
select: {
wishId: true
}
})
// 手動計算點讚數
likes.forEach(like => {
likeCountMap[Number(like.wishId)] = (likeCountMap[Number(like.wishId)] || 0) + 1
})
}
// 讀取文件
const fileContent = fs.readFileSync(dataFile, 'utf8')
const data = JSON.parse(fileContent)
// 轉換數據格式,處理 BigInt 序列化問題
const formattedWishes = (wishes as any[]).map((wish) => ({
id: Number(wish.id), // 轉換 BigInt 為 Number
title: wish.title,
current_pain: wish.current_pain,
expected_solution: wish.expected_solution,
expected_effect: wish.expected_effect,
is_public: Boolean(wish.is_public),
email: wish.email,
images: wish.images,
user_session: wish.user_session,
status: wish.status,
category: wish.category,
priority: Number(wish.priority), // 轉換 BigInt 為 Number
like_count: likeCountMap[Number(wish.id)] || 0,
created_at: wish.created_at ? new Date(wish.created_at).toISOString() : new Date().toISOString(),
updated_at: wish.updated_at ? new Date(wish.updated_at).toISOString() : new Date().toISOString()
}))
console.log(`✅ 成功讀取 ${data.data.length} 筆真實數據`)
// 按照 created_at 日期降序排序
formattedWishes.sort((a, b) => {
const dateA = new Date(a.created_at)
const dateB = new Date(b.created_at)
return dateB.getTime() - dateA.getTime()
})
return NextResponse.json(data)
console.log(`✅ 成功從資料庫獲取 ${formattedWishes.length} 筆即時數據`)
return NextResponse.json({
success: true,
data: formattedWishes
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to read real data' },
{ success: false, error: 'Failed to fetch real-time data from database' },
{ status: 500 }
)
}

View File

@@ -0,0 +1,70 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 簡化即時數據獲取: type=${type}`)
// 從資料庫獲取困擾案例(暫時移除排序避免記憶體問題)
let wishes
if (type === 'public') {
wishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
take: 100
})
} else {
wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
take: 100
})
}
console.log(`✅ 成功獲取 ${wishes.length} 筆困擾案例 (type: ${type})`)
// 轉換數據格式,暫時不包含點讚數
const formattedWishes = wishes.map((wish: any) => ({
id: Number(wish.id),
title: wish.title,
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic,
email: wish.email,
images: wish.images,
user_session: wish.userSession,
status: wish.status,
category: wish.category,
priority: Number(wish.priority),
like_count: 0, // 暫時設為 0
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString()
}))
// 按照 ID 降序排序(已在資料庫查詢中完成)
// 不需要額外排序,因為資料庫查詢已經使用 orderBy: { id: 'desc' }
console.log(`✅ 成功從資料庫獲取 ${formattedWishes.length} 筆即時數據`)
return NextResponse.json({
success: true,
data: formattedWishes
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: error.message },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,70 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 使用 SQL 即時數據獲取: type=${type}`)
// 使用原始 SQL 查詢避免 Prisma 的排序問題
let wishes
if (type === 'public') {
wishes = await prisma.$queryRaw`
SELECT id, title, current_pain, expected_solution, expected_effect,
is_public, email, images, user_session, status, category, priority,
created_at, updated_at
FROM wishes
WHERE is_public = true AND status = 'active'
LIMIT 100
`
} else {
wishes = await prisma.$queryRaw`
SELECT id, title, current_pain, expected_solution, expected_effect,
is_public, email, images, user_session, status, category, priority,
created_at, updated_at
FROM wishes
WHERE status = 'active'
LIMIT 100
`
}
console.log(`✅ 成功獲取 ${(wishes as any[]).length} 筆困擾案例 (type: ${type})`)
// 轉換數據格式
const formattedWishes = (wishes as any[]).map((wish) => ({
id: Number(wish.id),
title: wish.title,
current_pain: wish.current_pain,
expected_solution: wish.expected_solution,
expected_effect: wish.expected_effect,
is_public: Boolean(wish.is_public),
email: wish.email,
images: wish.images,
user_session: wish.user_session,
status: wish.status,
category: wish.category,
priority: Number(wish.priority),
like_count: 0, // 暫時設為 0
created_at: wish.created_at ? new Date(wish.created_at).toISOString() : new Date().toISOString(),
updated_at: wish.updated_at ? new Date(wish.updated_at).toISOString() : new Date().toISOString()
}))
console.log(`✅ 成功從資料庫獲取 ${formattedWishes.length} 筆即時數據`)
return NextResponse.json({
success: true,
data: formattedWishes
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: error.message },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,60 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
console.log('🔍 測試公開困擾案例查詢...')
// 分步測試
console.log('1. 測試基本查詢...')
const allWishes = await prisma.wish.findMany({
where: {
status: 'active'
},
take: 3,
select: {
id: true,
title: true,
isPublic: true
}
})
console.log(`✅ 基本查詢成功: ${allWishes.length}`)
console.log('2. 測試公開查詢...')
const publicWishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
take: 3,
select: {
id: true,
title: true,
isPublic: true
}
})
console.log(`✅ 公開查詢成功: ${publicWishes.length}`)
// 轉換數據格式
const formattedWishes = publicWishes.map((wish: any) => ({
id: Number(wish.id),
title: wish.title,
isPublic: wish.isPublic
}))
return NextResponse.json({
success: true,
data: formattedWishes,
message: `成功獲取 ${publicWishes.length} 筆公開困擾案例`
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: error.message },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
console.log('🔍 測試即時數據獲取...')
// 簡單測試獲取前5個困擾案例
const wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 5,
select: {
id: true,
title: true,
isPublic: true,
createdAt: true
}
})
console.log(`✅ 成功獲取 ${wishes.length} 筆困擾案例`)
// 轉換 BigInt 為 Number
const formattedWishes = wishes.map((wish: any) => ({
...wish,
id: Number(wish.id),
createdAt: wish.createdAt.toISOString()
}))
return NextResponse.json({
success: true,
data: formattedWishes,
message: `成功獲取 ${wishes.length} 筆困擾案例`
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: error.message },
{ status: 500 }
)
}
}