Egg.js官方快速入门案例更新

Egg.js官方快速入门案例更新

参考资料:

1.1 说明

本示例针对官方的快速入门项目进行了修改和完善,主要针对以下内容进行了修改。

  • 文档中的配置参数使用exports格式,但新版本的egg.js配置文件内容均为module.exports格式,同时增加了config变量,本文对项目中所有导出内容进行了修改与更新;
  • 原示例中的新闻栏目部署在firebase上,由于网络原因,在调试时可能无法访问,此外,由于该网站接口更新,快速入门教程无法正常访问新闻网站接口。因此,本项目使用一个json文件来模拟数据源,并修改了示例程序中的代码来更新访问。要运行数据源,需要全局安装json-servernpm install json-server -g,在data目录下运行以下命令以启用数据源,json-server --watch db.json
  • 可以直接clone项目并运行,也可以按照以下文档进行。

1.2 项目搭建

我们推荐直接使用脚手架,只需几条简单指令,即可快速生成项目(npm >=6.1.0),使用脚手架过程中,可能需要按提示输入项目名等内容。

mkdir egg-example && cd egg-example
npm init egg --type=simple
npm i

启动项目

npm run dev
#打开浏览器访问 http://localhost:7001

也可以按照以下步骤。

mkdir egg-example
cd egg-example
npm init
npm i egg --save
npm i egg-bin --save-dev

添加 npm scripts 到 package.json:

{
  "name": "egg-example",
  "scripts": {
    "dev": "egg-bin dev"
  }
}

1.3 编写Controller

如果你熟悉 Web 开发或 MVC,肯定猜到我们第一步需要编写的是 Controller 和 Router。

// app/controller/home.js
const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    this.ctx.body = 'Hello world';
  }
}

module.exports = HomeController;

在路由文件中配置路由映射:

// app/router.js
module.exports = (app) => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
};

在配置文件中修改配置文件,此处按照 module.exports格式进行了更新:

// config/config.default.js
  config.keys = appInfo.name + '_1648957490150_7277';

1.4 静态资源

Egg 内置了 static 插件,线上环境建议部署到 CDN,无需该插件。

static 插件默认映射 /public/* -> app/public/* 目录

此处,我们把静态资源都放到 app/public 目录即可:

app/public ├── css │ └── news.css

1.5 模板渲染

绝大多数情况,我们都需要读取数据后渲染模板,然后呈现给用户。故我们需要引入对应的模板引擎。

框架并不强制你使用某种模板引擎,只是约定了 View 插件开发规范,开发者可以引入不同的插件来实现差异化定制。

在本例中,我们使用 Nunjucks 来渲染,先安装对应的插件egg-view-nunjucks :

$ npm i egg-view-nunjucks --save

在插件文件中开启插件:

// config/plugin.js
module.exports = {
  // had enabled by egg
  // static: {
  //   enable: true,
  // }
  nunjucks:{
    enable: true,
    package: 'egg-view-nunjucks',
  }
};

在配置文件中修改配置,这里将原教程的模板后缀.tpl修改为nunjucks默认的.nj

// config/config.default.js

 config.view = {
    efaultViewEngine: 'nunjucks',
    mapping: {
      '.nj': 'nunjucks',
    },
  };

注意:是 config 目录,不是 app/config!

为列表页编写模板文件,放置在 app/view 目录下

<!-- app/view/news/list.nj -->
<html>
  <head>
    <title>Hacker News</title>
    <link rel="stylesheet" href="/public/css/news.css" />
  </head>
  <body>
    <ul class="news-view view">
      {% for item in list %}
      <li class="item">
        <a href="{{ item.url }}">{{ item.title }}</a>
      </li>
      {% endfor %}
    </ul>
  </body>
</html>

添加 Controller 和 Router

// app/controller/news.js
const Controller = require('egg').Controller;

class NewsController extends Controller {
  async list() {
    /*const dataList = {
      list: [
        { id: 1, title: 'this is news 1', url: '/news/1' },
        { id: 2, title: 'this is news 2', url: '/news/2' },
      ],
    };*/
    const ctx=this.ctx;
    const page=ctx.query.page||1;
    const newsList=await ctx.service.news.list(page);
    // await console.log(newsList);
    await ctx.render('news/list.nj',{list: newsList});
    // await this.ctx.render('news/list.nj', dataList);
  }
}

module.exports = NewsController;

在路径中添加以下路径

// app/router.js
module.exports = (app) => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/news', controller.news.list);
};

启动浏览器,访问 http://localhost:7001/news 即可看到渲染后的页面。

1.6 编写 service

在实际应用中,Controller 一般不会自己产出数据,也不会包含复杂的逻辑,复杂的过程应抽象为业务逻辑层 Service。我们来添加一个 Service 抓取 Hacker News 的数据 ,该部分内容使用data目录下的db.json文件内容进行替换,需要通过json-server启动服务。

// app/service/news.js
const Service = require('egg').Service;

class NewsService extends Service {
  async list(page = 1) {
    // read config
    const { serverUrl, pageSize } = this.config.news;

    // use build-in http client to GET hacker-news api
    const data = await this.ctx.curl(
      `${serverUrl}/topstories`,
      {
        // data: {
        //   orderBy: '"$key"',
        //   startAt: `"${pageSize * (page - 1)}"`,
        //   endAt: `"${pageSize * page - 1}"`,
        // },
        dataType: 'json',
      },
    );

    // await console.log('result is ' +JSON.stringify(data.data));

    // parallel GET detail
    const newsList = await Promise.all(
      // Object.keys(idList).map((key) => {
        // const url = `${serverUrl}/item/${idList[key]}.json`;
        // console.log('result is ' +JSON.stringify(data.data));
          data.data.map(element => {
          const url = `${serverUrl}/${element}`;
          return this.ctx.curl(url, { dataType: 'json' });
      }),
    );

    return newsList.map((res) => res.data);
  }
}

module.exports = NewsService;

框架提供了内置的 HttpClient 来方便开发者使用 HTTP 请求。

还需增加 app/service/news.js 中读取到的配置:

// config/config.default.js
// 添加 news 的配置项
 config.news={
    pageSize:5,
    serverUrl:'http://localhost:3000',
  };

1.7 编写扩展

遇到一个小问题,我们的资讯时间的数据是 UnixTime 格式的,我们希望显示为便于阅读的格式。框架提供了一种快速扩展的方式,只需在 app/extend 目录下提供扩展脚本即可,具体参见扩展。 在这里,我们可以使用 View 插件支持的 Helper 来实现:

$ npm i moment --save
// app/extend/helper.js
const moment = require('moment');
exports.relativeTime = (time) => moment(new Date(time * 1000)).fromNow();

在模板里面使用:

<!-- app/view/news/list.tpl -->
{{ helper.relativeTime(item.time) }}

1.8 编写 Middleware

假设有个需求:我们的新闻站点,禁止百度爬虫访问。聪明的同学们一定很快能想到可以通过 Middleware 判断 User-Agent,如下:

// app/middleware/robot.js
// options === app.config.robot
module.exports = (options, app) => {
  return async function robotMiddleware(ctx, next) {
    const source = ctx.get('user-agent') || '';
    const match = options.ua.some((ua) => ua.test(source));
    if (match) {
      ctx.status = 403;
      ctx.message = 'Go away, robot.';
    } else {
      await next();
    }
  };
};

// config/config.default.js
// add middleware robot
exports.middleware = ['robot'];
// robot's configurations
exports.robot = {
  ua: [/Baiduspider/i],
};

现在可以使用 curl http://localhost:7001/news -A “Baiduspider” 看看效果。或者使用vscode 的REST Client插件,利用data目录下的client.http文件进行调试。

1.8 配置文件

写业务的时候,不可避免的需要有配置文件,框架提供了强大的配置合并管理功能:支持按环境变量加载不同的配置文件,如 config.local.js, config.prod.js 等等。应用/插件/框架都可以配置自己的配置文件,框架将按顺序合并加载。具体合并逻辑可参见配置文件。

// config/config.default.js
exports.robot = {
  ua: [/curl/i, /Baiduspider/i],
};

// config/config.local.js
// only read at development mode, will override default
exports.robot = {
  ua: [/Baiduspider/i],
};

// app/service/some.js
const Service = require('egg').Service;

class SomeService extends Service {
  async list() {
    const rule = this.config.robot.ua;
  }
}

module.exports = SomeService;

1.9 单元测试

单元测试非常重要,框架也提供了 egg-bin 来帮开发者无痛的编写测试。测试文件应该放在项目根目录下的 test 目录下,并以 test.js 为后缀名,即 {app_root}/test/**/*.test.js。

// test/app/middleware/robot.test.js
const { app, mock, assert } = require('egg-mock/bootstrap');

describe('test/app/middleware/robot.test.js', () => {
  it('should block robot', () => {
    return app
      .httpRequest()
      .get('/')
      .set('User-Agent', 'Baiduspider')
      .expect(403);
  });
});

然后配置依赖和 npm scripts:

{
  "scripts": {
    "test": "egg-bin test",
    "cov": "egg-bin cov"
  }
}
$ npm i egg-mock --save-dev
执行测试:

$ npm test
作者
魏智勇(John)
加入讨论

此站点使用 Akismet 来减少垃圾评论。了解我们如何处理您的评论数据

魏智勇(John)

站长,80后,创业者,擅长工业自动化与信息化技术,熟悉各种PLC,组态软件,熟悉计算机技术,熟悉LabVIEW、C,C#,JavaScript程序设计技术。