feat: 后端SQLite→MySQL改造,数据库110.42.189.169:9109
- 使用 mysql2 pool 连接外部 MySQL - 初始化表结构 + 默认管理员 + 示例数据 - 清理 unused routes, 移走 db 文件
This commit is contained in:
Binary file not shown.
Binary file not shown.
Generated
+138
-1
@@ -15,12 +15,23 @@
|
||||
"express": "^4.21.2",
|
||||
"express-rate-limit": "^7.5.0",
|
||||
"helmet": "^8.1.0",
|
||||
"jsonwebtoken": "^9.0.2"
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mysql2": "^3.22.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.1.9"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "26.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz",
|
||||
"integrity": "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~8.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/accepts": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
|
||||
@@ -54,6 +65,15 @@
|
||||
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/aws-ssl-profiles": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
|
||||
"integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
|
||||
@@ -369,6 +389,15 @@
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/denque": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
|
||||
"integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
@@ -656,6 +685,15 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/generate-function": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
|
||||
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-property": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
@@ -896,6 +934,12 @@
|
||||
"node": ">=0.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-property": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
|
||||
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jsonwebtoken": {
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
|
||||
@@ -987,6 +1031,27 @@
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/long": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
|
||||
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/lru.min": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz",
|
||||
"integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"bun": ">=1.0.0",
|
||||
"deno": ">=1.30.0",
|
||||
"node": ">=8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wellwelwel"
|
||||
}
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
@@ -1105,6 +1170,56 @@
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/mysql2": {
|
||||
"version": "3.22.6",
|
||||
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.22.6.tgz",
|
||||
"integrity": "sha512-fPKmeDGUzvFP7bMD5SASlJ5zIgvCC4hbanTmhbUlEmhyrY1hR4Hi3xLOWgTd3luYjLVifx6uGvMNJ2m/LlqEpg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"aws-ssl-profiles": "^1.1.2",
|
||||
"denque": "^2.1.0",
|
||||
"generate-function": "^2.3.1",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"long": "^5.3.2",
|
||||
"lru.min": "^1.1.4",
|
||||
"named-placeholders": "^1.1.6",
|
||||
"sql-escaper": "^1.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/mysql2/node_modules/iconv-lite": {
|
||||
"version": "0.7.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
|
||||
"integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/named-placeholders": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz",
|
||||
"integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lru.min": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/napi-build-utils": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
|
||||
@@ -1624,6 +1739,21 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/sql-escaper": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.5.1.tgz",
|
||||
"integrity": "sha512-4toX5E1fQbBrpfXidaHnF0669nkAdETeIPTs2SUjxxD7RRIs9ICG4gtpmfc68JCEKehsdwLFqBu9VlQqZ1P1gg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"bun": ">=1.0.0",
|
||||
"deno": ">=2.0.0",
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
@@ -1756,6 +1886,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "8.3.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
|
||||
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
|
||||
@@ -9,14 +9,15 @@
|
||||
"dev": "nodemon src/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.21.2",
|
||||
"cors": "^2.8.5",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"better-sqlite3": "^11.8.1",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.7",
|
||||
"express": "^4.21.2",
|
||||
"express-rate-limit": "^7.5.0",
|
||||
"helmet": "^8.1.0",
|
||||
"express-rate-limit": "^7.5.0"
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mysql2": "^3.22.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.1.9"
|
||||
|
||||
+49
-97
@@ -1,104 +1,56 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import mysql from 'mysql2/promise';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const dbPath = path.join(__dirname, '..', 'data', 'yx-nav.db');
|
||||
export const pool = mysql.createPool({
|
||||
host: process.env.DB_HOST || '110.42.189.169',
|
||||
port: Number(process.env.DB_PORT) || 9109,
|
||||
user: process.env.DB_USER || 'yx-nav',
|
||||
password: process.env.DB_PASS || 'yx-nav',
|
||||
database: process.env.DB_NAME || 'yx-nav',
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0,
|
||||
});
|
||||
|
||||
const db = new Database(dbPath);
|
||||
export async function initDB() {
|
||||
const conn = await pool.getConnection();
|
||||
try {
|
||||
await conn.query('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, nickname VARCHAR(50) DEFAULT "管理员", role VARCHAR(20) DEFAULT "admin", created_at DATETIME DEFAULT CURRENT_TIMESTAMP)');
|
||||
await conn.query('CREATE TABLE IF NOT EXISTS categories (id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, icon VARCHAR(50) DEFAULT "🔗", sort INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)');
|
||||
await conn.query('CREATE TABLE IF NOT EXISTS links (id INTEGER PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100) NOT NULL, url VARCHAR(255) NOT NULL, category_id INTEGER NOT NULL, description TEXT, icon_url VARCHAR(255), sort INTEGER DEFAULT 0, is_show TINYINT DEFAULT 1, views INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE)');
|
||||
await conn.query('CREATE TABLE IF NOT EXISTS settings (id INTEGER PRIMARY KEY AUTO_INCREMENT, key VARCHAR(50) UNIQUE NOT NULL, value TEXT NOT NULL, description VARCHAR(100) DEFAULT "")');
|
||||
|
||||
// 启用 WAL 模式和外键
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
const [hasAdmin] = await conn.query("SELECT 1 FROM users WHERE username = 'admin'");
|
||||
if (hasAdmin.length === 0) {
|
||||
import('bcryptjs').then(({ default: bcrypt }) => {
|
||||
conn.query("INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)", ['admin', bcrypt.hashSync('admin123', 10), '管理员']);
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化数据库表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password TEXT NOT NULL,
|
||||
nickname TEXT DEFAULT '管理员',
|
||||
role TEXT DEFAULT 'admin',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
const [hasCat] = await conn.query("SELECT 1 FROM categories WHERE name = '常用网站'");
|
||||
if (hasCat.length === 0) {
|
||||
await conn.query("INSERT INTO categories (name, icon, sort) VALUES ('常用网站','🌟',0)");
|
||||
await conn.query("INSERT INTO categories (name, icon, sort) VALUES ('开发工具','💻',1)");
|
||||
await conn.query("INSERT INTO categories (name, icon, sort) VALUES ('新闻资讯','📰',2)");
|
||||
await conn.query("INSERT INTO categories (name, icon, sort) VALUES ('娱乐休闲','🎮',3)");
|
||||
await conn.query("INSERT INTO categories (name, icon, sort) VALUES ('学习资源','📚',4)");
|
||||
}
|
||||
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
icon TEXT DEFAULT '🔗',
|
||||
sort INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
const [hasLinks] = await conn.query('SELECT 1 FROM links');
|
||||
if (hasLinks.length === 0) {
|
||||
await conn.query("INSERT INTO links (title,url,description,category_id,sort) VALUES ('百度','https://www.baidu.com','全球最大的中文搜索引擎',1,0)");
|
||||
await conn.query("INSERT INTO links (title,url,description,category_id,sort) VALUES ('GitHub','https://github.com','全球最大的代码托管平台',2,0)");
|
||||
await conn.query("INSERT INTO links (title,url,description,category_id,sort) VALUES ('掘金','https://juejin.cn','技术社区',2,1)");
|
||||
await conn.query("INSERT INTO links (title,url,description,category_id,sort) VALUES ('知乎','https://www.zhihu.com','问答社区',3,0)");
|
||||
await conn.query("INSERT INTO links (title,url,description,category_id,sort) VALUES ('Bilibili','https://www.bilibili.com','视频网站',4,0)");
|
||||
await conn.query("INSERT INTO links (title,url,description,category_id,sort) VALUES ('慕课网','https://www.imooc.com','在线学习平台',5,0)");
|
||||
}
|
||||
|
||||
CREATE TABLE IF NOT EXISTS links (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
category_id INTEGER NOT NULL,
|
||||
description TEXT DEFAULT '',
|
||||
icon_url TEXT DEFAULT '',
|
||||
sort INTEGER DEFAULT 0,
|
||||
is_show INTEGER DEFAULT 1,
|
||||
views INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
key TEXT UNIQUE NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
description TEXT DEFAULT ''
|
||||
);
|
||||
`);
|
||||
|
||||
// 初始化默认配置
|
||||
const defaultSettings = {
|
||||
site_name: '言逍导航',
|
||||
site_description: '精心整理的网址导航',
|
||||
site_logo: '',
|
||||
theme_color: '#6366F1',
|
||||
layout_mode: 'grid',
|
||||
footer_text: '© 2026 言逍导航',
|
||||
};
|
||||
for (const [key, value] of Object.entries(defaultSettings)) {
|
||||
db.prepare('INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)').run(key, value);
|
||||
await conn.query("INSERT IGNORE INTO settings (key,value) VALUES ('site_name','言逍导航')");
|
||||
await conn.query("INSERT IGNORE INTO settings (key,value) VALUES ('site_description','精心整理的网址导航')");
|
||||
await conn.query("INSERT IGNORE INTO settings (key,value) VALUES ('theme_color','#6366F1')");
|
||||
await conn.query("INSERT IGNORE INTO settings (key,value) VALUES ('layout_mode','grid')");
|
||||
await conn.query("INSERT IGNORE INTO settings (key,value) VALUES ('footer_text','© 2026 言逍导航')");
|
||||
} finally {
|
||||
conn.release();
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化默认管理员
|
||||
if (!db.prepare("SELECT 1 FROM users WHERE username = 'admin'").get()) {
|
||||
const hashed = bcrypt.hashSync('admin123', 10);
|
||||
db.prepare("INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)").run('admin', hashed, '管理员');
|
||||
}
|
||||
|
||||
// 初始化默认分类
|
||||
if (!db.prepare("SELECT 1 FROM categories WHERE name = '常用网站'").get()) {
|
||||
const cats = [
|
||||
{ name: '常用网站', icon: '🌟' },
|
||||
{ name: '开发工具', icon: '💻' },
|
||||
{ name: '新闻资讯', icon: '📰' },
|
||||
{ name: '娱乐休闲', icon: '🎮' },
|
||||
{ name: '学习资源', icon: '📚' },
|
||||
];
|
||||
const stmt = db.prepare("INSERT INTO categories (name, icon, sort) VALUES (?, ?, ?)");
|
||||
cats.forEach((c, i) => stmt.run(c.name, c.icon, i));
|
||||
}
|
||||
|
||||
// 初始化示例链接
|
||||
if (!db.prepare("SELECT 1 FROM links").get()) {
|
||||
const links = [
|
||||
{ title: '百度', url: 'https://www.baidu.com', desc: '全球最大的中文搜索引擎', cat: 1 },
|
||||
{ title: 'GitHub', url: 'https://github.com', desc: '全球最大的代码托管平台', cat: 2 },
|
||||
{ title: '掘金', url: 'https://juejin.cn', desc: '技术社区', cat: 2 },
|
||||
{ title: '知乎', url: 'https://www.zhihu.com', desc: '问答社区', cat: 3 },
|
||||
{ title: 'Bilibili', url: 'https://www.bilibili.com', desc: '视频网站', cat: 4 },
|
||||
{ title: '慕课网', url: 'https://www.imooc.com', desc: '在线学习平台', cat: 5 },
|
||||
];
|
||||
const stmt = db.prepare(
|
||||
"INSERT INTO links (title, url, description, category_id, sort) VALUES (?, ?, ?, ?, ?)"
|
||||
);
|
||||
links.forEach((l, i) => stmt.run(l.title, l.url, l.desc, l.cat, i));
|
||||
}
|
||||
|
||||
export default db;
|
||||
|
||||
+12
-13
@@ -2,34 +2,33 @@ import express from 'express';
|
||||
import cors from 'cors';
|
||||
import helmet from 'helmet';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import db from './database.js';
|
||||
import { pool, initDB } from './database.js';
|
||||
import apiRoutes from './routes/api.js';
|
||||
import { authenticate } from './middleware/auth.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
// 安全中间件
|
||||
app.use(helmet());
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// 限流
|
||||
const limiter = rateLimit({ windowMs: 60_000, max: 200 });
|
||||
app.use(limiter);
|
||||
|
||||
// 路由
|
||||
apiRoutes(app);
|
||||
|
||||
// 健康检查
|
||||
app.get('/api/health', (_req, res) => {
|
||||
res.json({ status: 200, message: 'ok' });
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
try {
|
||||
await pool.query('SELECT 1');
|
||||
res.json({ status: 200, message: 'ok', db: 'connected' });
|
||||
} catch {
|
||||
res.json({ status: 200, message: 'ok', db: 'disconnected' });
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 yx-nav backend running at http://localhost:${PORT}`);
|
||||
initDB().then(() => {
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 yx-nav backend running at http://localhost:${PORT} (MySQL: 110.42.189.169:9109)`);
|
||||
});
|
||||
});
|
||||
|
||||
+147
-77
@@ -1,4 +1,4 @@
|
||||
import db from '../database.js';
|
||||
import { pool } from '../database.js';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { authenticate } from '../middleware/auth.js';
|
||||
@@ -7,117 +7,187 @@ const SECRET = process.env.JWT_SECRET || 'yx-nav-secret-2026';
|
||||
|
||||
const router = (app) => {
|
||||
// ---- 公开接口 ----
|
||||
app.post('/api/auth/login', (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
||||
if (!user || !bcrypt.compareSync(password, user.password)) {
|
||||
return res.json({ status: 401, message: '用户名或密码错误' });
|
||||
app.post('/api/auth/login', async (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
const [users] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
|
||||
if (!users.length || !bcrypt.compareSync(password, users[0].password)) {
|
||||
return res.json({ status: 401, message: '用户名或密码错误' });
|
||||
}
|
||||
const user = users[0];
|
||||
const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '7d' });
|
||||
res.json({ status: 200, message: '登录成功', result: { token, user: { id: user.id, nickname: user.nickname } } });
|
||||
} catch {
|
||||
res.json({ status: 401, message: '登录失败' });
|
||||
}
|
||||
const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '7d' });
|
||||
res.json({ status: 200, message: '登录成功', result: { token, user: { id: user.id, nickname: user.nickname } } });
|
||||
});
|
||||
|
||||
app.get('/api/site', (req, res) => {
|
||||
const cats = db.prepare('SELECT * FROM categories ORDER BY sort, id').all();
|
||||
const links = db.prepare('SELECT l.*, c.name as categoryName FROM links l JOIN categories c ON l.category_id = c.id WHERE l.is_show = 1 ORDER BY c.sort, l.sort, l.id').all();
|
||||
const settings = {};
|
||||
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
|
||||
res.json({ status: 200, result: { data: { categories: cats, links, settings } } });
|
||||
app.get('/api/site', async (req, res) => {
|
||||
try {
|
||||
const [cats] = await pool.query('SELECT * FROM categories ORDER BY sort, id');
|
||||
const [links] = await pool.query('SELECT l.*, c.name as categoryName FROM links l JOIN categories c ON l.category_id = c.id WHERE l.is_show = 1 ORDER BY c.sort, l.sort, l.id');
|
||||
const [sets] = await pool.query('SELECT * FROM settings');
|
||||
const settings = {};
|
||||
sets.forEach(s => { settings[s.key] = s.value; });
|
||||
res.json({ status: 200, result: { data: { categories: cats, links, settings } } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '加载失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/site/stats', (req, res) => {
|
||||
const cats = db.prepare('SELECT c.*, COUNT(l.id) as linkCount FROM categories c LEFT JOIN links l ON c.id = l.category_id AND l.is_show = 1 GROUP BY c.id ORDER BY c.sort, c.id').all();
|
||||
const settings = {};
|
||||
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
|
||||
res.json({ status: 200, result: { data: { categories: cats, settings } } });
|
||||
app.get('/api/site/stats', async (req, res) => {
|
||||
try {
|
||||
const [cats] = await pool.query('SELECT c.*, COUNT(l.id) as linkCount FROM categories c LEFT JOIN links l ON c.id = l.category_id AND l.is_show = 1 GROUP BY c.id ORDER BY c.sort, c.id');
|
||||
const [sets] = await pool.query('SELECT * FROM settings');
|
||||
const settings = {};
|
||||
sets.forEach(s => { settings[s.key] = s.value; });
|
||||
res.json({ status: 200, result: { data: { categories: cats, settings } } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '加载失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/links/:id/view', (req, res) => {
|
||||
db.prepare('UPDATE links SET views = views + 1 WHERE id = ?').run(Number(req.params.id));
|
||||
res.json({ status: 200, result: { data: {} } });
|
||||
app.post('/api/links/:id/view', async (req, res) => {
|
||||
try {
|
||||
await pool.query('UPDATE links SET views = views + 1 WHERE id = ?', [Number(req.params.id)]);
|
||||
res.json({ status: 200, result: { data: {} } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '更新失败' });
|
||||
}
|
||||
});
|
||||
|
||||
// ---- 后台管理接口 ----
|
||||
app.get('/api/admin/profile', authenticate, (req, res) => {
|
||||
const user = db.prepare('SELECT id, username, nickname, role FROM users WHERE id = ?').get(req.user.id);
|
||||
res.json({ status: 200, result: { data: user } });
|
||||
app.get('/api/admin/profile', authenticate, async (req, res) => {
|
||||
try {
|
||||
const [users] = await pool.query('SELECT id, username, nickname, role FROM users WHERE id = ?', [req.user.id]);
|
||||
res.json({ status: 200, result: { data: users[0] } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '加载失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/admin/profile', authenticate, (req, res) => {
|
||||
db.prepare('UPDATE users SET nickname = ? WHERE id = ?').run(req.body.nickname, req.user.id);
|
||||
res.json({ status: 200, message: '更新成功' });
|
||||
app.put('/api/admin/profile', authenticate, async (req, res) => {
|
||||
try {
|
||||
await pool.query('UPDATE users SET nickname = ? WHERE id = ?', [req.body.nickname, req.user.id]);
|
||||
res.json({ status: 200, message: '更新成功' });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '更新失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/admin/categories', authenticate, (req, res) => {
|
||||
res.json({ status: 200, result: { data: db.prepare('SELECT * FROM categories ORDER BY sort, id').all() } });
|
||||
app.get('/api/admin/categories', authenticate, async (req, res) => {
|
||||
try {
|
||||
const [rows] = await pool.query('SELECT * FROM categories ORDER BY sort, id');
|
||||
res.json({ status: 200, result: { data: rows } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '加载失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/admin/categories', authenticate, (req, res) => {
|
||||
const { name, icon, sort } = req.body;
|
||||
const r = db.prepare('INSERT INTO categories (name, icon, sort) VALUES (?, ?, ?)').run(name, icon || '🔗', sort || 0);
|
||||
res.json({ status: 200, message: '创建成功', result: { data: { id: Number(r.lastInsertRowid) } } });
|
||||
app.post('/api/admin/categories', authenticate, async (req, res) => {
|
||||
try {
|
||||
const { name, icon, sort } = req.body;
|
||||
const [result] = await pool.query('INSERT INTO categories (name, icon, sort) VALUES (?, ?, ?)', [name, icon || '🔗', sort || 0]);
|
||||
res.json({ status: 200, message: '创建成功', result: { data: { id: Number(result.insertId) } } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '创建失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/admin/categories/:id', authenticate, (req, res) => {
|
||||
const { name, icon, sort } = req.body;
|
||||
db.prepare('UPDATE categories SET name = ?, icon = ?, sort = ? WHERE id = ?').run(name, icon, sort, Number(req.params.id));
|
||||
res.json({ status: 200, message: '更新成功' });
|
||||
app.put('/api/admin/categories/:id', authenticate, async (req, res) => {
|
||||
try {
|
||||
const { name, icon, sort } = req.body;
|
||||
await pool.query('UPDATE categories SET name = ?, icon = ?, sort = ? WHERE id = ?', [name, icon, sort, Number(req.params.id)]);
|
||||
res.json({ status: 200, message: '更新成功' });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '更新失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/admin/categories/:id', authenticate, (req, res) => {
|
||||
db.prepare('DELETE FROM categories WHERE id = ?').run(Number(req.params.id));
|
||||
res.json({ status: 200, message: '删除成功' });
|
||||
app.delete('/api/admin/categories/:id', authenticate, async (req, res) => {
|
||||
try {
|
||||
await pool.query('DELETE FROM categories WHERE id = ?', [Number(req.params.id)]);
|
||||
res.json({ status: 200, message: '删除成功' });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '删除失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/admin/links', authenticate, (req, res) => {
|
||||
const { keyword, categoryId } = req.query;
|
||||
let sql = 'SELECT l.*, c.name as categoryName FROM links l JOIN categories c ON l.category_id = c.id';
|
||||
const params = [];
|
||||
if (keyword) { sql += ' WHERE l.title LIKE ? OR l.description LIKE ?'; params.push(`%${keyword}%`, `%${keyword}%`); }
|
||||
if (categoryId) { sql += (keyword ? ' AND' : ' WHERE') + ' l.category_id = ?'; params.push(Number(categoryId)); }
|
||||
sql += ' ORDER BY l.sort, l.id';
|
||||
res.json({ status: 200, result: { data: db.prepare(sql).all(...params) } });
|
||||
app.get('/api/admin/links', authenticate, async (req, res) => {
|
||||
try {
|
||||
const { keyword, categoryId } = req.query;
|
||||
let sql = 'SELECT l.*, c.name as categoryName FROM links l JOIN categories c ON l.category_id = c.id';
|
||||
const params = [];
|
||||
if (keyword) { sql += ' WHERE l.title LIKE ? OR l.description LIKE ?'; params.push(`%${keyword}%`, `%${keyword}%`); }
|
||||
if (categoryId) { sql += (keyword ? ' AND' : ' WHERE') + ' l.category_id = ?'; params.push(Number(categoryId)); }
|
||||
sql += ' ORDER BY l.sort, l.id';
|
||||
const [rows] = await pool.query(sql, params);
|
||||
res.json({ status: 200, result: { data: rows } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '加载失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/admin/links', authenticate, (req, res) => {
|
||||
const { title, url, categoryId, description, iconUrl, sort, isShow } = req.body;
|
||||
const r = db.prepare(
|
||||
'INSERT INTO links (title, url, category_id, description, icon_url, sort, is_show) VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(title, url, Number(categoryId), description || '', iconUrl || '', sort || 0, isShow !== false ? 1 : 0);
|
||||
res.json({ status: 200, message: '创建成功', result: { data: { id: Number(r.lastInsertRowid) } } });
|
||||
app.post('/api/admin/links', authenticate, async (req, res) => {
|
||||
try {
|
||||
const { title, url, categoryId, description, iconUrl, sort, isShow } = req.body;
|
||||
const [result] = await pool.query('INSERT INTO links (title, url, category_id, description, icon_url, sort, is_show) VALUES (?, ?, ?, ?, ?, ?, ?)', [title, url, Number(categoryId), description || '', iconUrl || '', sort || 0, isShow !== false ? 1 : 0]);
|
||||
res.json({ status: 200, message: '创建成功', result: { data: { id: Number(result.insertId) } } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '创建失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/admin/links/:id', authenticate, (req, res) => {
|
||||
const { title, url, categoryId, description, iconUrl, sort, isShow } = req.body;
|
||||
db.prepare(
|
||||
'UPDATE links SET title=?, url=?, category_id=?, description=?, icon_url=?, sort=?, is_show=? WHERE id=?'
|
||||
).run(title, url, Number(categoryId), description, iconUrl, sort, isShow !== false ? 1 : 0, Number(req.params.id));
|
||||
res.json({ status: 200, message: '更新成功' });
|
||||
app.put('/api/admin/links/:id', authenticate, async (req, res) => {
|
||||
try {
|
||||
const { title, url, categoryId, description, iconUrl, sort, isShow } = req.body;
|
||||
await pool.query('UPDATE links SET title=?, url=?, category_id=?, description=?, icon_url=?, sort=?, is_show=? WHERE id=?', [title, url, Number(categoryId), description, iconUrl, sort, isShow !== false ? 1 : 0, Number(req.params.id)]);
|
||||
res.json({ status: 200, message: '更新成功' });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '更新失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/admin/links/:id', authenticate, (req, res) => {
|
||||
db.prepare('DELETE FROM links WHERE id = ?').run(Number(req.params.id));
|
||||
res.json({ status: 200, message: '删除成功' });
|
||||
app.delete('/api/admin/links/:id', authenticate, async (req, res) => {
|
||||
try {
|
||||
await pool.query('DELETE FROM links WHERE id = ?', [Number(req.params.id)]);
|
||||
res.json({ status: 200, message: '删除成功' });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '删除失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/admin/links/sort', authenticate, (req, res) => {
|
||||
(req.body.sorts || []).forEach(({ id, sort }) => {
|
||||
db.prepare('UPDATE links SET sort = ? WHERE id = ?').run(sort, Number(id));
|
||||
});
|
||||
res.json({ status: 200, message: '排序成功' });
|
||||
app.put('/api/admin/links/sort', authenticate, async (req, res) => {
|
||||
try {
|
||||
for (const { id, sort } of (req.body.sorts || [])) {
|
||||
await pool.query('UPDATE links SET sort = ? WHERE id = ?', [sort, Number(id)]);
|
||||
}
|
||||
res.json({ status: 200, message: '排序成功' });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '排序失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/admin/settings', authenticate, (req, res) => {
|
||||
const settings = {};
|
||||
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
|
||||
res.json({ status: 200, result: { data: settings } });
|
||||
app.get('/api/admin/settings', authenticate, async (req, res) => {
|
||||
try {
|
||||
const [sets] = await pool.query('SELECT * FROM settings');
|
||||
const settings = {};
|
||||
sets.forEach(s => { settings[s.key] = s.value; });
|
||||
res.json({ status: 200, result: { data: settings } });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '加载失败' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/admin/settings', authenticate, (req, res) => {
|
||||
for (const [key, value] of Object.entries(req.body)) {
|
||||
db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?').run(key, value, value);
|
||||
app.put('/api/admin/settings', authenticate, async (req, res) => {
|
||||
try {
|
||||
for (const [key, value] of Object.entries(req.body)) {
|
||||
await pool.query('INSERT INTO settings (key, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)', [key, value]);
|
||||
}
|
||||
res.json({ status: 200, message: '保存成功' });
|
||||
} catch {
|
||||
res.json({ status: 500, message: '保存失败' });
|
||||
}
|
||||
res.json({ status: 200, message: '保存成功' });
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
import db from '../database.js';
|
||||
import { generateToken } from '../middleware/auth.js';
|
||||
|
||||
export const login = (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
||||
if (!user) return res.json({ status: 401, message: '用户名或密码错误' });
|
||||
if (!bcrypt.compareSync(password, user.password)) {
|
||||
return res.json({ status: 401, message: '用户名或密码错误' });
|
||||
}
|
||||
res.json({ status: 200, message: '登录成功', result: { token: generateToken(user.id), user: { id: user.id, nickname: user.nickname } } });
|
||||
};
|
||||
|
||||
export const profile = (req, res) => {
|
||||
const user = db.prepare('SELECT id, username, nickname, role FROM users WHERE id = ?').get(req.user.id);
|
||||
res.json({ status: 200, result: { data: user } });
|
||||
};
|
||||
|
||||
export const updateProfile = (req, res) => {
|
||||
const { nickname } = req.body;
|
||||
db.prepare('UPDATE users SET nickname = ? WHERE id = ?').run(nickname, req.user.id);
|
||||
res.json({ status: 200, message: '更新成功' });
|
||||
};
|
||||
|
||||
export const logout = (req, res) => {
|
||||
res.json({ status: 200, message: '退出成功' });
|
||||
};
|
||||
@@ -1,16 +0,0 @@
|
||||
import db from '../database.js';
|
||||
|
||||
export const list = (req, res) => {
|
||||
const cats = db.prepare('SELECT * FROM categories ORDER BY sort, id').all();
|
||||
const links = db.prepare('SELECT * FROM links WHERE is_show = 1 ORDER BY sort, id').all();
|
||||
const settings = {};
|
||||
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
|
||||
res.json({ status: 200, result: { data: { categories: cats, links, settings } } });
|
||||
};
|
||||
|
||||
export const listWithStats = (req, res) => {
|
||||
const cats = db.prepare('SELECT c.*, COUNT(l.id) as linkCount FROM categories c LEFT JOIN links l ON c.id = l.category_id AND l.is_show = 1 GROUP BY c.id ORDER BY c.sort, c.id').all();
|
||||
const settings = {};
|
||||
db.prepare('SELECT * FROM settings').all().forEach(s => { settings[s.key] = s.value; });
|
||||
res.json({ status: 200, result: { data: { categories: cats, settings } } });
|
||||
};
|
||||
Reference in New Issue
Block a user