使用Egg.js重构项目:搭建基础设施

904 阅读1分钟

使用Egg.js重构项目:搭建基础设施

在本教程中,我们将使用Egg.js重构之前的项目,主要聚焦于项目基础设施的搭建。

创建项目

首先,我们需要创建一个新的Egg项目,并安装必要的插件。

创建Egg项目

cd egg-project
npm init egg --type=simple
# 选择simple,之后一路敲回车
npm install
# 安装mongo插件,egg-mongoose,egg中直接当成插件使用
npm i egg-mongoose --save

配置Mongo插件

在Egg.js中,插件、应用和中间件是有紧密联系的。参考官方文档了解更多信息。

配置plugin.js

config/plugin.js文件中启用egg-mongoose插件:

module.exports.mongoose = {
  enable: true,
  package: 'egg-mongoose'
}

配置config.default.js

config/config.default.js文件中配置MongoDB连接信息:

config.mongoose = {
  client: {
    url: 'mongodb://127.0.0.1/express-video',
    options: {},
    plugins: [],
  },
}

使用Mongoose

与Koa和Express略有不同,我们需要在Egg.js项目中新建模型文件。

创建User模型

app/model/user.js中定义用户模型:

module.exports = app => {
  const mongoose = app.mongoose
  const Schema = mongoose.Schema

  const userSchema = new Schema({
    userName: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true,
      select: false
    },
    phone: {
      type: String,
      required: true
    },
    image: {
      type: String,
      default: null
    },
    cover: {
      type: String,
      default: null
    },
    channelDes: {
      type: String,
      default: null
    },
    subscribeCount: {
      type: Number,
      default: 0
    },
    createdAt: { // 创建时间
      type: Date,
      default: Date.now
    },
    updatedAt: { // 更新时间
      type: Date,
      default: Date.now
    }
  })

  return mongoose.model('User', userSchema)
}

测试模型

最后,我们在控制器中测试User模型,确保可以正常查询数据。

创建控制器

controller/home.js中创建一个控制器方法来查询所有用户数据:

const { Controller } = require('egg');

class HomeController extends Controller {
  async index() {
    this.ctx.body = await this.app.model.User.find()
  }
}

module.exports = HomeController;

测试请求

启动项目并在浏览器中发送请求,可以看到所有用户数据。