- 官网koa2
-
用koa2 创建项目
创建repo biz-editor-server(为何设置私有private ? )
- 本地,用脚手架生成项目
- 调整项目目录,代码都放在src目录下
- 连接数据库:
- 安装数据库驱动:
- 新建文件,存放数据库配置 ```javascript module.exports = { // mysql 连接配置 mysqlConf: { host: “localhost”, user: “root”, password: “@wjy123456”, port: “3306”, database: “low_code”, }, };
- 连接数据库:新建db/mysql2.js,测试连接
```javascript
const mysql = require("mysql2/promise");
const { mysqlConf } = require("../config/envs/dev");
async function testMysqlConn() {
const connection = await mysql.createConnection(mysqlConf);
const [rows] = await connection.execute("select now();");
console.log("rows", rows);
}
(async () => {
testMysqlConn();
})();
测试数据库连接
// 测试数据库连接
router.get("/api/db-check", async (ctx, next) => {
// 测试 mysql 连接
const mysqlRes = await testMysqlConn();
ctx.body = {
errno: 0,
data: {
name: "biz editor sever",
version: packageInfo.version,
// ENV,
// redisConn: redisTestVal != null,
mysqlConn: mysqlRes.length > 0,
// mongodbConn,
},
};
});
- 配置数据库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
```javascript
// conn-test.js
const seq = require("../seq");
(async () => {
try {
await seq.authenticate();
console.log("Connection has been established successfully.");
} catch (error) {
console.error("Unable to connect to the database:", error);
}
})();
- 创建数据模型 ```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
- **模型和数据表的同步**:每当model模型做了修改,得把修改同步到数据库,在 `bin/www` 启动服务时去同步修改
```javascript
// 同步数据表
async function syncDb() {
let needToSyncDb = true
// 只适用于开发环境!!!
if (isDev) {
// 开发环境下,修改频繁,每次重启都同步数据表,消耗太大
// 所以,开发环境下,判断是否修改了 src/models 中的内容?
// 如果是,则同步数据表。否则,不用同步数据表。
const git = simpleGit()
// 获取 git status 修改的文件,modified 格式如 [ '.gitignore', 'package.json', 'src/models/README.md' ]
const { modified, not_added: nodeAdded, created, deleted, renamed } = await git.status()
const fileChanged = modified
.concat(nodeAdded)
.concat(created)
.concat(deleted)
.concat(renamed)
if (fileChanged.length) {
// 到此,说明 git status 有改动
// 是否改动了 db 相关的文件
const changedDbFiles = fileChanged.some(f => {
// 改动了 src/models ,需要同步数据库
if (f.indexOf('src/models/') === 0) return true
// 改动了 src/db/seq ,需要同步数据库
if (f.indexOf('src/db/seq/') === 0) return true
// 其他情况,不同步
return false
})
// 没改动 db 文件,则不需要同步
if (!changedDbFiles) needToSyncDb = false
}
// 如果 git status 没有改动,则照常同步数据表,重要!!!
}
// 执行同步修改
if (needToSyncDb) {
await seq.sync({ alter: true })
}
}