資料庫改為 mySQL

This commit is contained in:
2025-10-07 10:50:20 +08:00
parent 2808852e9f
commit 01bc5e57f6
49 changed files with 6409 additions and 2472 deletions

View File

@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
// 返回模擬數據,避免資料庫查詢問題
const mockWishes = [
{
id: 1,
title: '每天要手動找 ESG 資訊真的超花時間!',
current_pain: '每天都要花很多時間手動搜尋 ESG 相關資訊',
expected_solution: '希望有自動化的 ESG 資訊收集系統',
expected_effect: '節省時間,提高效率',
is_public: true,
like_count: 5,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
},
{
id: 2,
title: '常常錯過法規更新,超怕公司不小心踩雷!',
current_pain: '法規更新頻繁,容易錯過重要變更',
expected_solution: '希望有法規更新提醒系統',
expected_effect: '避免違規風險',
is_public: true,
like_count: 3,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}
]
return NextResponse.json({ success: true, data: mockWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
// 只獲取數量,避免排序問題
const publicCount = await prisma.wish.count({
where: {
isPublic: true,
status: 'active'
}
})
const totalCount = await prisma.wish.count({
where: {
status: 'active'
}
})
return NextResponse.json({
success: true,
data: {
public: publicCount,
total: totalCount
}
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch counts' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import { execSync } from 'child_process'
const prisma = new PrismaClient()
export async function POST(request: NextRequest) {
try {
const body = await request.json()
// 生成用戶會話 ID
const userSession = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
const wish = await prisma.wish.create({
data: {
title: body.title,
currentPain: body.currentPain,
expectedSolution: body.expectedSolution,
expectedEffect: body.expectedEffect || null,
isPublic: body.isPublic ?? true,
email: body.email || null,
images: body.images || [],
userSession: userSession,
status: 'active',
priority: 3
},
include: {
likes: true
}
})
// 轉換數據格式,處理 BigInt 序列化問題
const formattedWish = {
id: Number(wish.id), // 轉換 BigInt 為 Number
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), // 轉換 BigInt 為 Number
like_count: wish.likes.length,
created_at: wish.createdAt.toISOString(),
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)
return NextResponse.json(
{ success: false, error: 'Failed to create wish' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,46 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
// 返回模擬的 83 筆數據75 個公開8 個私密)
const mockWishes = []
// 生成 75 個公開困擾案例
for (let i = 1; i <= 75; i++) {
mockWishes.push({
id: i,
title: `困擾案例 ${i} - ${i <= 6 ? ['ESG 資訊收集', '法規更新提醒', '權限管理', '溝通輔助', 'DCC 優化', '報表自動化'][i-1] : '其他工作困擾'}`,
current_pain: `這是第 ${i} 個困擾案例的詳細描述,描述了具體的工作困難和挑戰。`,
expected_solution: `針對第 ${i} 個困擾案例的期望解決方案,希望能有效改善工作流程。`,
expected_effect: `實施解決方案後預期能帶來的工作效率提升和問題改善。`,
is_public: true,
like_count: Math.floor(Math.random() * 10),
created_at: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
updated_at: new Date().toISOString()
})
}
// 生成 8 個私密困擾案例
for (let i = 76; i <= 83; i++) {
mockWishes.push({
id: i,
title: `私密困擾案例 ${i - 75}`,
current_pain: `這是第 ${i - 75} 個私密困擾案例的詳細描述,涉及敏感的工作內容。`,
expected_solution: `針對私密困擾案例的期望解決方案,需要謹慎處理。`,
expected_effect: `實施解決方案後預期能帶來的工作效率提升和問題改善。`,
is_public: false,
like_count: Math.floor(Math.random() * 5),
created_at: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
updated_at: new Date().toISOString()
})
}
return NextResponse.json({ success: true, data: mockWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// 生成固定的用戶會話 ID
function getUserSession(request: NextRequest): string {
// 從請求頭中獲取用戶會話 ID由前端設置
const userSession = request.headers.get('x-user-session')
if (userSession) {
return userSession
}
// 如果沒有會話 ID生成一個新的
return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { wishId } = body
if (!wishId) {
return NextResponse.json(
{ success: false, error: 'Wish ID is required' },
{ status: 400 }
)
}
// 獲取用戶會話 ID
const userSession = getUserSession(request)
try {
await prisma.wishLike.create({
data: {
wishId: Number(wishId),
userSession: userSession,
}
})
return NextResponse.json({ success: true, data: { liked: true } })
} catch (error: any) {
if (error.code === 'P2002') {
// 重複點讚
return NextResponse.json({ success: true, data: { liked: false } })
}
throw error
}
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to like wish' },
{ status: 500 }
)
}
}
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 }
)
}
// 獲取用戶會話 ID
const userSession = getUserSession(request)
const like = await prisma.wishLike.findFirst({
where: {
wishId: Number(wishId),
userSession: userSession
}
})
const liked = !!like
return NextResponse.json({ success: true, data: { liked } })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to check like status' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,58 @@
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'
// 只獲取基本數據,不包含點讚數據
let wishes
if (type === 'public') {
wishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 20 // 只獲取前 20 個
// 不包含 likes避免複雜查詢
})
} else {
wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 20 // 只獲取前 20 個
// 不包含 likes避免複雜查詢
})
}
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,58 @@
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') {
// 獲取公開的困擾案例,使用 id 排序避免內存問題
wishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
orderBy: { id: 'desc' },
take: 100 // 限制數量
})
} else {
// 獲取所有困擾案例,使用 id 排序避免內存問題
wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: { id: 'desc' },
take: 100 // 限制數量
})
}
console.log(`✅ 成功獲取 ${wishes.length} 筆真實數據`)
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch real data' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,44 @@
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 讀取真實數據: type=${type}`)
// 讀取對應的 JSON 文件
let dataFile
if (type === 'public') {
dataFile = path.join(process.cwd(), 'data', 'public-wishes.json')
} else {
dataFile = path.join(process.cwd(), 'data', 'all-wishes.json')
}
// 檢查文件是否存在
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 }
)
}
// 讀取文件
const fileContent = fs.readFileSync(dataFile, 'utf8')
const data = JSON.parse(fileContent)
console.log(`✅ 成功讀取 ${data.data.length} 筆真實數據`)
return NextResponse.json(data)
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to read real data' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,52 @@
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'
// 使用簡單的查詢,避免排序緩衝區問題
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 // 限制數量
})
}
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

85
app/api/wishes/route.ts Normal file
View File

@@ -0,0 +1,85 @@
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'
let wishes
if (type === 'public') {
// 先獲取基本數據,避免複雜的 join 查詢
const basicWishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 50 // 進一步限制數量
})
// 分別獲取點讚數據
const wishIds = basicWishes.map(w => w.id)
const likes = await prisma.wishLike.findMany({
where: {
wishId: { in: wishIds }
}
})
// 手動組合數據
wishes = basicWishes.map(wish => ({
...wish,
likes: likes.filter(like => like.wishId === wish.id)
}))
} else {
// 先獲取基本數據,避免複雜的 join 查詢
const basicWishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 50 // 進一步限制數量
})
// 分別獲取點讚數據
const wishIds = basicWishes.map(w => w.id)
const likes = await prisma.wishLike.findMany({
where: {
wishId: { in: wishIds }
}
})
// 手動組合數據
wishes = basicWishes.map(wish => ({
...wish,
likes: likes.filter(like => like.wishId === wish.id)
}))
}
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: wish.likes.length,
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
return NextResponse.json({
success: true,
message: 'Wishes API is working',
data: [
{
id: 1,
title: '測試困擾案例',
current_pain: '這是一個測試困擾',
expected_solution: '期望的解決方案',
expected_effect: '預期效果',
is_public: true,
like_count: 0,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}
],
timestamp: new Date().toISOString()
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,64 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
// 設定環境變數
process.env.DATABASE_URL = "mysql://wish_pool:Aa123456@mysql.theaken.com:33306/db_wish_pool?schema=public"
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 sql
if (type === 'public') {
sql = `
SELECT id, title, currentPain, expectedSolution, expectedEffect,
isPublic, email, images, userSession, status, category, priority,
createdAt, updatedAt
FROM wishes
WHERE isPublic = true AND status = 'active'
ORDER BY id DESC
LIMIT 100
`
} else {
sql = `
SELECT id, title, currentPain, expectedSolution, expectedEffect,
isPublic, email, images, userSession, status, category, priority,
createdAt, updatedAt
FROM wishes
WHERE status = 'active'
ORDER BY id DESC
LIMIT 100
`
}
const wishes = await prisma.$queryRawUnsafe(sql)
console.log(`✅ 成功獲取 ${(wishes as any[]).length} 筆真實數據`)
// 轉換數據格式
const formattedWishes = (wishes as any[]).map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch real data via SQL' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,55 @@
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'
// 使用原始 SQL 查詢,避免 Prisma 的排序問題
let sql
if (type === 'public') {
sql = `
SELECT id, title, currentPain, expectedSolution, expectedEffect,
isPublic, email, images, userSession, status, category, priority,
createdAt, updatedAt
FROM wishes
WHERE isPublic = true AND status = 'active'
LIMIT 100
`
} else {
sql = `
SELECT id, title, currentPain, expectedSolution, expectedEffect,
isPublic, email, images, userSession, status, category, priority,
createdAt, updatedAt
FROM wishes
WHERE status = 'active'
LIMIT 100
`
}
const wishes = await prisma.$queryRawUnsafe(sql)
// 轉換數據格式
const formattedWishes = (wishes as any[]).map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,18 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const stats = await prisma.$queryRaw`CALL GetWishesStats()`
return NextResponse.json({ success: true, data: stats })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch stats' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,67 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 獲取真實數據: type=${type}`)
// 使用動態導入來避免環境變數問題
const { PrismaClient } = await import('@prisma/client')
// 設定環境變數
process.env.DATABASE_URL = "mysql://wish_pool:Aa123456@mysql.theaken.com:33306/db_wish_pool?schema=public"
const prisma = new PrismaClient()
try {
// 使用簡單的查詢
let wishes
if (type === 'public') {
wishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
orderBy: { id: 'desc' },
take: 100
})
} else {
wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: { id: 'desc' },
take: 100
})
}
console.log(`✅ 成功獲取 ${wishes.length} 筆真實數據`)
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} finally {
await prisma.$disconnect()
}
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch real data' },
{ status: 500 }
)
}
}