当前位置:   article > 正文

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

nodejs中使用mysql2

node js 环境版本

  • NodeJS 16 or later

  • TypeScript 4.9.3 or later

依赖模块安装

  1. npm install mysql2 --save
  2. npm install toml --save
  3. npm install moment-timezone --save
  4. npm install @types/moment --save

toml配置文件解析

config.ts

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

mysql数据库链接获取

  1. // mysql/connection.ts
  2. import config from "../config";
  3. import mysql from 'mysql2/promise';
  4. let connection: mysql.Connection;
  5. const getConnection = async () => {
  6.    if (!connection) {
  7.        connection = await mysql.createConnection({
  8.            host     : config.mysql.host,
  9.            user     : config.mysql.user,
  10.            password : config.mysql.password,
  11.            database : config.mysql.database
  12.       });
  13.   }
  14.    return connection;
  15. }
  16. export {
  17.    getConnection
  18. };

mysql数据库操作对象定义

  1. // metrics/add-client-log.ts
  2. import moment from "moment-timezone";
  3. import config from "config";
  4. import { getConnection } from "../mysql/connection";
  5. export default async function addClientLog(clientId: string, eventKey: string, eventValue: string): Promise<void> {
  6.    const connection = await getConnection();
  7.    const enableLogging = config.runtime.enableLogging ?? false;
  8.    if (!enableLogging) {
  9.        return;
  10.   }
  11.    const date = moment().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
  12.    await connection.query(
  13.        `INSERT INTO client_log
  14.         VALUES (
  15.             0,
  16.             "${connection.escape(clientId)}",
  17.             "${connection.escape(eventKey)}",
  18.             "${connection.escape(eventValue)}",
  19.             "${date}"
  20.        )
  21.    `);
  22. }
 

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

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

相关资源

  1. CREATE TABLE IF NOT EXISTS `client_log` (
  2.  `id` int NOT NULL AUTO_INCREMENT,
  3.  `clientId` varchar(255) DEFAULT NULL,
  4.  `eventKey` varchar(255) DEFAULT NULL,
  5.  `eventValue` text,
  6.  `date` datetime DEFAULT NULL,
  7.  PRIMARY KEY (`id`)
  8. );

config.toml

  1. environment = "local"
  2. ###
  3. # Config for the web and websockets servers
  4. # The password is for any routes you want to password protect
  5. # By default this is only the endpoint that lists active connections for debugging purposes
  6. ###
  7. [server]
  8. httpPort = 8000
  9. websocketPort = 8080
  10. domain = 'localhost'
  11. password = 'changeme'
  12. # A list of banned IPs
  13. bannedIps = [
  14.    '999.999.999.999',
  15. ]
  16. # A list of banned Client IDs
  17. bannedClientIds = [
  18.    'df3453rewr349543utff'
  19. ]
  20. # A list of banned hostnames
  21. bannedHostnames = [
  22.    'evil.com'
  23. ]
  24. ###
  25. # MySQL is used for Logging wnen it is enabled
  26. ###
  27. [mysql]
  28. host = 'localhost'
  29. user = 'root'
  30. password = 'changeme'
  31. database = 'test'
  32. ###
  33. # Enable or disable debug output and logging
  34. ###
  35. [runtime]
  36. debug = true
  37. enableLogging = false

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/454495
推荐阅读
相关标签
  

闽ICP备14008679号