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,26 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
const USERS_FILE = path.join(process.cwd(), 'data/users.json');
interface User {
id: string;
username: string;
passwordHash: string;
token: string;
createdAt: string;
}
async function readUsers(): Promise<User[]> {
try {
const data = await fs.readFile(USERS_FILE, 'utf-8');
return JSON.parse(data);
} catch {
return [];
}
}
import pool from '@/lib/db';
function hashPassword(password: string): string {
return crypto.createHash('sha256').update(password).digest('hex');
@@ -31,6 +11,7 @@ function generateToken(): string {
}
export async function POST(request: NextRequest) {
let connection;
try {
const { username, password } = await request.json();
@@ -38,18 +19,18 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: '用户名和密码不能为空' }, { status: 400 });
}
const users = await readUsers();
const user = users.find(u => u.username === username);
connection = await pool.getConnection();
if (!user || user.passwordHash !== hashPassword(password)) {
const [rows] = await connection.query<any[]>('SELECT * FROM users WHERE username = ?', [username]);
if (rows.length === 0 || rows[0].password_hash !== hashPassword(password)) {
return NextResponse.json({ error: '用户名或密码错误' }, { status: 401 });
}
const newToken = generateToken();
user.token = newToken;
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
await connection.query('UPDATE users SET token = ? WHERE id = ?', [newToken, rows[0].id]);
const response = NextResponse.json({ success: true, username: user.username });
const response = NextResponse.json({ success: true, username });
response.cookies.set('auth_token', newToken, {
httpOnly: true,
secure: false,
@@ -62,5 +43,7 @@ export async function POST(request: NextRequest) {
} catch (error) {
console.error('Login error:', error);
return NextResponse.json({ error: '登录失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
}

View File

@@ -1,25 +1,8 @@
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
const USERS_FILE = path.join(process.cwd(), 'data/users.json');
interface User {
id: string;
username: string;
token: string;
}
async function readUsers(): Promise<User[]> {
try {
const data = await fs.readFile(USERS_FILE, 'utf-8');
return JSON.parse(data);
} catch {
return [];
}
}
import pool from '@/lib/db';
export async function GET(request: NextRequest) {
let connection;
try {
const token = request.cookies.get('auth_token')?.value;
@@ -27,17 +10,20 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ user: null });
}
const users = await readUsers();
const user = users.find(u => u.token === token);
connection = await pool.getConnection();
if (!user) {
const [rows] = await connection.query<any[]>('SELECT username FROM users WHERE token = ?', [token]);
if (rows.length === 0) {
return NextResponse.json({ user: null });
}
return NextResponse.json({ user: { username: user.username } });
return NextResponse.json({ user: { username: rows[0].username } });
} catch (error) {
console.error('Get user error:', error);
return NextResponse.json({ user: null });
} finally {
if (connection) connection.release();
}
}
@@ -45,4 +31,4 @@ export async function DELETE(request: NextRequest) {
const response = NextResponse.json({ success: true });
response.cookies.delete('auth_token');
return response;
}
}

View File

@@ -1,31 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
const DATA_DIR = path.join(process.cwd(), 'data');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
interface User {
id: string;
username: string;
passwordHash: string;
token: string;
createdAt: string;
}
async function readUsers(): Promise<User[]> {
try {
const data = await fs.readFile(USERS_FILE, 'utf-8');
return JSON.parse(data);
} catch {
return [];
}
}
async function writeUsers(users: User[]): Promise<void> {
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
}
import pool from '@/lib/db';
function hashPassword(password: string): string {
return crypto.createHash('sha256').update(password).digest('hex');
@@ -36,6 +11,7 @@ function generateToken(): string {
}
export async function POST(request: NextRequest) {
let connection;
try {
const { username, password } = await request.json();
@@ -47,23 +23,19 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: '用户名至少3位密码至少6位' }, { status: 400 });
}
const users = await readUsers();
connection = await pool.getConnection();
if (users.find(u => u.username === username)) {
const [rows] = await connection.query<any[]>('SELECT id FROM users WHERE username = ?', [username]);
if (rows.length > 0) {
return NextResponse.json({ error: '用户名已存在' }, { status: 400 });
}
const token = generateToken();
const newUser: User = {
id: crypto.randomUUID(),
username,
passwordHash: hashPassword(password),
token,
createdAt: new Date().toISOString()
};
users.push(newUser);
await writeUsers(users);
await connection.query(
'INSERT INTO users (id, username, password_hash, token, created_at) VALUES (?, ?, ?, ?, ?)',
[crypto.randomUUID(), username, hashPassword(password), token, new Date()]
);
const response = NextResponse.json({ success: true, username });
response.cookies.set('auth_token', token, {
@@ -78,5 +50,7 @@ export async function POST(request: NextRequest) {
} catch (error) {
console.error('Register error:', error);
return NextResponse.json({ error: '注册失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
}

View File

@@ -1,17 +1,21 @@
import { NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
const DATA_DIR = path.join(process.cwd(), 'data');
const DISTRICTS_FILE = path.join(DATA_DIR, 'districts.json');
import pool from '@/lib/db';
export async function GET() {
let connection;
try {
const data = await fs.readFile(DISTRICTS_FILE, 'utf-8');
const districts = JSON.parse(data);
connection = await pool.getConnection();
const [rows] = await connection.query<any[]>('SELECT name FROM districts ORDER BY sort_order, id');
const districts = rows.map((row: any) => row.name);
connection.release();
return NextResponse.json({ districts });
} catch (error) {
console.error('Get districts error:', error);
return NextResponse.json({ districts: [] });
} finally {
if (connection) connection.release();
}
}

View File

@@ -1,69 +1,41 @@
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, []);
}
async function writeHouses(houses: House[]): Promise<void> {
await fs.writeFile(HOUSES_FILE, JSON.stringify(houses, null, 2));
}
import pool from '@/lib/db';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
let connection;
try {
const { id } = await params;
const houses = await readHouses();
const house = houses.find(h => h.id === id);
connection = await pool.getConnection();
if (!house) {
const [rows] = await connection.query<any[]>('SELECT * FROM houses WHERE id = ?', [id]);
if (rows.length === 0) {
return NextResponse.json({ error: '房屋不存在' }, { status: 404 });
}
const row = rows[0];
const house = {
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
};
return NextResponse.json({ house });
} catch (error) {
console.error('Get house error:', error);
return NextResponse.json({ error: '获取房屋信息失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
@@ -71,6 +43,7 @@ export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
let connection;
try {
const token = request.cookies.get('auth_token')?.value;
@@ -78,43 +51,65 @@ export async function PUT(
return NextResponse.json({ error: '请先登录' }, { status: 401 });
}
const user = await getUserFromToken(token);
if (!user) {
const { id } = await params;
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 { id } = await params;
const houses = await readHouses();
const houseIndex = houses.findIndex(h => h.id === id);
if (houseIndex === -1) {
const [houses] = await connection.query<any[]>('SELECT * FROM houses WHERE id = ?', [id]);
if (houses.length === 0) {
connection.release();
return NextResponse.json({ error: '房屋不存在' }, { status: 404 });
}
if (houses[houseIndex].owner !== user.username) {
if (houses[0].owner !== users[0].username) {
connection.release();
return NextResponse.json({ error: '无权修改此房屋' }, { status: 403 });
}
const body = await request.json();
const { title, description, price, district, address, phone, images } = body;
houses[houseIndex] = {
...houses[houseIndex],
title: title || houses[houseIndex].title,
description: description ?? houses[houseIndex].description,
price: price !== undefined ? Number(price) : houses[houseIndex].price,
district: district || houses[houseIndex].district,
address: address || houses[houseIndex].address,
phone: phone || houses[houseIndex].phone,
images: images || houses[houseIndex].images
await connection.query(
'UPDATE houses SET title = ?, description = ?, price = ?, district = ?, address = ?, phone = ?, images = ? WHERE id = ?',
[
title || houses[0].title,
description ?? houses[0].description,
price !== undefined ? Number(price) : houses[0].price,
district || houses[0].district,
address || houses[0].address,
phone || houses[0].phone,
images ? JSON.stringify(images) : houses[0].images,
id
]
);
const [updated] = await connection.query<any[]>('SELECT * FROM houses WHERE id = ?', [id]);
const row = updated[0];
const house = {
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
};
await writeHouses(houses);
return NextResponse.json({ success: true, house: houses[houseIndex] });
connection.release();
return NextResponse.json({ success: true, house });
} catch (error) {
console.error('Update house error:', error);
return NextResponse.json({ error: '更新房屋失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
@@ -122,6 +117,7 @@ export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
let connection;
try {
const token = request.cookies.get('auth_token')?.value;
@@ -129,29 +125,34 @@ export async function DELETE(
return NextResponse.json({ error: '请先登录' }, { status: 401 });
}
const user = await getUserFromToken(token);
if (!user) {
const { id } = await params;
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 { id } = await params;
const houses = await readHouses();
const house = houses.find(h => h.id === id);
if (!house) {
const [houses] = await connection.query<any[]>('SELECT * FROM houses WHERE id = ?', [id]);
if (houses.length === 0) {
connection.release();
return NextResponse.json({ error: '房屋不存在' }, { status: 404 });
}
if (house.owner !== user.username) {
if (houses[0].owner !== users[0].username) {
connection.release();
return NextResponse.json({ error: '无权删除此房屋' }, { status: 403 });
}
const newHouses = houses.filter(h => h.id !== id);
await writeHouses(newHouses);
await connection.query('DELETE FROM houses WHERE id = ?', [id]);
connection.release();
return NextResponse.json({ success: true });
} catch (error) {
console.error('Delete house error:', error);
return NextResponse.json({ error: '删除房屋失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
}

View File

@@ -1,84 +1,58 @@
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
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, []);
}
async function writeHouses(houses: House[]): Promise<void> {
await fs.writeFile(HOUSES_FILE, JSON.stringify(houses, null, 2));
}
import pool from '@/lib/db';
export async function GET(request: NextRequest) {
let connection;
try {
const { searchParams } = new URL(request.url);
const district = searchParams.get('district');
const keyword = searchParams.get('keyword');
let houses = await readHouses();
connection = await pool.getConnection();
let sql = 'SELECT * FROM houses WHERE 1=1';
const params: any[] = [];
if (district && district !== '全部') {
houses = houses.filter(h => h.district === district);
sql += ' AND district = ?';
params.push(district);
}
if (keyword) {
const kw = keyword.toLowerCase();
houses = houses.filter(h =>
h.title.toLowerCase().includes(kw) ||
h.address.toLowerCase().includes(kw) ||
h.description.toLowerCase().includes(kw)
);
sql += ' AND (title LIKE ? OR address LIKE ? OR description LIKE ?)';
const kw = `%${keyword}%`;
params.push(kw, kw, kw);
}
houses.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
sql += ' ORDER BY created_at DESC';
const [rows] = await connection.query<any[]>(sql, params);
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
}));
return NextResponse.json({ houses });
} catch (error) {
console.error('Get houses error:', error);
return NextResponse.json({ error: '获取房屋列表失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
export async function POST(request: NextRequest) {
let connection;
try {
const token = request.cookies.get('auth_token')?.value;
@@ -86,8 +60,11 @@ export async function POST(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) {
return NextResponse.json({ error: '用户不存在' }, { status: 401 });
}
@@ -98,9 +75,15 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: '请填写完整信息' }, { status: 400 });
}
const house: House = {
id: crypto.randomUUID(),
owner: user.username,
const id = crypto.randomUUID();
await connection.query(
'INSERT INTO houses (id, owner, title, description, price, district, address, phone, images, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[id, users[0].username, title, description || '', Number(price), district, address, phone, JSON.stringify(images || []), new Date()]
);
const house = {
id,
owner: users[0].username,
title,
description: description || '',
price: Number(price),
@@ -108,16 +91,14 @@ export async function POST(request: NextRequest) {
address,
phone,
images: images || [],
createdAt: new Date().toISOString()
createdAt: new Date()
};
const houses = await readHouses();
houses.push(house);
await writeHouses(houses);
return NextResponse.json({ success: true, house });
} catch (error) {
console.error('Create house error:', error);
return NextResponse.json({ error: '创建房屋失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
}

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();
}
}
}