app/service创建student.js文件放在controller和mysql之间
const Service = require("egg").Service;
class StudentService extends Service {
async getstudentlist() {
try {
let clazzlist = await this.app.model.Clazz.findAll();
this.ctx.body = clazzlist;
return clazzlist;
} catch (e) {
return null;
}
}
async creatstudent(name) {
try {
await this.app.model.Clazz.create({
name: name
})
return true;
} catch (e) { return false }
}
}
module.exports = StudentService;
此时controller里的index可简化为
async index() {
let list = this.ctx.service.student.getstudentlist();
if (list) {
this.ctx.body = { code: 2000, data = list }
} else { this.ctx.body = { code: 5000, msg: "服务器异常" } }
}
create可简化为
async create() {
let name = this.ctx.request.body.name;
let result = await this.ctx.service.student.createstudent(name);
if (result) {
this.ctx.body = {
code: 2000,
msg: "添加成功"
}
} else { this.ctx.boy = {
code: 5000,
msg: "添加失败" }
}
}