egg+sequelize+mysql实现CRUD操作

开发环境

  • node v10.16.3
  • mysql v8.0.18 

第一步:确保能够跑起来

  • mkdir egg-test && cd egg-test
  • npm init egg --type=simple
  • npm install
  • npm run dev
  • 结果

    image.png

第二步:完成CRUD功能

  • mysql准备
    • mysql用户名,密码和数据库名
      • user:root
      • password:123456
      • database:test
    • test->user表结构
      •  

         

  • 安装依赖包
    • npm install --save egg-sequelize mysql2
  • 目录结构

      image.png 

  • config/plugin.js

 

'use strict';

/** @type Egg.EggPlugin */
module.exports = {
  sequelize: {
    enable: true,
    package: 'egg-sequelize',
  },
};

 

  • config/config.default.js:数据库的配置

 

/* eslint valid-jsdoc: "off" */

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1576133935920_4183';

  // add your middleware config here
  config.middleware = [];
  config.security = {
    csrf: false,
    ctoken: false,
  };
  config.sequelize = {
    dialect: 'mysql',
    host: '127.0.0.1',
    port: '3306',
    user: 'root',//用户名
    password: '123456',//用户密码
    database: 'test',//数据库名
    define: {
      underscored: true,
      freezeTableName: true,
    },
  };
  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  return {
    ...config,
    ...userConfig,
  };
}; 

 

  • model/user.js

 

'use strict';
module.exports = app => {
  const { STRING, INTEGER } = app.Sequelize;
  const User = app.model.define('user', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    nickname: STRING(20),
  }, {
    timestamps: false,
  });
  return User;
};

 

  • controller/user.js

 

'use strict';

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

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}
class UserController extends Controller {
  async index() {
    const { ctx } = this;
    const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };
    ctx.body = await ctx.model.User.findAll(query);
  }
  async show() {
    const { ctx } = this;
    ctx.body = await ctx.model.User.findByPk(toInt(ctx.params.id));
  }
  async create() {
    const { ctx } = this;
    const { nickname } = ctx.request.body;
    const user = await ctx.model.User.create({ nickname });
    ctx.status = 201;
    ctx.body = user;
  }
  async update() {
    const { ctx } = this;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.User.findByPk(id);
    if (!user) {
      ctx.status = 404;
      return;
    }
    const { nickname } = ctx.request.body;
    await user.update({ nickname });
    ctx.body = user;
  }
  async destroy() {
    const { ctx } = this;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.User.findByPk(id);
    if (!user) {
      ctx.status = 404;
      return;
    }
    await user.destroy();
    ctx.status = 200;
  }
}
module.exports = UserController;

 

  • router.js

 

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.resources('user', '/user', controller.user);
};

 

postman测试

 

  • 查询所有用户
    • image.png
  • 根据id查找
    • image.png
  • 新增
    • image.png
  • 修改
    • image.png
  • 删除
    • image.png

参考

    • image.png
posted @ 2019-12-12 17:00  mingL  阅读(2875)  评论(0编辑  收藏  举报