代碼地址 https://github.com/MoceptWeb/egg-passport-portal
看之前確定至少了解了egg的文檔了丘薛, 不然看下面是浪費時間哈;本人只寫了重點需要注意的地方邦危!不對的地方請多多指教
npm包方式
如果代碼還不完善還不想發(fā)布洋侨,可以直接在項目文件中 npm link npm包目錄文件夾
package.json
name和eggPlugin字段
"name": "@node/egg-passport-jyb", // 包名
"eggPlugin": {
"name": "passportJyb" 這里是在egg中真正用到的name
},
項目中使用插件和配置
- {app_root}/app/config/plugin.js
config.passportJyb = {
'menu_code': 'loan_manage'
};
- {app_root}/app/config/config.{env}.js
exports.passportJyb = {
enable: true,
package: '@node/egg-passport-jyb'
};
npm中代碼
extend
個人建議extend中的方法盡量當前插件相關(guān)的加前綴舍扰, 防止互相干擾
- context.js
暴露方法給外部項目直接調(diào)用 - helper.js
統(tǒng)一封裝了內(nèi)部請求和mysql連接(多數(shù)據(jù)和單數(shù)據(jù)庫連接的區(qū)分),操作
async passportMysqlConnect() {
const portalConfig= this.app.config['passportJyb']
let mysqlConnect = null;
if(portalConfig.userDBClient) {
mysqlConnect = this.app.mysql.get(portalConfig.userDBClient)
} else {
mysqlConnect = this.app.mysql
}
if(!mysqlConnect) {
this.ctx.logger.error('數(shù)據(jù)庫連接數(shù)據(jù)');
}
return mysqlConnect;
}
service
則是一些數(shù)據(jù)相關(guān)的操作
middleware
- middleware位置
在app.js入口控制插件中的所有middleware執(zhí)行順序
當然可以加入配置項目希坚, 指定在哪個外部項目中的middleware之后边苹, 看各項目需求
module.exports = app => {
// 將 static 中間件放到 bodyParser 之前
const index = app.config.coreMiddleware.length;
// const index = app.config.coreMiddleware.indexOf('bodyParser');
// assert(index >= 0, 'bodyParser 中間件必須存在');
app.config.coreMiddleware.splice(index, 0, 'passportJybAuth');
};
config
- 配置noAuth正則url
在passportJybAuth中間件中 可以無需auth即可請求, 插件盡量可拓展 - 以及登錄后和單點(被動)登錄后的跳轉(zhuǎn)地址的配置