Web应用开发框架-egg进阶与实战(二)02——环境配置与数据库初始化、编写schema、service逻辑提取
正式开始
安装依赖
npm init egg type-simple
npm install egg-mongoose --save
开发顺序
- 安装环境,配置数据库插件
- 编写schema,设计存储的字段
- 进行路由设计, 通过控制器添加数据
- 错误处理
- 返回值
- 校验参数
- 数据库的查询
- 查询全部数据
- 查询单个数据
- 数据库的删除
- 数据库的更新
- service提取
配置
// config/plugin.js
mongoose: {
enable: true,
package: 'egg-mongoose',
},
// config/config.default.js
config.mongoose = {
url: 'mongodb://127.0.0.1/example',
options: {},
}
路由配置
- 解析用户请求,给相应的controller
- 通过resources 直接创建restFul api
// app/router.js
module.exports = app => {
const { router, controller } = app;
router.resources('posts', '/api/posts',controller.posts);
};
控制器
- 解析request参数
- 校验参数
- 调用service
- 返回结果
'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
- 对controller的一种抽象
- 抽取通用逻辑
// 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
- 对数据模型的描述和创建
// {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
- 具体操作数据库的逻辑
- 进行增删改查,并暴露方法给控制器调用
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;
未来展望
增删改查只是服务端的冰山一角,希望同学们能持续的学习。
- 登录,鉴权,用户
- 服务部署
- 监控预警,日志分析系统
- 数据库优化
- 多进程,分布式集群
- 大数据处理,分析