2.egg+mysql

380 阅读2分钟

一.egg作为服务端向外提供接口
分析从请求端到服务端再到请求端的逻辑,结合洋葱头模型,很容易得出如下处理方式:
router => controller => 内置对象ctx => service => extend => service => controller router分发路由进入controller
controller获取通过内置对象ctx获取请求端入参
controller携带参数进入service
service处理内部逻辑,如有需要调取extend中的公共方法
service将处理结果返回controller
controller交付请求方

二.egg-mysql
安装对应的插件 egg-mysql :

$ npm i --save egg-mysql

开启插件:

// config/plugin.js
exports.mysql = {
  enable: true,
  package: 'egg-mysql',
};

在 config/config.${env}.js 配置各个环境的数据库连接信息。

// config/config.${env}.js
exports.mysql = {
  // 单数据库信息配置
  client: {
    // host
    host: 'mysql.com',
    // 端口号
    port: '3306',
    // 用户名
    user: 'test_user',
    // 密码
    password: 'test_password',
    // 数据库名
    database: 'test',
  },
  // 是否加载到 app 上,默认开启
  app: true,
  // 是否加载到 agent 上,默认关闭
  agent: false,
};

Create

// 插入
const result = await this.app.mysql.insert('posts', { title: 'Hello World' }); // 在 post 表中,插入 title 为 Hello World 的记录

=> INSERT INTO `posts`(`title`) VALUES('Hello World');

console.log(result);
=>
{
  fieldCount: 0,
  affectedRows: 1,
  insertId: 3710,
  serverStatus: 2,
  warningCount: 2,
  message: '',
  protocol41: true,
  changedRows: 0
}

// 判断插入成功
const insertSuccess = result.affectedRows === 1;

Read 查询一条记录

const post = await this.app.mysql.get('posts', { id: 12 });

=> SELECT * FROM `posts` WHERE `id` = 12 LIMIT 0, 1;

查询全表

const results = await this.app.mysql.select('posts');

=> SELECT * FROM `posts`;

Update

// 修改数据,将会根据主键 ID 查找,并更新
const row = {
  id: 123,
  name: 'fengmk2',
  otherField: 'other field value',    // any other fields u want to update
  modifiedAt: this.app.mysql.literals.now, // `now()` on db server
};
const result = await this.app.mysql.update('posts', row); // 更新 posts 表中的记录

=> UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE id = 123 ;

// 判断更新成功
const updateSuccess = result.affectedRows === 1;

// 如果主键是自定义的 ID 名称,如 custom_id,则需要在 `where` 里面配置
const row = {
  name: 'fengmk2',
  otherField: 'other field value',    // any other fields u want to update
  modifiedAt: this.app.mysql.literals.now, // `now()` on db server
};

const options = {
  where: {
    custom_id: 456
  }
};
const result = await this.app.mysql.update('posts', row, options); // 更新 posts 表中的记录

=> UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE custom_id = 456 ;

// 判断更新成功
const updateSuccess = result.affectedRows === 1;

Delete

const result = await this.app.mysql.delete('posts', {
  author: 'fengmk2',
});

=> DELETE FROM `posts` WHERE `author` = 'fengmk2';

三.案例
router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.user.find);
  router.post('/insert', controller.user.insert);
  router.post('/saveOrUpdateHabit', controller.updateSpaceUp.saveOrUpdateHabit);
  router.post('/getErr', controller.errLogs.getErr);
  router.get('/readErr', controller.errLogs.readErr);
};

controller

// app/controller/user.js
'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async find() {
    const ctx = this.ctx;
    const user = await ctx.service.user.find();
    ctx.body = user;
  }
  async insert() {
    const ctx = this.ctx;
    const user = await ctx.service.user.insert(ctx.request.body);
    ctx.body = user;
  }
}

module.exports = UserController;

service

// app/service/user.js
'use strict';
const Service = require('egg').Service;

class UserService extends Service {
  async find() {
    // 假如 我们拿到用户 id 从数据库获取用户详细信息
    const result = await this.app.mysql.select('columnsUpdate');
    return result;
  }
  async insert(body) {
    const result = await this.app.mysql.insert('columnsUpdate', { pageId: body.pageId, pageDesc: body.pageDesc, showField: body.showField, hideField: body.hideField }); // 在 post 表中,插入 title 为 Hello World 的记录
    return result;
  }
}
module.exports = UserService;