Files
yx-nav/backend/src/database.js
T
Agent 05330fc965 feat: 分类层级支持(parent_id)
- 数据库 migration: categories 加 parent_id 字段(幂等)
- 后端 API: POST/PUT 支持 parentId 参数
- 前端 Home.vue: 分类树展示,父→子层级渲染
- 前端 Categories.vue: 编辑弹窗加父级选择,表格显示父级
- 前端 Links.vue: 分类下拉显示层级前缀
2026-07-16 10:26:29 +08:00

108 lines
4.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import mysql from 'mysql2/promise';
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,
});
async function row(conn, sql, params) {
const [rows] = await conn.query(sql, params);
return rows;
}
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,
UNIQUE KEY uk_link_url (url)
)`);
// 给已存在的 links 表补唯一索引(幂等)
try { await conn.query("ALTER TABLE links ADD UNIQUE KEY uk_link_url (url)"); } catch { /* 已存在则忽略 */ }
// 给 categories 表补 parent_id 字段(幂等,支持层级分类)
try { await conn.query("ALTER TABLE categories ADD COLUMN parent_id INT DEFAULT NULL"); } catch { /* 已存在则忽略 */ }
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 ''
)`);
// 管理员(密码:qq755141)
const hasAdmin = await row(conn, "SELECT 1 FROM users WHERE username = 'admin'");
if (hasAdmin.length === 0) {
const bcrypt = (await import('bcryptjs')).default;
await conn.query("INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)",
['admin', bcrypt.hashSync('qq755141', 10), '管理员']);
}
// 分类
const hasCat = await row(conn, "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)");
await conn.query("INSERT INTO categories (name, icon, sort) VALUES ('学习资源','📚',5)");
}
// 用户给的网址
const userLinks = [
['百度', 'https://www.baidu.com', '搜索引擎', '常用网站'],
['GitHub', 'https://github.com', '代码托管', '开发工具'],
['base64解密', 'https://www.bejson.com/enc/base64/', 'base64解密/编码转换', '工具网站'],
['代码格式化', 'https://tool.oschina.net/codeformat/xml', '代码格式化/XML', '工具网站'],
['uuid5创建', 'https://www.uuid.online/', 'UUID5在线生成', '工具网站'],
];
const [cats] = await conn.query('SELECT id, name FROM categories');
const catMap = {};
cats.forEach(r => { catMap[r.name] = r.id; });
for (const [title, url, desc, cat] of userLinks) {
const cid = catMap[cat];
if (cid) {
await conn.query('INSERT IGNORE INTO links (title, url, description, category_id, sort) VALUES (?, ?, ?, ?, ?)',
[title, url, desc, cid, 0]);
}
}
console.log('initDB done, categories:', Object.keys(catMap).join(','), ', links inserted:', userLinks.length);
} finally {
conn.release();
}
}