@charming_dans/elpis 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/.eslintignore +3 -0
  2. package/.eslintrc +55 -0
  3. package/README.md +294 -2
  4. package/app/controller/base.js +39 -0
  5. package/app/controller/project.js +77 -0
  6. package/app/controller/view.js +19 -0
  7. package/app/extend/database.js +5 -0
  8. package/app/extend/logger.js +38 -0
  9. package/app/middleware/api-params-verify.js +75 -0
  10. package/app/middleware/api-sign-verify.js +38 -0
  11. package/app/middleware/error-handler.js +34 -0
  12. package/app/middleware/project-handler.js +28 -0
  13. package/app/middleware.js +38 -0
  14. package/app/pages/asserts/custom.css +12 -0
  15. package/app/pages/boot.js +49 -0
  16. package/app/pages/common/curl.js +85 -0
  17. package/app/pages/common/utils.js +3 -0
  18. package/app/pages/dashboard/complex-view/header-view/complex-view/sub-menu/sub-menu.vue +20 -0
  19. package/app/pages/dashboard/complex-view/header-view/header-view.vue +118 -0
  20. package/app/pages/dashboard/complex-view/iframe-view/iframe-view.vue +44 -0
  21. package/app/pages/dashboard/complex-view/schema-view/complex-view/search-panel/search-panel.vue +39 -0
  22. package/app/pages/dashboard/complex-view/schema-view/complex-view/table-panel/table-panel.vue +130 -0
  23. package/app/pages/dashboard/complex-view/schema-view/components/component-config.js +23 -0
  24. package/app/pages/dashboard/complex-view/schema-view/components/create-form/create-form.vue +99 -0
  25. package/app/pages/dashboard/complex-view/schema-view/components/detail-panel/detail-panel.vue +113 -0
  26. package/app/pages/dashboard/complex-view/schema-view/components/edit-form/edit-form.vue +129 -0
  27. package/app/pages/dashboard/complex-view/schema-view/hook/schema.js +128 -0
  28. package/app/pages/dashboard/complex-view/schema-view/schema-view.vue +98 -0
  29. package/app/pages/dashboard/complex-view/sider-view/complex-view/sub-menu/sub-menu.vue +25 -0
  30. package/app/pages/dashboard/complex-view/sider-view/sider-view.vue +120 -0
  31. package/app/pages/dashboard/dashboard.vue +98 -0
  32. package/app/pages/dashboard/entry.dashboard.js +42 -0
  33. package/app/pages/store/index.js +3 -0
  34. package/app/pages/store/menu.js +61 -0
  35. package/app/pages/store/project.js +17 -0
  36. package/app/pages/widgets/header-container/asserts/logo.png +0 -0
  37. package/app/pages/widgets/header-container/header-container.vue +81 -0
  38. package/app/pages/widgets/schema-form/complex-view/input/input.vue +139 -0
  39. package/app/pages/widgets/schema-form/complex-view/input-number/input-number.vue +138 -0
  40. package/app/pages/widgets/schema-form/complex-view/select/select.vue +116 -0
  41. package/app/pages/widgets/schema-form/form-item-config.js +23 -0
  42. package/app/pages/widgets/schema-form/schema-form.vue +131 -0
  43. package/app/pages/widgets/schema-search-bar/complex-view/date-range/date-range.vue +47 -0
  44. package/app/pages/widgets/schema-search-bar/complex-view/dynamic-select/dynamic-select.vue +63 -0
  45. package/app/pages/widgets/schema-search-bar/complex-view/input/input.vue +41 -0
  46. package/app/pages/widgets/schema-search-bar/complex-view/select/select.vue +48 -0
  47. package/app/pages/widgets/schema-search-bar/schema-search-bar.vue +130 -0
  48. package/app/pages/widgets/schema-search-bar/search-item-config.js +27 -0
  49. package/app/pages/widgets/schema-table/schema-table.vue +237 -0
  50. package/app/pages/widgets/sider-container/sider-container.vue +30 -0
  51. package/app/public/static/logo.png +0 -0
  52. package/app/public/static/normalize.css +239 -0
  53. package/app/router/project.js +6 -0
  54. package/app/router/view.js +8 -0
  55. package/app/router-schema/project.js +30 -0
  56. package/app/service/base.js +12 -0
  57. package/app/service/project.js +47 -0
  58. package/app/view/entry.tpl +25 -0
  59. package/app/webpack/config/webpack.base.js +210 -0
  60. package/app/webpack/config/webpack.dev.js +58 -0
  61. package/app/webpack/config/webpack.prod.js +113 -0
  62. package/app/webpack/dev.js +56 -0
  63. package/app/webpack/libs/blank.js +1 -0
  64. package/app/webpack/prod.js +21 -0
  65. package/config/config.default.js +3 -0
  66. package/elpis-core/env.js +23 -0
  67. package/elpis-core/index.js +95 -0
  68. package/elpis-core/loader/config.js +50 -0
  69. package/elpis-core/loader/controller.js +66 -0
  70. package/elpis-core/loader/extend.js +56 -0
  71. package/elpis-core/loader/middleware.js +65 -0
  72. package/elpis-core/loader/router-schema.js +48 -0
  73. package/elpis-core/loader/router.js +41 -0
  74. package/elpis-core/loader/service.js +66 -0
  75. package/index.js +38 -0
  76. package/model/index.js +99 -0
  77. package/package.json +90 -4
  78. package/test/controller/project.test.js +205 -0
package/.eslintignore ADDED
@@ -0,0 +1,3 @@
1
+ node_modules/
2
+ public/
3
+ docs/
package/.eslintrc ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "extends": [
3
+ "plugin:vue/base",
4
+ "plugin:vue/recommended",
5
+ ],
6
+ "plugins": ["vue"],
7
+ "env": {
8
+ "browser": true,
9
+ "node": true
10
+ },
11
+ "parser": "vue-eslint-parser",
12
+ "parserOptions": {
13
+ "parser": "babel-eslint",
14
+ "ecmaVersion": 2017,
15
+ "sourceType": "module"
16
+ },
17
+ "rules": {
18
+ "no-unused-vars": [2, {"args": "none"}],
19
+ "strict": "off",
20
+ "valid-jsdoc": "off",
21
+ "jsdoc/require-param-description": "off",
22
+ "jsdoc/require-param-type": "off",
23
+ "jsdoc/check-param-names": "off",
24
+ "jsdoc/require-param": "off",
25
+ "jsdoc/check-tag-names": "off",
26
+ "linebreak-style": "off",
27
+ "array-bracket-spacing": "off",
28
+ "prefer-promise-reject-errors": "off",
29
+ "comma-dangle": "off",
30
+ "newline-per-chained-call": "off",
31
+ "no-loop-func": "off",
32
+ "no-empty": "off",
33
+ "no-else-return": "off",
34
+ "no-unneeded-ternary": "off",
35
+ "no-eval": "off",
36
+ "prefer-destructuring": "off",
37
+ "no-param-reassign": "off",
38
+ "max-len": "off",
39
+ "no-restricted-syntax": "off",
40
+ "no-plusplus": "off",
41
+ "no-useless-escape": "off",
42
+ "no-nested-ternary": "off",
43
+ "radix": "off",
44
+ "arrow-body-style": "off",
45
+ "arrow-parens": "off",
46
+ "vue/multi-word-component-names": "off",
47
+ "vue/valid-v-for": "off",
48
+ "vue/no-multiple-template-root": "off"
49
+ },
50
+ "globals": {
51
+ "$": true,
52
+ "axios": true,
53
+ "Vue": true
54
+ }
55
+ }
package/README.md CHANGED
@@ -1,3 +1,295 @@
1
- # Temporary Holding Version
1
+ # elpis
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ## 一个企业级全栈应用框架。
4
+
5
+ 包名:`@charming_dans/elpis`,入口为仓库根目录的 `index.js`。
6
+
7
+ ---
8
+
9
+ ## 安装与依赖
10
+
11
+ ### 克隆后在本仓库安装
12
+
13
+ 从 Git 拉取代码后,在 **elpis 仓库根目录** 安装依赖(`node_modules` 不会提交,需本地自行安装):
14
+
15
+ ```bash
16
+ git clone git@github.com:charming_dans/elpis.git
17
+ cd elpis
18
+ npm install
19
+ ```
20
+
21
+ ### 在业务项目中安装
22
+
23
+ 业务项目通过 npm 依赖本包时,在 **业务项目根目录** 执行:
24
+
25
+ ```bash
26
+ npm install @charming_dans/elpis
27
+ ```
28
+
29
+ 若尚未发布到 npm,可在业务项目的 `package.json` 里用 Git 地址等形式声明依赖,再执行 `npm install`。
30
+
31
+ ### 本地联调(npm link)
32
+
33
+ 改 elpis 源码时,希望业务项目立刻用到当前目录的版本,可以用 **npm link**:
34
+
35
+ **1. 在 elpis 仓库根目录**(需已 `npm install`):
36
+
37
+ ```bash
38
+ cd /path/to/elpis
39
+ npm install
40
+ npm link
41
+ ```
42
+
43
+ 会在全局注册包名 `@charming_dans/elpis`,指向当前目录。
44
+
45
+ **2. 在业务项目根目录**:
46
+
47
+ ```bash
48
+ cd /path/to/your-business-app
49
+ npm link @charming_dans/elpis
50
+ ```
51
+
52
+ 之后业务项目 `require('@charming_dans/elpis')` 会解析到本地 elpis 目录;修改 elpis 后重启业务进程即可验证(前端构建若带缓存,必要时清缓存或重新构建)。
53
+
54
+ **取消 link,恢复 registry / lockfile 里的正式依赖:**
55
+
56
+ ```bash
57
+ # 业务项目
58
+ cd /path/to/your-business-app
59
+ npm unlink @charming_dans/elpis
60
+ npm install
61
+
62
+ # elpis 仓库(可选,取消全局 link)
63
+ cd /path/to/elpis
64
+ npm unlink
65
+ ```
66
+
67
+ > 注意:link 期间业务项目的 `node_modules/@charming_dans/elpis` 是指向本地的符号链接;提交代码时不要误把 link 状态当成已发布版本。
68
+
69
+ ---
70
+
71
+ ## 常用命令
72
+
73
+ 在 elpis 仓库根目录:
74
+
75
+ | 命令 | 说明 |
76
+ |------|------|
77
+ | `npm install` | 安装依赖 |
78
+ | `npm link` | 将 `@charming_dans/elpis` 注册到全局,供其他项目 `npm link @charming_dans/elpis` |
79
+ | `npm run lint` | ESLint 检查(提交前 ghooks 也会跑) |
80
+ | `npm test` | 运行 Mocha 测试(`_ENV=local`) |
81
+
82
+ ---
83
+
84
+ ## 本地配置与忽略项
85
+
86
+ `.gitignore` 中常见忽略:
87
+
88
+ - `node_modules` — 依赖目录,用 `npm install` 生成
89
+ - `config.local.js` — 本地私有配置,可复制 `config/config.default.js` 思路自行添加
90
+ - `app/public/dist` — 前端构建产物
91
+
92
+ ---
93
+
94
+ ### model配置
95
+ ```javascript
96
+ {
97
+ mode: 'dashboard', // 模版类型,不同模版类型对应不一样的模版数据结构
98
+ name: '', // 名称
99
+ desc: '', // 描述
100
+ icon: '', // icon
101
+ homePage: ‘’, // 首页(项目配置)
102
+ // 头部菜单
103
+ menu: [{
104
+ key: '', // 菜单唯一描述,
105
+ name: '', // 菜单名称
106
+ menuType: '', // 枚举值:group / module
107
+
108
+ // 当 menuType == group 时,可填
109
+ subMenu: [{
110
+ // 可递归 menuItem
111
+ }, ...],
112
+
113
+ // 当 menuType == module 时,可填
114
+ moduleType: '', // 枚举值:sider/iframe/custom/schema
115
+
116
+ // 当 moduleType == sider 时
117
+ siderConfig: {
118
+ menu: [{
119
+ // 可递归 menuItem(除 moduleType === sider)
120
+ }, ...]
121
+ },
122
+
123
+ // 当 moduleType == iframe 时
124
+ iframeConfig: {
125
+ path: '', // iframe 路径
126
+ },
127
+
128
+ // 当 moduleType == custom 时
129
+ customConfig: {
130
+ path: '', // 自定义路由路径
131
+ },
132
+
133
+ // 当 moduleType == schema 时
134
+ schemaConfig: {
135
+ api: '', // 数据源API(遵循 RESTFUL 规范)
136
+ schema: { // 板块数据结构
137
+ type: 'object',
138
+ properties: {
139
+ key: {
140
+ ...schema, // 标准 schema 配置
141
+ type: '', // 字段类型
142
+ label: '', // 字段的中文名
143
+ // 字段在 table 中的相关配置
144
+ tableOption: {
145
+ ...elTableColumnConfig, // 标准 el-table-column 配置
146
+ toFixed: 0, // 保留小数点后几位
147
+ visible: true, // 默认为 true(false 时,表示不在表单中显示)
148
+ },
149
+ // 字段在 search-bar 中的相关配置
150
+ searchOption: {
151
+ ...eleComponentConfig, // 标准 el-component-column 配置
152
+ comType: '', // 配置组件类型 input/select/.....
153
+ default: '', // 默认值
154
+
155
+ // comType === 'select'
156
+ enumList: [], // 下拉框可选项
157
+
158
+ // comType === 'dynamicSelect'
159
+ api: ''
160
+ },
161
+ // 字段在不同动态 component 中的相关配置,前缀对应 componentComfig 中的键值
162
+ // 如:componentConfig.createForm,这里对应 createFormOption
163
+ // 字段在 createForm 中相关配置
164
+ createFormOption: {
165
+ ...eleComponentConfig, // 标准 el-component 配置
166
+ comType: '', // 控件类型 input/selct/input-number
167
+ visible: true, // 是否展示 (true/false),默认为 true
168
+ disabled: false, // 是否禁用 (true/false),默认为 false
169
+ default: '', // 默认值
170
+
171
+ // comType === 'select' 时生效
172
+ enumList: [] // 枚举列表
173
+ },
174
+ // 字段在 editForm 表单中的相关配置
175
+ editFormOption: {
176
+ ...eleComponentConfig, // 标准 el-component 配置
177
+ comType: '', // 控件类型 input/selct/input-number
178
+ visible: true, // 是否展示 (true/false),默认为 true
179
+ disabled: false, // 是否禁用 (true/false),默认为 false
180
+ default: '', // 默认值
181
+
182
+ // comType === 'select' 时生效
183
+ enumList: [] // 枚举列表
184
+ },
185
+ detailPanelOption: {
186
+ ...eleComponentConfig // 标准 el-component 配置
187
+ }
188
+ },
189
+ ...
190
+ },
191
+ required: [], // 标记哪些字段是必填项
192
+ },
193
+ // table 相关配置
194
+ tableConfig: {
195
+ headerButtons: [{
196
+ label: '', // 按钮中文名
197
+ eventKey: '', // 按钮事件名
198
+ // 按钮事件具体配置
199
+ eventOption: {
200
+ // 当 eventKey === 'showComponent'
201
+ comName: '' // 组件名称
202
+ },
203
+ ...elButtonConfig // 标准 el-button 配置
204
+ }, ...],
205
+ rowButtons: [{
206
+ label: '', // 按钮中文名
207
+ eventKey: '', // 按钮事件名
208
+ eventOption: {
209
+ // 当 eventKey === 'showComponent'
210
+ comName: '' // 组件名称
211
+
212
+ // 当 eventKey === 'remove'
213
+ params: {
214
+ // paramKey = 参数的键值
215
+ // rowValueKey = 参数值, 格式为 schema::tableKey,到 table 中找相应的字段
216
+ paramKey: rowValueKey
217
+ }
218
+ }, // 按钮事件具体配置
219
+ ...elButtonConfig // 标准 el-button 配置
220
+ }, ...]
221
+ },
222
+ // search-bar 相关配置
223
+ searchConfig: {},
224
+ // 动态组件 相关配置
225
+ componentConfig: {
226
+ // create-form 表单相关配置
227
+ createForm: {
228
+ title: '', // 表单标题
229
+ saveBtnText: '', // 保存按钮文案
230
+ },
231
+ // edit-form 表单相关配置
232
+ editForm: {
233
+ mainKey: '', // 表单主键,用于唯一标识要修改的数据对象
234
+ title: '', // 表单标题
235
+ saveBtnText: '', // 保存按钮文案
236
+ },
237
+ // detail-panel 相关配置
238
+ detailPanel: {
239
+ mainKey: '', // 表单主键,用于唯一标识要修改的数据对象
240
+ title: '', // 表单标题
241
+ }
242
+ // ...支持用户动态扩展
243
+ }
244
+ }
245
+ }, ...]
246
+ }
247
+ ```
248
+
249
+
250
+ ### 服务端启动
251
+ ``` javascript
252
+ const {
253
+ serverStart
254
+ } = require('@charming_dans/elpis');
255
+
256
+ // 启动 elpis 服务
257
+ const app = serverStart({});
258
+ ```
259
+
260
+
261
+ ### 自定义服务端
262
+ - router-schema
263
+ - router
264
+ - controller
265
+ - service
266
+ - extend
267
+ - config
268
+
269
+
270
+ ### 前端构建
271
+ ```javascript
272
+ const { frontendBuild } = require('@charming_dans/elpis');
273
+
274
+ // 编译构建前端工程
275
+ frontendBuild(process.env._ENV);
276
+ ```
277
+
278
+
279
+ ### 自定义页面扩展
280
+ * 在 `app/pages/` 目录下写入口 entry.xxx.js
281
+
282
+ ### dashboard / custom-view 自定义页面扩展
283
+ * 在 `app/pages/dashboard/xxxx` 下写页面
284
+
285
+ ### dashboard / shcema-view / components 动态组件扩展
286
+ 1. 在 `app/pages/dashboard/complex-view/schema-view/components` 下写组件
287
+ 2. 配置到 `app/pages/dashboard/complex-view/schema-view/components/component-config.js`
288
+
289
+ ### schema-form 控件扩展
290
+ 1. 在 `app/widgets/schema-form/complex-view` 下写控件
291
+ 2. 配置到 `app/widgets/schema-form/form-item-config.js`
292
+
293
+ ### schema-search-bar 控件扩展
294
+ 1. 在 `app/widgets/schema-search-bar/complex-view` 下写控件
295
+ 2. 配置到 `app/widgets/schema-search-bar/search-item-config.js`
@@ -0,0 +1,39 @@
1
+ module.exports = (app) => class BaseController {
2
+ /**
3
+ * controller 基类
4
+ * 统一收拢 controller 相关的公共方法
5
+ */
6
+ constructor() {
7
+ this.app = app;
8
+ this.config = app.config;
9
+ }
10
+
11
+ /**
12
+ * API 处理成功时统一返回结构
13
+ * @params {object} ctx 上下文
14
+ * @params {object} data 核心数据
15
+ * @params {object} metadata 附加数据
16
+ */
17
+ success(ctx, data = {}, metadata = {}) {
18
+ ctx.status = 200;
19
+ ctx.body = {
20
+ success: true,
21
+ data,
22
+ metadata
23
+ }
24
+ }
25
+
26
+ /**
27
+ * API 处理失败时统一返回结构
28
+ * @params {object} ctx 上下文
29
+ * @params {object} message 错误信息
30
+ * @params {object} code 错误码
31
+ */
32
+ fail(ctx, message, code) {
33
+ ctx.body = {
34
+ success: false,
35
+ message,
36
+ code
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,77 @@
1
+ module.exports = (app) => {
2
+ const BaseController = require('./base')(app);
3
+ return class ProjectController extends BaseController {
4
+ /**
5
+ * 根据 proj_key 获取项目配置
6
+ */
7
+ get(ctx) {
8
+ const {
9
+ proj_key: projKey
10
+ } = ctx.request.query;
11
+
12
+ const { project: projectService } = app.service;
13
+ const projConfg = projectService.get(projKey);
14
+
15
+ if (!projConfg) {
16
+ this.fail(ctx, '获取项目异常', 50000);
17
+ return;
18
+ }
19
+
20
+ this.success(ctx, projConfg);
21
+ }
22
+
23
+ /**
24
+ * 获取当前 projectKey 对应模型下的项目列表(如果无 projKey,全量获取)
25
+ */
26
+ getList(ctx) {
27
+ const {
28
+ proj_key: projKey
29
+ } = ctx.request.query;
30
+
31
+ const { project: projectService } = app.service;
32
+ const projectList = projectService.getList({ projKey });
33
+
34
+ // 构造关键数据 list
35
+ const dtoProjectList = projectList.map(item => {
36
+ const { modelKey, key, name, desc, homePage } = item;
37
+ return { modelKey, key, name, desc, homePage };
38
+ });
39
+
40
+ this.success(ctx, dtoProjectList);
41
+ }
42
+
43
+ /**
44
+ * 获取所有模型鱼项目的结构化数据
45
+ */
46
+ async getModelList(ctx) {
47
+ const { project: projectService } = app.service;
48
+ const modelList = await projectService.getModelList();
49
+
50
+ // 构造返回结果,只返回关键数据
51
+ const dtoModelList = modelList.reduce((preList, item) => {
52
+ const { model, project } = item;
53
+
54
+ // 构造 model 关键数据
55
+ const { key, name, desc } = model;
56
+ const dtoModel = { key, name, desc };
57
+
58
+ // 构造 project 关键数据
59
+ const dtoProject = Object.keys(project).reduce((preObj, projKey) => {
60
+ const { key, name, desc, homePage } = project[projKey];
61
+ preObj[projKey] = { key, name, desc, homePage };
62
+ return preObj;
63
+ }, {});
64
+
65
+ // 整合返回结构
66
+ preList.push({
67
+ model: dtoModel,
68
+ project: dtoProject
69
+ });
70
+
71
+ return preList;
72
+ }, []);
73
+
74
+ this.success(ctx, dtoModelList);
75
+ }
76
+ }
77
+ }
@@ -0,0 +1,19 @@
1
+ module.exports = (app) => {
2
+ return class ViewController {
3
+ /**
4
+ * 渲染页面
5
+ * @param {object} ctx 上下文
6
+ */
7
+ async renderPage(ctx) {
8
+ const { query, params } = ctx.request;
9
+ app.logger.info(`[ViewController] query: ${JSON.stringify(query)}`);
10
+ app.logger.info(`[ViewController] params: ${JSON.stringify(params)}`);
11
+ await ctx.render(`dist/entry.${ctx.params.page}`, {
12
+ projKey: ctx.query?.proj_key,
13
+ name: app.options?.name,
14
+ env: app.env.get(),
15
+ options: JSON.stringify(app.options)
16
+ });
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,5 @@
1
+ module.exports = (app) => {
2
+ const { db: dbConfig } = app.config;
3
+ if (!dbConfig) { return; }
4
+ return require('knex')(dbConfig);
5
+ }
@@ -0,0 +1,38 @@
1
+ const log4js = require('log4js');
2
+
3
+ /**
4
+ * 日志工具
5
+ * 外部调用 app.logger.info app.logger.error
6
+ */
7
+ module.exports = (app) => {
8
+ let logger;
9
+
10
+ if (app.env.isLocal()) {
11
+ // 打印在控制台即可
12
+ logger = console;
13
+ } else {
14
+ // 把日志输出并落地到磁盘(日志落盘)
15
+ log4js.configure({
16
+ appenders: {
17
+ console: {
18
+ type: 'console'
19
+ },
20
+ // 日志文件切分
21
+ dateFile: {
22
+ type: 'dateFile',
23
+ filename: './logs/application.log',
24
+ pattern: '.yyyy-MM-dd'
25
+ }
26
+ },
27
+ categories: {
28
+ default: {
29
+ appenders: [ 'console', 'dateFile' ],
30
+ level: 'trace'
31
+ }
32
+ }
33
+ });
34
+ logger = log4js.getLogger();
35
+ }
36
+
37
+ return logger;
38
+ }
@@ -0,0 +1,75 @@
1
+ const Ajv = require('ajv');
2
+ const ajv = new Ajv();
3
+
4
+ /**
5
+ * API 参数校验
6
+ */
7
+ module.exports = (app) => {
8
+ const $schema = 'http://json-schema.org/draft-07/schema#';
9
+ return async (ctx, next) => {
10
+ // 只对 API 参数校验
11
+ if (ctx.path.indexOf('/api/') < 0) {
12
+ return await next();
13
+ }
14
+
15
+ // 获取请求参数
16
+ const { body, query, headers } = ctx.request;
17
+ const { params, path, method } = ctx;
18
+
19
+ app.logger.info(`[${method} ${path}] body: ${JSON.stringify(body)}`);
20
+ app.logger.info(`[${method} ${path}] query: ${JSON.stringify(query)}`);
21
+ app.logger.info(`[${method} ${path}] params: ${JSON.stringify(params)}`);
22
+ app.logger.info(`[${method} ${path}] headers: ${JSON.stringify(headers)}`);
23
+
24
+ const schema = app.routerSchema[path]?.[method.toLowerCase()];
25
+
26
+ if (!schema) {
27
+ return await next();
28
+ }
29
+
30
+ let valid = true;
31
+
32
+ // ajv 校验器
33
+ let validate;
34
+
35
+ // 校验 headers
36
+ if (valid && headers && schema.headers) {
37
+ schema.headers.$schema = $schema;
38
+ validate = ajv.compile(schema.headers);
39
+ valid = validate(headers);
40
+ }
41
+
42
+ // 校验 body
43
+ if (valid && body && schema.body) {
44
+ schema.body.$schema = $schema;
45
+ validate = ajv.compile(schema.body);
46
+ valid = validate(body);
47
+ }
48
+
49
+ // 校验 query
50
+ if (valid && query && schema.query) {
51
+ schema.query.$schema = $schema;
52
+ validate = ajv.compile(schema.query);
53
+ valid = validate(query);
54
+ }
55
+
56
+ // 校验 params
57
+ if (valid && params && schema.params) {
58
+ schema.params.$schema = $schema;
59
+ validate = ajv.compile(schema.params);
60
+ valid = validate(params);
61
+ }
62
+
63
+ if (!valid) {
64
+ ctx.status = 200;
65
+ ctx.body = {
66
+ success: false,
67
+ message: `request validate fail: ${ajv.errorsText(validate.errors)}`,
68
+ code: 442
69
+ }
70
+ return;
71
+ }
72
+
73
+ await next();
74
+ }
75
+ }
@@ -0,0 +1,38 @@
1
+ const md5 = require('md5');
2
+
3
+ /**
4
+ * API 签名合法性校验
5
+ */
6
+ module.exports = (app) => {
7
+ return async (ctx, next) => {
8
+ // 校验白名单
9
+ if (app.config?.apiSignVerify.whiteList.includes(ctx.path)) {
10
+ return await next();
11
+ }
12
+
13
+ // 只对 API 请求做签名校验
14
+ if (ctx.path.indexOf('/api') < 0) {
15
+ return await next();
16
+ }
17
+
18
+ const { path, method } = ctx;
19
+ const { headers } = ctx.request;
20
+ const { s_sign: sSign, s_t: st } = headers;
21
+
22
+ const signKey = 'klx05hb3n1c9ujp8uhxbs2ikkiowp212';
23
+ const signature = md5(`${signKey}_${st}`);
24
+ app.logger.info(`[${method} ${path}] signature: ${signature}`);
25
+
26
+ if (!sSign || !st || signature !== sSign.toLowerCase() || Date.now() - st > 600000) {
27
+ ctx.status = 200;
28
+ ctx.body = {
29
+ success: false,
30
+ message: 'signature not correct or api timeout!!',
31
+ code: 445
32
+ }
33
+ return;
34
+ }
35
+
36
+ await next();
37
+ }
38
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * 运行时异常错误处理,兜底所有异常
3
+ * @param {[object]} app koa 实例
4
+ */
5
+ module.exports = (app) => {
6
+ return async (ctx, next) => {
7
+ try {
8
+ await next();
9
+ } catch(err) {
10
+ // 异常处理
11
+ const { status, message, detail } = err;
12
+
13
+ app.logger.info(JSON.stringify(err));
14
+ app.logger.error('[-- exception --]:', err);
15
+ app.logger.error('[-- exception --]:', status, message, detail);
16
+
17
+ if (message && message.indexOf('template not found') > -1) {
18
+ // 页面重定向
19
+ ctx.status = 302; // 临时重定向
20
+ ctx.redirect(`${app.options?.homePage}`);
21
+ return;
22
+ }
23
+
24
+ const resBody = {
25
+ succes: false,
26
+ code: 50000,
27
+ message: '网络异常 请稍后重试'
28
+ }
29
+
30
+ ctx.status = 200;
31
+ ctx.body = resBody;
32
+ }
33
+ }
34
+ }