feat: 切换为MariaDB数据库存储

This commit is contained in:
Cuishibing
2026-03-22 22:10:41 +08:00
parent a105f4aecb
commit fbd5f94a43
10 changed files with 346 additions and 299 deletions

View File

@@ -1,49 +1,8 @@
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
const DATA_DIR = path.join(process.cwd(), 'data');
const HOUSES_FILE = path.join(DATA_DIR, 'houses.json');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
interface House {
id: string;
owner: string;
title: string;
description: string;
price: number;
district: string;
address: string;
phone: string;
images: string[];
createdAt: string;
}
interface User {
id: string;
username: string;
token: string;
}
async function readFile<T>(filePath: string, defaultValue: T): Promise<T> {
try {
const data = await fs.readFile(filePath, 'utf-8');
return JSON.parse(data);
} catch {
return defaultValue;
}
}
async function getUserFromToken(token: string): Promise<User | null> {
const users = await readFile<User[]>(USERS_FILE, []);
return users.find(u => u.token === token) || null;
}
async function readHouses(): Promise<House[]> {
return readFile<House[]>(HOUSES_FILE, []);
}
import pool from '@/lib/db';
export async function GET(request: NextRequest) {
let connection;
try {
const token = request.cookies.get('auth_token')?.value;
@@ -51,19 +10,39 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: '请先登录' }, { status: 401 });
}
const user = await getUserFromToken(token);
if (!user) {
connection = await pool.getConnection();
const [users] = await connection.query<any[]>('SELECT username FROM users WHERE token = ?', [token]);
if (users.length === 0) {
connection.release();
return NextResponse.json({ error: '用户不存在' }, { status: 401 });
}
const houses = await readHouses();
const myHouses = houses
.filter(h => h.owner === user.username)
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
const [rows] = await connection.query<any[]>(
'SELECT * FROM houses WHERE owner = ? ORDER BY created_at DESC',
[users[0].username]
);
return NextResponse.json({ houses: myHouses });
const houses = rows.map((row: any) => ({
id: row.id,
owner: row.owner,
title: row.title,
description: row.description,
price: row.price,
district: row.district,
address: row.address,
phone: row.phone,
images: row.images ? JSON.parse(row.images) : [],
createdAt: row.created_at
}));
connection.release();
return NextResponse.json({ houses });
} catch (error) {
console.error('Get my houses error:', error);
return NextResponse.json({ error: '获取房屋列表失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
}