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);

.

原文地址:https://www.cnblogs.com/crazycode2/p/12422413.html