实现连接数据库后的基本功能
- 在
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); // 改
- 在
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;
- 在
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;不多做解释我们先关闭安全机制
- 进入
/config/config.default.js
内添加
config.security = {
csrf: {
enable: false,
},
};