Egg 增删改查 mysql

2020-05-19  本文已影响0人  张思学

实现连接数据库后的基本功能

  1. app/router.js 添加路由
router.get('/user', controller.user.list); // 查
router.post('/user/add/:name', controller.user.add); // 增
router.del('/user/delete/:id', controller.user.delete); // 删
router.put('/user/change', controller.user.change); // 改
  1. app/controller/ 下创建 user.js
'use strict';

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

class UserController extends Controller {
  async list() {
    const ctx = this.ctx;
    const user = await ctx.service.user.searchAll();
    ctx.body = {
      csrf: ctx.csrf,
      user,
    };
  }

  async add() {
    const ctx = this.ctx;
    console.log(ctx.query);
    const userName = ctx.params.name;
    const isSuccess = await ctx.service.user.add(userName);
    ctx.body = isSuccess;
  }

  async delete() {
    const ctx = this.ctx;
    const userId = ctx.params.id;
    const isSuccess = await ctx.service.user.delete(userId);
    ctx.body = isSuccess;
  }

  async change() {
    const ctx = this.ctx;
    console.log(ctx.query);
    const params = ctx.query;
    const isSuccess = await ctx.service.user.change(params);
    ctx.body = isSuccess;
   }
}

module.exports = UserController;
  1. app/ 下创建 service 文件夹, 并在文件夹下创建 user.js
'use strict';

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

class UserList extends Service {
  async searchAll() {
    const users = await this.app.mysql.select('user');
    return { users };
  }
  async add(name) {
    const result = await this.app.mysql.insert('user', { name });
    const isSuccess = result.affectedRows === 1;
    return isSuccess;
  }
  async delete(id) {
    const result = await this.app.mysql.delete('user', { id });
    const isSuccess = result.affectedRows === 1;
    return isSuccess;
  }
  async change(params) {
   const isSuccess = await this.app.mysql.beginTransactionScope(async conn => {
      const result = await conn.update('user', params);
      const success = result.affectedRows === 1;
      if (success) {
        conn.insert('user', { name: 'tx-test' });
        throw new Error('rollback');
      }
      return success;
    }, this.ctx);
    return isSuccess;
  }
}

module.exports = UserList;

注:犹豫egg安全机制 csrf 的更新,可能你使用postman请求的post、put、delete 都为403;不多做解释我们先关闭安全机制

  1. 进入 /config/config.default.js 内添加
config.security = {
  csrf: {
    enable: false,
  },
};
上一篇下一篇

猜你喜欢

热点阅读