• 官网koa2
  • 脚手架:

    用koa2 创建项目

  • 创建repo biz-editor-server(为何设置私有private ? )

  • 本地,用脚手架生成项目
  • 调整项目目录,代码都放在src目录下

image.png

  • 连接数据库:
    • 安装数据库驱动:
    • 新建文件,存放数据库配置 ```javascript module.exports = { // mysql 连接配置 mysqlConf: { host: “localhost”, user: “root”, password: “@wjy123456”, port: “3306”, database: “low_code”, }, };
  1. - 连接数据库:新建db/mysql2.js,测试连接
  2. ```javascript
  3. const mysql = require("mysql2/promise");
  4. const { mysqlConf } = require("../config/envs/dev");
  5. async function testMysqlConn() {
  6. const connection = await mysql.createConnection(mysqlConf);
  7. const [rows] = await connection.execute("select now();");
  8. console.log("rows", rows);
  9. }
  10. (async () => {
  11. testMysqlConn();
  12. })();
  • 测试数据库连接

    1. // 测试数据库连接
    2. router.get("/api/db-check", async (ctx, next) => {
    3. // 测试 mysql 连接
    4. const mysqlRes = await testMysqlConn();
    5. ctx.body = {
    6. errno: 0,
    7. data: {
    8. name: "biz editor sever",
    9. version: packageInfo.version,
    10. // ENV,
    11. // redisConn: redisTestVal != null,
    12. mysqlConn: mysqlRes.length > 0,
    13. // mongodbConn,
    14. },
    15. };
    16. });
  • 配置数据库ORM框架:sequeliz,它让开发者不用写繁琐的SQL语句,通过API即可操作数据,步骤:
    • 安装
    • 数据库连接 ```javascript /**
      • @description 配置 sequelize ,连接 mysql
      • @author 双越 */

const Sequelize = require(‘sequelize’) const { mysqlConf } = require(‘../../config/index’) const { isPrd, isTest } = require(‘../../utils/env’)

// 连接配置 const { database, user, password, host, port } = mysqlConf const conf = { host, port, dialect: ‘mysql’, }

// 测试环境不打印日志 if (isTest) { conf.logging = () => {} // 默认是 console.log }

// 线上环境用 链接池 if (isPrd) { conf.pool = { max: 5, // 连接池中最大连接数量 min: 0, // 连接池中最小连接数量 idle: 10000, // 如果一个线程 10 秒钟内没有被使用过的话,那么就释放线程 } }

// 创建连接 const seq = new Sequelize(database, user, password, conf)

module.exports = seq

  1. ```javascript
  2. // conn-test.js
  3. const seq = require("../seq");
  4. (async () => {
  5. try {
  6. await seq.authenticate();
  7. console.log("Connection has been established successfully.");
  8. } catch (error) {
  9. console.error("Unable to connect to the database:", error);
  10. }
  11. })();
  • 创建数据模型 ```javascript const { Sequelize, DataTypes } = require(‘sequelize’); const sequelize = new Sequelize(‘sqlite::memory:’);

const User = sequelize.define(‘User’, { // Model attributes are defined here firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING // allowNull defaults to true } }, { // Other model options go here });

// sequelize.define also returns the model console.log(User === sequelize.models.User); // true

  1. - **模型和数据表的同步**:每当model模型做了修改,得把修改同步到数据库,在 `bin/www` 启动服务时去同步修改
  2. ```javascript
  3. // 同步数据表
  4. async function syncDb() {
  5. let needToSyncDb = true
  6. // 只适用于开发环境!!!
  7. if (isDev) {
  8. // 开发环境下,修改频繁,每次重启都同步数据表,消耗太大
  9. // 所以,开发环境下,判断是否修改了 src/models 中的内容?
  10. // 如果是,则同步数据表。否则,不用同步数据表。
  11. const git = simpleGit()
  12. // 获取 git status 修改的文件,modified 格式如 [ '.gitignore', 'package.json', 'src/models/README.md' ]
  13. const { modified, not_added: nodeAdded, created, deleted, renamed } = await git.status()
  14. const fileChanged = modified
  15. .concat(nodeAdded)
  16. .concat(created)
  17. .concat(deleted)
  18. .concat(renamed)
  19. if (fileChanged.length) {
  20. // 到此,说明 git status 有改动
  21. // 是否改动了 db 相关的文件
  22. const changedDbFiles = fileChanged.some(f => {
  23. // 改动了 src/models ,需要同步数据库
  24. if (f.indexOf('src/models/') === 0) return true
  25. // 改动了 src/db/seq ,需要同步数据库
  26. if (f.indexOf('src/db/seq/') === 0) return true
  27. // 其他情况,不同步
  28. return false
  29. })
  30. // 没改动 db 文件,则不需要同步
  31. if (!changedDbFiles) needToSyncDb = false
  32. }
  33. // 如果 git status 没有改动,则照常同步数据表,重要!!!
  34. }
  35. // 执行同步修改
  36. if (needToSyncDb) {
  37. await seq.sync({ alter: true })
  38. }
  39. }