近来公司须要构建一套 EMM(Enterprise Mobility Management)的管理平台,就这种面向企业的应用管理自己须要考虑的需求是十分复杂的,技术层面管理端和服务端构建是架构核心,客户端自己初期倒不须要那么复杂,做为移动端的负责人(其实也就是一个打杂的小组长),这个平台架构我天然是免不了去参与的,做为一个前端 jser 来公司这边老是接到这种不太像前端的工做,要是之前我可能会有些抵触这种业务层面须要考虑的不少,技术实现自己又不太容易积累技术成长的活。这一年我成长了太多,老是尝试着去作一些可能本身谈不上喜欢但仍是有意义的事情,因此此次接手这个任务仍是想好好把这个事情作好,因此想考虑参与到 EMM 服务端构建。其实话又说回来,任何事只要想去把它作好,怎么会存在有意义仍是没意义的区别呢?html
考虑到基于 Node.js 构建的服务目前愈来愈流行,也方便后续放在平台容器云上构建微服务,另外做为一个前端 jser 出身的程序员,使用 Node.js 来构建服务格外熟悉。以前学习过一段时间 Egg.js,此次绝不犹豫的选择了基于 Egg.js 框架来搭建。前端
去年在 gitchat JavaScript 进阶之 Vue.js + Node.js 入门实战开发 中安利过 Egg.js,那个时候是初接触 Egg.js,可是仍是被它惊艳到了,Egg 继承于 Koa,奉行『约定优于配置』,按照一套统一的约定进行应用开发,插件机制也比较完善。虽说 Egg 继承于 Koa,你们可能以为彻底能够本身基于 Koa 去实现一套,不必基于这个框架去搞,可是其实本身去设计一套这样的框架,最终也是须要去借鉴各家所长,时间成本上短时间是划不来的。Koa 是一个小而精的框架,而 Egg 正如文档说的为企业级框架和应用而生,对于咱们快速搭建一个完备的企业级应用仍是很方便的。Egg 功能已经比较完善,另外若是没有实现的功能,本身根据 Koa 社区提供的插件封装一下也是不难的。node
在数据库选择上本次项目考虑使用 MySQL,而不是 MongoDB,开始使用的是 egg-mysql 插件,写了一部分后发现 service 里面写了太多东西,表字段修改会影响太多代码,在设计上缺少对 Model 的管理,看到资料说能够引入 ORM 框架,好比 sequelize,而 Egg 官方刚好提供了 egg-sequelize 插件。mysql
首先了解一下什么是 ORM ?git
对象关系映射(英语:Object Relational Mapping,简称 ORM,或 O/RM,或 O/R mapping),是一种程序设计技术,用于实现面向对象编程语言里不一样类型系统的数据之间的转换。从效果上说,它实际上是建立了一个可在编程语言里使用的“虚拟对象数据库”。程序员
相似于 J2EE 中的 DAO 设计模式,将程序中的数据对象自动地转化为关系型数据库中对应的表和列,数据对象间的引用也能够经过这个工具转化为表。这样就能够很好的解决我遇到的那个问题,对于表结构修改和数据对象操做是两个独立的部分,从而使得代码更好维护。实际上是否选择 ORM 框架,和之前前端是选择模板引擎仍是手动拼字符串同样,ORM 框架避免了在开发的时候手动拼接 SQL 语句,能够防止 SQL 注入,另外也将数据库和数据 CRUD 解耦,更换数据库也相对更容易。github
sequelize 是 Node.js 社区比较流行的一个 ORM 框架,相关文档:web
安装:算法
$ npm install --save sequelize
创建链接:sql
const Sequelize = require("sequelize"); // 完整用法 const sequelize = new Sequelize("database", "username", "password", { host: "localhost", dialect: "mysql" | "sqlite" | "postgres" | "mssql", operatorsAliases: false, pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, // SQLite only storage: "path/to/database.sqlite" }); // 简单用法 const sequelize = new Sequelize("postgres://user:pass@example.com:5432/dbname");
校验链接是否正确:
sequelize
.authenticate() .then(() => { console.log("Connection has been established successfully."); }) .catch(err => { console.error("Unable to connect to the database:", err); });
定义 Model :
定义一个 Model 的基本语法:
sequelize.define("name", { attributes }, { options });
例如:
const User = sequelize.define("user", { username: { type: Sequelize.STRING }, password: { type: Sequelize.STRING } });
对于一个 Model 字段类型设计,主要考虑如下几个方面:
Sequelize 默认会添加 createdAt 和 updatedAt,这样能够很方便的知道数据建立和更新的时间。若是不想使用能够经过设置 attributes 的 timestamps: false;
Sequelize 支持丰富的数据类型,例如:STRING、CHAR、TEXT、INTEGER、FLOAT、DOUBLE、BOOLEAN、DATE、UUID 、JSON 等多种不一样的数据类型,具体能够看文档:DataTypes。
Getters & setters 支持,当咱们须要对字段进行处理的时候十分有用,例如:对字段值大小写转换处理。
const Employee = sequelize.define("employee", { name: { type: Sequelize.STRING, allowNull: false, get() { const title = this.getDataValue("title"); return this.getDataValue("name") + " (" + title + ")"; } }, title: { type: Sequelize.STRING, allowNull: false, set(val) { this.setDataValue("title", val.toUpperCase()); } } });
字段校验有两种类型:非空校验及类型校验,Sequelize 中非空校验经过字段的 allowNull 属性断定,类型校验是经过 validate 进行断定,底层是经过 validator.js 实现的。若是模型的特定字段设置为容许 null(allowNull:true),而且该值已设置为 null,则 validate 属性不生效。例如,有一个字符串字段,allowNull 设置为 true,validate 验证其长度至少为 5 个字符,但也容许为空。
const ValidateMe = sequelize.define("foo", { foo: { type: Sequelize.STRING, validate: { is: ["^[a-z]+$", "i"], // will only allow letters is: /^[a-z]+$/i, // same as the previous example using real RegExp not: ["[a-z]", "i"], // will not allow letters isEmail: true, // checks for email format (foo@bar.com) isUrl: true, // checks for url format (http://foo.com) isIP: true, // checks for IPv4 (129.89.23.1) or IPv6 format isIPv4: true, // checks for IPv4 (129.89.23.1) isIPv6: true, // checks for IPv6 format isAlpha: true, // will only allow letters isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail isNumeric: true, // will only allow numbers isInt: true, // checks for valid integers isFloat: true, // checks for valid floating point numbers isDecimal: true, // checks for any numbers isLowercase: true, // checks for lowercase isUppercase: true, // checks for uppercase notNull: true, // won't allow null isNull: true, // only allows null notEmpty: true, // don't allow empty strings equals: "specific value", // only allow a specific value contains: "foo", // force specific substrings notIn: [["foo", "bar"]], // check the value is not one of these isIn: [["foo", "bar"]], // check the value is one of these notContains: "bar", // don't allow specific substrings len: [2, 10], // only allow values with length between 2 and 10 isUUID: 4, // only allow uuids isDate: true, // only allow date strings isAfter: "2011-11-05", // only allow date strings after a specific date isBefore: "2011-11-05", // only allow date strings before a specific date max: 23, // only allow values <= 23 min: 23, // only allow values >= 23 isCreditCard: true, // check for valid credit card numbers // custom validations are also possible: isEven(value) { if (parseInt(value) % 2 != 0) { throw new Error("Only even values are allowed!"); // we also are in the model's context here, so this.otherField // would get the value of otherField if it existed } } } } });
最后咱们说明一个最重要的字段主键 id 的设计, 须要经过字段 primaryKey: true
指定为主键。MySQL 里面主键设计主要有两种方式:自动递增;UUID。
自动递增设置 autoIncrement: true
便可,对于通常的小型系统这种方式是最方便,查询效率最高的,可是这种不利于分布式集群部署,这种基本用过 MySQL 里面应用都用过,这里不作深刻讨论。
UUID, 又名全球独立标识(Globally Unique Identifier),UUID 是 128 位(长度固定)unsigned integer, 可以保证在空间(Space)与时间(Time)上的惟一性。并且无需注册机制保证, 能够按需随时生成。据 WIKI, 随机算法生成的 UUID 的重复几率为 170 亿分之一。Sequelize 数据类型中有 UUID,UUID1,UUID4 三种类型,基于node-uuid 遵循 RFC4122。例如:
const User = sequelize.define("user", { id: { type: Sequelize.UUID, primaryKey: true, allowNull: false, defaultValue: Sequelize.UUID1 } });
这样 id 默认值生成一个 uuid 字符串,例如:'1c572360-faca-11e7-83ee-9d836d45ff41',不少时候咱们不太想要这个 -
字符,咱们能够经过设置 defaultValue 实现,例如:
const uuidv1 = require("uuid/v1"); const User = sequelize.define("user", { id: { type: Sequelize.UUID, primaryKey: true, allowNull: false, defaultValue: function() { return uuidv1().replace(/-/g, ""); } } });
使用 Model 对象:
对于 Model 对象操做,Sequelize 提供了一系列的方法:
经过上述提供的一系列方法能够实现数据的增删改查(CRUD),例如:
User.create({ username: "fnord", job: "omnomnom" }) .then(() => User.findOrCreate({ where: { username: "fnord" }, defaults: { job: "something else" } }) ) .spread((user, created) => { console.log( user.get({ plain: true }) ); console.log(created); /* In this example, findOrCreate returns an array like this: [ { username: 'fnord', job: 'omnomnom', id: 2, createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET), updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET) }, false ] */ });
文档:egg-sequelize:https://github.com/eggjs/egg-sequelize
这里咱们暂时先不分析 egg 插件规范,暂时先只看看 egg-sequelize/lib/loader.js 里面的实现:
"use strict"; const path = require("path"); const Sequelize = require("sequelize"); const MODELS = Symbol("loadedModels"); const chalk = require("chalk"); Sequelize.prototype.log = function() { if (this.options.logging === false) { return; } const args = Array.prototype.slice.call(arguments); const sql = args[0].replace(/Executed \(.+?\):\s{0,1}/, ""); this.options.logging.info("[model]", chalk.magenta(sql), `(${args[1]}ms)`); }; module.exports = app => { const defaultConfig = { logging: app.logger, host: "localhost", port: 3306, username: "root", benchmark: true, define: { freezeTableName: false, underscored: true } }; const config = Object.assign(defaultConfig, app.config.sequelize); app.Sequelize = Sequelize; const sequelize = new Sequelize( config.database, config.username, config.password, config ); // app.sequelize Object.defineProperty(app, "model", { value: sequelize, writable: false, configurable: false }); loadModel(app); app.beforeStart(function*() { yield app.model.authenticate(); }); }; function loadModel(app) { const modelDir = path.join(app.baseDir, "app/model"); app.loader.loadToApp(modelDir, MODELS, { inject: app, caseStyle: "upper", ignore: "index.js" }); for (const name of Object.keys(app[MODELS]