前言
接上文 Egg框架搭建后台服务【1】,继续优化后台服务,之前直接用 SQL 语句调用的数据库数据,既不安全,也比较麻烦,当然最重要的是“显着不专业”。
所以本文仍然是增删改查,重点是将原本 SQL 语句操作改为 ORM 框架 sequelize 操作。
开发
初始化
安装
安装 sequelize 框架及 mysql2 库(我这里用的是MySQL,所以安装 mysql2库,如果使用的是其他数据库参考 官方文档 安装相应连接器库。)
npm install --save egg-sequelize mysql2
配置
在 config/plugin.js 中引入egg-sequelize 插件。
module.exports = {sequelize: {enable: true,package: 'egg-sequelize'},
};
在 config/config.default.js 中编写配置
/* eslint valid-jsdoc: "off" *//*** @param {Egg.EggAppInfo} appInfo app info*/
module.exports = appInfo => {/*** built-in config* @type {Egg.EggAppConfig}**/const config = exports = {};// use for cookie sign key, should change to your own and keep securityconfig.keys = appInfo.name + '123';// add your middleware config hereconfig.middleware = [];// 关闭安全配置config.security = {csrf: {enable: false,}};// 添加sequelize配置config.sequelize = {dialect: 'mysql',host: '127.0.0.1',port: 3306,database: 'egg-blogs',username: 'root',password: '12345678'}// add your user config hereconst userConfig = {// myAppName: 'egg',};return {...config,...userConfig,};
};
开发逻辑
Model
创建 app/model/Tag.js
module.exports = (app) => {const {STRING} = app.Sequelize;const Tag = app.model.define('tag', {id: {type: STRING, primaryKey: true, autoIncrement: true},tag_name: STRING,tag_color: STRING,remark: STRING,}, {timestamps: true,createdAt: 'create_time',updatedAt: 'update_time',tableName: 'tag'});return Tag;
}
注意:这里一定要指定主键,配置部分如果数据库中表明为 tags,可以不指定 tableName, sequelize 会自动推定表名。表字段如果不具备 createAt、updateAt,可以设置为 false 去除,也可以映射为其他字段。
Service
修改原本的 app/service/tag.js
const {Service} = require('egg');class TagsService extends Service {async getTagList(params) {const {ctx, app} = this;const {Op} = app.Sequelize;const query = {where: {tag_name: {[Op.like]: `%${params.tagName || ''}%`}}}const tagList = await ctx.model.Tag.findAll(query);ctx.status = 200;ctx.body = {code: 200,success: true,data: tagList,msg: '获取标签列表成功',show: false}}async createTag(params) {const {ctx, app} = this;const tagInfo = {id: ctx.helper.snowflakeId(),tagName: params.tagName,tagColor: params.tagColor,remark: params.remark}const result = await app.model.Tag.create(tagInfo)ctx.status = 200;ctx.body = {code: 200,success: true,data: result,msg: '创建标签成功',show: true}}async updateTag(params) {const {ctx, app} = this;const tagInfo = {tagName: params.tagName,tagColor: params.tagColor,remark: params.remark}const result = await ctx.model.Tag.update(tagInfo, {where: {id: params.id}});ctx.status = 200;ctx.body = {code: 200,success: true,data: result,msg: '更新标签成功',show: true}}async deleteTag(params) {const {ctx, app} = this;const ids = params.ids.split(',');await ctx.model.Tag.destroy({where: {id: ids}});ctx.status = 200;ctx.body = {code: 200,success: true,msg: '删除标签成功',show: true}}
}module.exports = TagsService;
注意:这里因为是初学,仅实现就收手了,还有可优化的地方。
总结
相较于 MySQL 直连操作数据库的方案,ORM 的方案无疑更加安全,也更加专业。后端在实现数据库操作的时候基本上都使用的 ORM 框架,这种实现方式在多人开发的时候不至于 SQL 语句写的满天飞。
问题:
- sequelize 框架具体逻辑并不太清楚,很多地方仍存在优化空间,尤其是错误处理。
- 数据库字段和前后端数据对接方面问题仍然不清楚,有些字段使用 tagName 的小驼峰方式仍可以走通,但是有些地方必须和数据库一致,写 tag_name。
- 数据库配置项数据应该是动态的,独立于项目外的,实现配置化,此处仍不太清楚。