service代替controller操作数据库,使controller更加简洁
controller只需要接收前端的数据和返回响应的内容
定义service
在app目录中新建service目录再创建student.js
const Service = require('egg').Service;
class StudentService extends Service {
async getStudentList(){
try{
let studentList = await this.app.model.Student.findAll();
return studentList;
}catch(e){
return null;
}
}
}
module.exports = StudentService;
controller中student.js
不再关注数据库和业务逻辑,只关心响应的内容
const { Controller } = require('egg');
class studentController extends Controller {
async index() {
//调用service的student的getStudentList方法
let list = await this.ctx.service.student.getStudentList();
if(list){//如果list有对象,返回true
this.ctx.body = {
code:20000,
data:list,
}
}else{
this.ctx.body = {
code:50000,
msg:"服务器异常"
}
}
}
}
module.exports = studentController;
service能保持业务逻辑的独立性,体现在比如程序中还有些地方需要获取学生列表,直接调用service对应的方法如getStuentList
实现了方法的复用
再写个添加数据的业务
service
student.js
const Service = require('egg').Service;
class StudentService extends Service {
async getStudentList(){
try{
let studentList = await this.app.model.Student.findAll();
return studentList;
}catch(e){
return null;
}
}
async createStudent(name,score,clazz_id){//数据是前端通过controller传过来的
try{
await this.app.model.Student.create({
name:name,
score:score,
clazz_id:clazz_id
});
return true;//告诉controller已经成功了
}catch(e){
return false;
}
}
}
module.exports = StudentService;
controller
student.js
const { Controller } = require('egg');
class studentController extends Controller {
async index() {
//调用service的student的getStudentList方法
let list = await this.ctx.service.student.getStudentList();
if(list){//如果list有对象,返回true
this.ctx.body = {
code:20000,
data:list,
}
}else{
this.ctx.body = {
code:50000,
msg:"服务器异常"
}
}
}
async create(){
let name = this.ctx.request.body.name;
let score = this.ctx.request.body.score;
let clazz_id = this.ctx.request.body.clazz_id;
let result = await this.ctx.service.student.createStudent(name,score,clazz_id);
if(result){
this.ctx.body = {
code:20000,
msg:"添加成功"
}
}else{
this.ctx.body = {
code:50000,
msg:"添加失败"
}
}
}
}
module.exports = studentController;
标签:body,service,ctx,list,let,student
From: https://www.cnblogs.com/ben10044/p/17110788.html