node js mysql2数据库 toml配置文件使用示例

node js 环境版本

  • NodeJS 16 or later

  • TypeScript 4.9.3 or later

依赖模块安装

npm install mysql2 --save
npm install toml --save
npm install moment-timezone --save
npm install @types/moment --save

toml配置文件解析

config.ts

// config.ts
import fs from 'fs';
import toml from 'toml';
​
// 读取当前文件夹下的 config.toml 配置文件
let config = toml.parse(fs.readFileSync('config.toml').toString());
​
export default config;

mysql数据库链接获取

// mysql/connection.ts
import config from "../config";
​
import mysql from 'mysql2/promise';
​
let connection: mysql.Connection;
​
const getConnection = async () => {
    if (!connection) {
        connection = await mysql.createConnection({
            host     : config.mysql.host,
            user     : config.mysql.user,
            password : config.mysql.password,
            database : config.mysql.database
        });
    }
​
    return connection;
}
​
export {
    getConnection
};

mysql数据库操作对象定义

// metrics/add-client-log.ts
import moment from "moment-timezone";
import config from "config";
import { getConnection } from "../mysql/connection";
​
export default async function addClientLog(clientId: string, eventKey: string, eventValue: string): Promise<void> {
    const connection = await getConnection();
    const enableLogging = config.runtime.enableLogging ?? false;
​
    if (!enableLogging) {
        return;
    }
​
    const date = moment().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
    await connection.query(
        `INSERT INTO client_log
         VALUES (
             0,
             "${connection.escape(clientId)}",
             "${connection.escape(eventKey)}",
             "${connection.escape(eventValue)}",
             "${date}"
        )
    `);
}
​
 

mysql数据库操作对象 使用示例

// config.ts
import addClientLog from '../metrics/add-client-log';
​
// 使用示例
await addClientLog(123, "initialized", "localhost");

相关资源

  • 数据库脚本

CREATE TABLE IF NOT EXISTS `client_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `clientId` varchar(255) DEFAULT NULL,
  `eventKey` varchar(255) DEFAULT NULL,
  `eventValue` text,
  `date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
);

config.toml

environment = "local"
​
###
# Config for the web and websockets servers
# The password is for any routes you want to password protect
# By default this is only the endpoint that lists active connections for debugging purposes
###
[server]
httpPort = 8000
websocketPort = 8080
domain = 'localhost'
password = 'changeme'
​
# A list of banned IPs
bannedIps = [
    '999.999.999.999',
]
​
# A list of banned Client IDs
bannedClientIds = [
    'df3453rewr349543utff'
]
​
# A list of banned hostnames
bannedHostnames = [
    'evil.com'
]
​
###
# MySQL is used for Logging wnen it is enabled
###
[mysql]
host = 'localhost'
user = 'root'
password = 'changeme'
database = 'test'
​
###
# Enable or disable debug output and logging
###
[runtime]
debug = true
enableLogging = false

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值