Egg日常开发所需插件
Mercer-Lee的空间 2019-10-27
Egg
JS
Node
在日常的开发中,我们需要一些常用的第三方库来促进我们的开发体验 😏,Egg 提供了很多插件供我们下载安装使用,这里我们来安利一波插件。
# egg-console
在日常开发中我们需要在终端查看请求的一些信息来更好的辅助我们开发,比如egg-console的效果如下:
安装和配置:
$ npm install egg-console
// config/config.default.js
"use strict";
module.exports = appInfo => {
const config = exports = {};
config.console = {
// local 环境下默认值均为 true,prod 环境下均为 false
debug: false,
error: true
}
}
// config/plugin.js
'use strict';
exports.console = {
enable: true,
package: 'egg-console',
}
# egg-bcrypt
这个是基本都会用到的加密库,比如用户的密码加密,具体使用看文档 (opens new window)
$ npm install egg-bcrypt
// config/config.default.js
"use strict";
module.exports = appInfo => {
const config = exports = {};
config.bcrypt = {
saltRounds: 10
}
}
// config/plugin.js
'use strict';
exports.bcrypt = {
enable: true,
package: 'egg-bcrypt'
}
# egg-validate
$ npm install egg-validate
// config/plugin.js
'use strict';
exports.validate = {
enable: true,
package: 'egg-validate',
}
这个在注册用户的controller那里用过,看代码就能看出用法:
'use strict';
const Controller = require('egg').Controller;
class UserController extends Controller {
constructor(ctx) {
super(ctx)
this.userValidate = {
email: { type: 'email' },
password: { tpe: 'password', required: true, min: 5 },
username: { type: 'string', required: true, min: 3 }
}
}
/**
* @description 注册
*/
async register() {
const { ctx, service } = this;
ctx.validate(this.userValidate, ctx.request.body);
const { username, password, email } = ctx.request.body;
password = ctx.genHash(password);
const user = await service.user.getUser({ '$or': [{ username }, { email }] });
if (!user) {
await service.user.addUser({
username,
password,
email
});
ctx.helper.success({ ctx })
} else {
ctx.throw(422, '用户已经存在')
}
}
}
# egg-cors
配置跨域的第三方包:
$ npm install egg-cors
// config/config.default.js
"use strict";
module.exports = appInfo => {
const config = exports = {};
config.security = {
csrf: {
enable: false,
},
domainWhiteList: ['*'],
}
}
'use strict'
exports.cors = {
enable: true,
package: 'egg-cors',
}