返回

Egg.js初体验——从天气预报开始的旅程

前端

Egg.js初体验

Egg.js是一个基于Koa开发的Node.js框架,非常适合企业级应用的开发。它倡导“约定优于配置”的理念,采用统一的开发方式来降低团队成员的学习成本。

安装Egg.js

安装Egg.js非常简单,可以使用以下命令:

npm install -g egg-init

安装完成后,就可以使用egg-init命令来创建一个新的Egg.js项目了。

egg-init my-app

创建天气预报应用

现在,让我们使用Egg.js来创建一个天气预报应用。首先,我们需要在项目中安装必要的依赖包。

npm install egg-sequelize egg-cors egg-validate egg-view-nunjucks

安装完成后,就可以在config/config.default.js文件中配置这些依赖包了。

// config/config.default.js
exports.sequelize = {
  dialect: 'mysql',
  host: '127.0.0.1',
  port: 3306,
  database: 'weather',
  username: 'root',
  password: '123456'
};

exports.cors = {
  origin: '*',
  allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};

exports.validate = {
  convert: true
};

exports.view = {
  defaultViewEngine: 'nunjucks'
};

接下来,我们需要创建数据库模型。在app/model目录下,创建一个weather.js文件。

// app/model/weather.js
module.exports = app => {
  const { INTEGER, DATE, STRING } = app.Sequelize;

  const Weather = app.model.define('weather', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    date: {
      type: DATE
    },
    city: {
      type: STRING(255)
    },
    temperature: {
      type: STRING(255)
    },
    weather: {
      type: STRING(255)
    }
  });

  return Weather;
};

现在,我们就可以使用Sequelize来操作数据库了。在app/controller/weather.js文件中,创建一个新的控制器。

// app/controller/weather.js
module.exports = app => {
  class WeatherController extends app.Controller {
    async index() {
      const { ctx } = this;
      const weathers = await ctx.model.Weather.findAll();
      ctx.body = weathers;
    }

    async create() {
      const { ctx } = this;
      const weather = await ctx.model.Weather.create(ctx.request.body);
      ctx.body = weather;
    }

    async update() {
      const { ctx } = this;
      const weather = await ctx.model.Weather.findById(ctx.params.id);
      await weather.update(ctx.request.body);
      ctx.body = weather;
    }

    async destroy() {
      const { ctx } = this;
      const weather = await ctx.model.Weather.findById(ctx.params.id);
      await weather.destroy();
      ctx.body = { success: true };
    }
  }

  return WeatherController;
};

最后,我们需要在app/router.js文件中配置路由。

// app/router.js
module.exports = app => {
  const { controller } = app;

  app.get('/weather', controller.weather.index);
  app.post('/weather', controller.weather.create);
  app.put('/weather/:id', controller.weather.update);
  app.delete('/weather/:id', controller.weather.destroy);
};

运行应用

现在,就可以运行应用了。使用以下命令启动应用:

npm start

然后,就可以访问http://localhost:7001/weather来查看天气预报了。

结语

在这篇文章中,我们展示了如何使用Egg.js来创建