egg 项目实战(九)egg.js 开发文章首页和详情页接口


1.开发文章首页接口

app/service/article.js

const Service = require('egg').Service;
 
class ArticleService extends Service {
  async lists() {
    const { app } = this;
    try {
      const result = await app.mysql.select('article');
      return result;
    } catch(err) {
      console.log(err);
      return null;
    }
  }
}
 
module.exports = ArticleService;

app/controller/article.js

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

class ArticleController extends Controller {
  async lists() {
    const { ctx } = this;
    const result = await ctx.service.article.lists();
    if(result){
      ctx.body = {
        status: 200,
        data: result
      };
    }else{
      ctx.body = {
        status: 500,
        errMsg: '查询文章列表失败'
      };
    }
  }
}

module.exports = ArticleController;

app/router.js

router.get('/article/lists', controller.article.lists);

2.开发文章详情页接口

app/service/article.js

const Service = require('egg').Service;
 
class ArticleService extends Service {
  async detail(id) {
    if(!id){
      console.log('id必须传递');
      return null;
    }

    try {
      const result = await this.app.mysql.get('article', {id});
      return result;
    } catch(err) {
      console.log(err);
      return null;
    }
  }
}
 
module.exports = ArticleService;

app/controller/article.js

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

class ArticleController extends Controller {
  async detail() {
    const { ctx } = this;
    const result = await ctx.service.article.detail(ctx.params.id);
    if(result){
      ctx.body = {
        status: 200,
        data: result
      };
    }else{
      ctx.body = {
        status: 500,
        errMsg: '查询文章详情页失败'
      };
    }
  }
}

module.exports = ArticleController;

app/router.js

router.get('/article/detail/:id', controller.article.detail);

.

打赏

免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2021 CODEPRJ.COM