29 lines
960 B
JavaScript
29 lines
960 B
JavaScript
import { drizzle } from 'drizzle-orm/mysql2';
|
|
import { sql } from 'drizzle-orm';
|
|
import mysql from 'mysql2/promise';
|
|
import fastifyPlugin from 'fastify-plugin';
|
|
async function database(fastify, options) {
|
|
fastify.log.warn('Register Database Plugin!');
|
|
const config = fastify.config;
|
|
// 配置数据库
|
|
const pool = await mysql.createPool({
|
|
host: config.db.host,
|
|
port: config.db.port,
|
|
user: config.db.user,
|
|
password: config.db.password,
|
|
database: config.db.database,
|
|
ssl: config.db.ssl,
|
|
waitForConnections: true,
|
|
connectionLimit: 10,
|
|
queueLimit: 0,
|
|
});
|
|
// 暴露数据库
|
|
const db = drizzle(pool);
|
|
// 新增获取所有表名方法
|
|
const [result] = await db.execute(sql`SHOW TABLES`);
|
|
const tableList = result.map(row => Object.values(row)[0]);
|
|
db.tableList = tableList;
|
|
fastify.decorate('db', db);
|
|
}
|
|
export default fastifyPlugin(database);
|