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

node js 环境版本

  • NodeJS 16 or later

  • TypeScript 4.9.3 or later

依赖模块安装

bash 复制代码
npm install mysql2 --save
npm install toml --save
npm install moment-timezone --save
npm install @types/moment --save

toml配置文件解析

config.ts

javascript 复制代码
// 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数据库链接获取

javascript 复制代码
// 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数据库操作对象定义

javascript 复制代码
// 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数据库操作对象 使用示例

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

相关资源

  • 数据库脚本
sql 复制代码
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

XML 复制代码
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
相关推荐
正在走向自律6 分钟前
豆包编程模型Doubao-Seed-Code深度体验,从零开始构建全栈项目的完整指南
java·服务器·数据库·doubao·claude code·火山方舟
h***8567 分钟前
MySQL数据分析
数据库·mysql
倔强的石头_12 分钟前
从海量时序数据到无人值守:数据库在新能源集控系统中的架构实践
数据库
十五年专注C++开发13 分钟前
libdatrie: 一个高效的 基于双数组字典树(Double-Array Trie)的C语言函数库
c语言·开发语言·trie
合作小小程序员小小店24 分钟前
web网页开发,在线%医院诊断管理%系统,基于Idea,html,css,jQuery,java,jsp,ssh,mysql。
java·前端·css·数据库·jdk·html·intellij-idea
Alita11101_24 分钟前
深度测评:openGauss 在虚拟机中对 SQL92 标准的兼容性
数据库
软件技术NINI26 分钟前
html css js网页制作成品——html+css+js5 页 jk制服附源码
javascript·css·html
w***954933 分钟前
【Redis】centos7 systemctl 启动 Redis 失败
数据库·redis·缓存
爱学习的程序媛34 分钟前
【Web前端】Vue2与Vue3核心概览与优化对比
前端·javascript·vue.js·typescript
Mr.徐大人ゞ34 分钟前
8.事务在 Group Replication 中的处理流程
mysql