Web应用开发框架-egg进阶与实战(二)02——环境配置与数据库初始化、编写schema、service逻辑提取

Web应用开发框架-egg进阶与实战(二)02——环境配置与数据库初始化、编写schema、service逻辑提取

正式开始
安装依赖

npm init egg type-simple

npm install egg-mongoose --save

开发顺序
  1. 安装环境,配置数据库插件
  2. 编写schema,设计存储的字段
  3. 进行路由设计, 通过控制器添加数据
    1. 错误处理
    2. 返回值
    3. 校验参数
  4. 数据库的查询
    1. 查询全部数据
    2. 查询单个数据
  5. 数据库的删除
  6. 数据库的更新
  7. service提取
配置
// config/plugin.js
mongoose: {
    enable: true,
    package: 'egg-mongoose',
},
// config/config.default.js
config.mongoose = {
  url: 'mongodb://127.0.0.1/example',
  options: {},
}
路由配置
  1. 解析用户请求,给相应的controller
  2. 通过resources 直接创建restFul api
// app/router.js
module.exports = app => {
  const { router, controller } = app;
  router.resources('posts', '/api/posts',controller.posts);
};
控制器
  1. 解析request参数
  2. 校验参数
  3. 调用service
  4. 返回结果
'use strict';

// const Controller = require('egg').Controller;

const httpController = require('./base/http');
// GET /posts -> app.controller.posts.index
// GET /posts/new -> app.controller.posts.new
// GET /posts/:id -> app.controller.posts.show
// GET /posts/:id/edit -> app.controller.posts.edit
// POST /posts -> app.controller.posts.create
// PUT /posts/:id -> app.controller.posts.update
// DELETE /posts/:id -> app.controller.posts.destroy

const createRule = {  // 参数校验
  title: { type: 'string' },
  content: { type: 'string' },
}

const updateRule = {
  title: { type: 'string', required: false },
  content: { type: 'string', required: false },
}

class PostsController extends httpController {
  async create() { // 创建文章
    const { ctx } = this;

    const requestBody = ctx.request.body;

    try {
      this.ctx.validate(createRule);
      const res = await ctx.service.posts.create(requestBody);
      this.success(res);
    } catch (err) {
      // console.log('=======', err)
      this.fail(err)
    }
  }

  async index() {// 读取所有文章
    const { ctx } = this;
    ctx.body = await ctx.service.posts.find({});
  }

  async show() {
    const { ctx } = this;

    try {
      const params_id = ctx.params.id;
      const res = await ctx.service.posts.find({
        _id: params_id
      });
      this.success(res);
    } catch (err) {
      this.fail(err);
    }
  }

  async update() {  // 更新文章
    const { ctx } = this;
    // console.log('================', ctx.request.body)
    try {
      const params_id = ctx.params.id;
      const requestBody = ctx.request.body;
      ctx.validate(updateRule);

      const res = await ctx.service.posts.update({
        _id: params_id,
      }, {
          $set: {
            ...requestBody
          }
        });
      this.success(res);
    } catch (err) {
      this.fail(err);
    }
  }

  async destroy() { // 删除文章

    const { ctx } = this;

    // console.log('------------', ctx.model);
    try {
      const params_id = ctx.params.id;
      const res = await ctx.service.posts.remove({
        _id: params_id
      });
      this.success(res);
    } catch (err) {
      this.fail(err);
    }
  }
}

module.exports = PostsController;

base controller
  1. 对controller的一种抽象
  2. 抽取通用逻辑
// controller/base/http.js
'use strict';

const Controller = require('egg').Controller;

class HttpController extends Controller {
    success(data) {
        // msg 和 code这样的2个字段 在所有的请求里面都需要返回。
        // 好好理解oop
        this.ctx.body = {
            msg: data && data.msg || 'success',
            code: 0,
            data
        }
    }

    fail(data) {
        this.logger.error(data)
        this.ctx.body = {
            msg: data && data.msg || 'fail',
            code: data && data.code || 1,
            data
        }
    }
}

module.exports = HttpController;

model
  1. 对数据模型的描述和创建
// {app_root}/app/model/user.js
module.exports = app => {
    const mongoose = app.mongoose;
    const Schema = mongoose.Schema;
    const postsSchema = new Schema({
        title: { type: String, unique: true },
        content: { type: String },
    });
    return mongoose.model('Posts', postsSchema);
}

service
  1. 具体操作数据库的逻辑
  2. 进行增删改查,并暴露方法给控制器调用
const Service = require('egg').Service;

class PostsService extends Service {
    async find(data) {  // 查
        const res = await this.ctx.model.Posts.find(data);
        return res
    }

    async update(findData, updateData) { // 改
        const res = await this.ctx.model.Posts.update(findData, updateData);
        return res;
    }

    async remove(data) {  // 删除
        const res = await this.ctx.model.Posts.remove(data);
        return res;
    }

    async create(data) {  // 增
        // console.log(this.ctx.model)
        const postsInstance = new this.ctx.model.Posts({
            title: data.title,
            content: data.content
        });

        const res = await postsInstance.save();
        return res;
    }
}

module.exports = PostsService;

未来展望

增删改查只是服务端的冰山一角,希望同学们能持续的学习。

  • 登录,鉴权,用户
  • 服务部署
  • 监控预警,日志分析系统
  • 数据库优化
  • 多进程,分布式集群
  • 大数据处理,分析
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值