返回

Egg.js 基础全面解析(中): 框架模式与环境配置详解

前端

在上一篇 Egg.js 基础全面解析(上) 中,我们介绍了 Egg.js 的架构、基本概念和路由使用。本篇文章将继续深入探讨 Egg.js 的框架模式、环境配置和数据模型,帮助你更全面地理解和掌握这个强大的 Node.js 框架。

框架模式

Egg.js 采用经典的 MVC(模型-视图-控制器)设计模式,将应用程序的逻辑和表示层分离,提高代码的可维护性和可扩展性。

模型 (Model): 负责数据操作,与数据库交互,提供数据持久化功能。
视图 (View): 负责呈现数据,生成 HTML、JSON 等格式的响应内容。
控制器 (Controller): 负责处理用户请求,调用模型获取数据,调用视图生成响应。

环境配置

Egg.js 支持多种环境配置,包括开发环境、测试环境和生产环境。这些环境配置影响着应用程序的行为和性能。

开发环境 (development):用于开发和调试,日志级别高,错误信息详细。
测试环境 (test):用于测试,日志级别低,错误信息简短。
生产环境 (production):用于部署,日志级别最低,错误信息最简短。

你可以通过设置 EGG_SERVER_ENV 环境变量来切换不同的环境。例如:

EGG_SERVER_ENV=production node app.js

数据模型

Egg.js 集成了 Sequelize ORM,提供了对关系型数据库的强大支持。你可以使用 Sequelize 定义数据模型,进行数据操作,包括增删改查和关联关系管理。

定义数据模型:

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

  return app.model.define('user', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    name: STRING(30),
  });
};

使用数据模型:

// app/controller/user.js
class UserController extends app.Controller {
  async index() {
    const users = await this.ctx.model.User.findAll();
    this.ctx.body = users;
  }
}

关联关系管理

Egg.js 支持数据模型之间的关联关系管理,包括一对一、一对多和多对多关联。你可以使用 Sequelize 的 belongsTohasManybelongsToMany 方法来定义关联关系。

一对一关联:

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

  return app.model.define('user', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    name: STRING(30),
    profileId: { type: INTEGER, unique: true, references: { model: 'profile', key: 'id' } },
  });
};

一对多关联:

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

  return app.model.define('post', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    title: STRING(100),
    userId: { type: INTEGER, references: { model: 'user', key: 'id' } },
  });
};

多对多关联:

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

  return app.model.define('user', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    name: STRING(30),
  }).belongsToMany(app.model.Role, { through: 'user_role' });
};

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

  return app.model.define('role', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    name: STRING(30),
  }).belongsToMany(app.model.User, { through: 'user_role' });
};

总结

在本文中,我们深入探讨了 Egg.js 的框架模式、环境配置和数据模型。通过理解这些基础概念,你可以更有效地构建和维护 Egg.js 应用程序。在下一篇 Egg.js 基础全面解析(下) 中,我们将介绍国际化、服务和插件,进一步提升你的 Egg.js 开发技能。