@jiangliffey/elpis 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 (81) hide show
  1. package/.eslintignore +3 -0
  2. package/.eslintrc +55 -0
  3. package/CLAUDE.md +81 -0
  4. package/README.md +200 -0
  5. package/app/controller/base.js +38 -0
  6. package/app/controller/project.js +74 -0
  7. package/app/controller/view.js +22 -0
  8. package/app/extend/logger.js +35 -0
  9. package/app/middleware/api-params-verify.js +81 -0
  10. package/app/middleware/api-sign-verify.js +35 -0
  11. package/app/middleware/error-handler.js +33 -0
  12. package/app/middleware/project-handler.js +27 -0
  13. package/app/middleware.js +37 -0
  14. package/app/pages/asserts/custom.css +12 -0
  15. package/app/pages/boot.js +50 -0
  16. package/app/pages/common/curl.js +89 -0
  17. package/app/pages/common/utils.js +2 -0
  18. package/app/pages/dashboard/complex-view/header-view/complex-view/sub-menu/sub-menu.vue +21 -0
  19. package/app/pages/dashboard/complex-view/header-view/header-view.vue +123 -0
  20. package/app/pages/dashboard/complex-view/iframe-view/iframe-view.vue +43 -0
  21. package/app/pages/dashboard/complex-view/schema-view/complex-view/search-panel/search-panel.vue +40 -0
  22. package/app/pages/dashboard/complex-view/schema-view/complex-view/table-panel/table-panel.vue +124 -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 +87 -0
  25. package/app/pages/dashboard/complex-view/schema-view/components/detail-panel/detail-panel.vue +100 -0
  26. package/app/pages/dashboard/complex-view/schema-view/components/edit-form/edit-form.vue +118 -0
  27. package/app/pages/dashboard/complex-view/schema-view/hook/schema.js +124 -0
  28. package/app/pages/dashboard/complex-view/schema-view/schema-view.vue +80 -0
  29. package/app/pages/dashboard/complex-view/sider-view/complex-view/sub-menu/sub-menu.vue +21 -0
  30. package/app/pages/dashboard/complex-view/sider-view/sider-view.vue +135 -0
  31. package/app/pages/dashboard/dashboard.vue +96 -0
  32. package/app/pages/dashboard/entry.dashboard.js +45 -0
  33. package/app/pages/dashboard/todo/todo.vue +11 -0
  34. package/app/pages/store/index.js +4 -0
  35. package/app/pages/store/menu.js +58 -0
  36. package/app/pages/store/project.js +14 -0
  37. package/app/pages/widgets/header-container/asserts/avatar.png +0 -0
  38. package/app/pages/widgets/header-container/asserts/logo.png +0 -0
  39. package/app/pages/widgets/header-container/header-container.vue +106 -0
  40. package/app/pages/widgets/schema-form/complex-view/input/input.vue +134 -0
  41. package/app/pages/widgets/schema-form/complex-view/input-number/input-number.vue +136 -0
  42. package/app/pages/widgets/schema-form/complex-view/select/select.vue +116 -0
  43. package/app/pages/widgets/schema-form/form-item-config.js +23 -0
  44. package/app/pages/widgets/schema-form/schema-form.vue +135 -0
  45. package/app/pages/widgets/schema-search-bar/complex-view/date-range/date-range.vue +50 -0
  46. package/app/pages/widgets/schema-search-bar/complex-view/dynamic-select/dynamic-select.vue +67 -0
  47. package/app/pages/widgets/schema-search-bar/complex-view/input/input.vue +44 -0
  48. package/app/pages/widgets/schema-search-bar/complex-view/select/select.vue +51 -0
  49. package/app/pages/widgets/schema-search-bar/schema-search-bar.vue +129 -0
  50. package/app/pages/widgets/schema-search-bar/search-item-config.js +27 -0
  51. package/app/pages/widgets/schema-table/schema-table.vue +235 -0
  52. package/app/pages/widgets/sider-container/sider-container.vue +31 -0
  53. package/app/public/static/logo.png +0 -0
  54. package/app/public/static/normalize.css +239 -0
  55. package/app/router/project.js +6 -0
  56. package/app/router/view.js +8 -0
  57. package/app/router-schema/project.js +30 -0
  58. package/app/service/base.js +11 -0
  59. package/app/service/project.js +56 -0
  60. package/app/view/entry.tpl +26 -0
  61. package/app/webpack/config/webpack.base.js +203 -0
  62. package/app/webpack/config/webpack.dev.js +59 -0
  63. package/app/webpack/config/webpack.prod.js +107 -0
  64. package/app/webpack/dev.js +53 -0
  65. package/app/webpack/libs/blank.js +3 -0
  66. package/app/webpack/prod.js +17 -0
  67. package/config/config.default.js +3 -0
  68. package/docs/dashboard-model.js +153 -0
  69. package/elpis-core/env.js +23 -0
  70. package/elpis-core/index.js +96 -0
  71. package/elpis-core/loader/config.js +50 -0
  72. package/elpis-core/loader/controller.js +54 -0
  73. package/elpis-core/loader/extend.js +49 -0
  74. package/elpis-core/loader/middleware.js +53 -0
  75. package/elpis-core/loader/router-schema.js +41 -0
  76. package/elpis-core/loader/router.js +45 -0
  77. package/elpis-core/loader/service.js +54 -0
  78. package/index.js +40 -0
  79. package/model/index.js +99 -0
  80. package/package.json +92 -0
  81. package/test/controller/project.test.js +225 -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/CLAUDE.md ADDED
@@ -0,0 +1,81 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Commands
6
+
7
+ ```bash
8
+ npm run dev # Start dev server with nodemon (env: local)
9
+ npm run beta # Start beta server (env: beta)
10
+ npm run prod # Start production server (env: production)
11
+ npm run build:dev # Webpack dev build (HMR dev server on port 9002)
12
+ npm run build:prod # Webpack production build
13
+ npm run lint # ESLint --quiet on .js/.vue files
14
+ ```
15
+
16
+ - Server listens on port 8080 by default (set `PORT` env var to override).
17
+ - Tests use Mocha + Supertest (no dedicated test script in package.json — run `npx mocha`).
18
+
19
+ ## Project Architecture
20
+
21
+ Full-stack enterprise application framework powered by a custom **elpis-core** bootstrap.
22
+
23
+ ### elpis-core Framework (`elpis-core/`)
24
+
25
+ Custom Koa-based framework that auto-discovers and loads app components. Bootstrap order:
26
+
27
+ 1. **middleware** — loads `app/middleware/**/*.js` into `app.middlewares.{dir}.{name}`
28
+ 2. **router-schema** — loads `app/router-schema/**/*.js` into `app.routerSchema` (JSON Schema for API param validation via ajv)
29
+ 3. **controller** — loads `app/controller/**/*.js` into `app.controller.{dir}.{name}` (instantiated as classes)
30
+ 4. **service** — loads `app/service/**/*.js` into `app.service.{dir}.{name}` (instantiated as classes)
31
+ 5. **config** — merges `config/config.default.js` with env-specific override (`config.local.js`/`config.beta.js`/`config.prod.js`) into `app.config`
32
+ 6. **extend** — loads `app/extend/**/*.js`, mounted directly onto `app` object (conflict-protected)
33
+
34
+ Then registers global middleware from `app/middleware.js`, then routes from `app/router/`, then starts the server.
35
+
36
+ ### Global Middleware Pipeline (`app/middleware.js`)
37
+
38
+ 1. `koa-static` — serves `app/public`
39
+ 2. `koa-nunjucks-2` — template rendering (`.tpl` files)
40
+ 3. `koa-bodyparser` — request body parsing (json/form/text, 1000mb limit)
41
+ 4. `app.middlewares.errorHandler` — catches and formats errors
42
+ 5. `app.middlewares.apiSignVerify` — MD5-based signature verification on `/api/*` routes
43
+ 6. `app.middlewares.apiParamsVerify` — JSON Schema param validation against `app.routerSchema`
44
+
45
+ ### API Conventions
46
+
47
+ - All API routes under `/api/`
48
+ - Response format: `{ success: true, data, metadata }` or `{ success: false, message, code }`
49
+ - Signature auth: MD5 of `{signKey}_{timestamp}` sent in headers `s_sign`/`s_t` (600s expiry)
50
+ - Base controller (`app/controller/base.js`) provides `success(ctx, data, metadata)` and `fail(ctx, message, code)` helpers
51
+ - Base service (`app/service/base.js`) exposes `this.curl` (superagent) and `this.config`
52
+
53
+ ### Frontend (`app/pages/`)
54
+
55
+ Vue 3 + Element Plus + Pinia + Vue Router. Pages are auto-discovered via glob `app/pages/**/entry.*.js`.
56
+
57
+ - `boot.js` — Vue app bootstrap (creates app, mounts Element Plus/Pinia/Router)
58
+ - Each page has `entry.{page}.js` + `{page}.vue`
59
+ - Webpack splits bundles: vendor (node_modules), common (shared modules), entry.{page} (page-specific)
60
+ - Dev: HMR-enabled on port 9002, outputs to `app/public/dist/dev/`
61
+ - Prod: outputs to `app/public/dist/`
62
+ - Path aliases: `$elpisPages`, `$elpisCommon`, `$elpisWidgets`, `$elpisStore`
63
+
64
+ ### Directory Layout
65
+
66
+ ```
67
+ app/
68
+ controller/ # Controllers (class per file, receives `app` in factory)
69
+ service/ # Services (class per file, extends BaseService)
70
+ middleware/ # Koa middleware (function(app) => async fn)
71
+ router/ # Route definitions (receives app + koa-router)
72
+ router-schema/ # JSON Schema for API param validation
73
+ extend/ # Extensions merged into Koa app instance
74
+ pages/ # Vue 3 frontend pages
75
+ webpack/ # Webpack config (base/dev/prod)
76
+ view/ # Nunjucks templates (.tpl)
77
+ public/ # Static assets
78
+ middleware.js # Global middleware registration
79
+ config/ # Environment configs (default/local/beta/prod)
80
+ elpis-core/ # Custom framework bootstrap & loaders
81
+ ```
package/README.md ADDED
@@ -0,0 +1,200 @@
1
+ # elpis
2
+ ## 一个企业级应用框架,通过全栈实现。
3
+
4
+ ### model配置
5
+ ```javascript
6
+ {
7
+ model: 'dashboard'; // 模板类型,不同模板类型对应不一样的模板数据结构
8
+ name: ''; // 名称
9
+ desc: ''; // 描述
10
+ icon: ''; // 图标
11
+ homePage: ''; // 首页(项目配置)
12
+ // 头部菜单
13
+ menu: [{
14
+ key: '', // 菜单唯一描述
15
+ name: '', // 菜单名称
16
+ menuType: '', // 枚举值:group/module
17
+
18
+ // 当 menuType == group 时,可填
19
+ subMenu: [{
20
+ // 可递归 menuItem
21
+ },],
22
+
23
+ // 当 menuType == module 时,可填
24
+ moduleType: '', // 枚举值:sider/iframe/custom/schema
25
+
26
+ // 当 moduleType == sider 时
27
+ siderConfig: {
28
+ menu: [{
29
+ // 可递归 menuItem(除了menuType == sider外)
30
+ }]
31
+ },
32
+
33
+ // 当 moduleType == iframe 时
34
+ iframeConfig: {
35
+ path: '', // iframe路径
36
+ },
37
+
38
+ // 当 moduleType == custom 时
39
+ customConfig: {
40
+ path: '', // 自定义路由路径
41
+ },
42
+
43
+ // 当 moduleType == schema 时
44
+ schemaConfig: {
45
+ api: '', // 数据源API(遵循 RESTFUL 规范)
46
+ schema: { // 板块数据结构
47
+ type: 'object',
48
+ properties: {
49
+ key: {
50
+ ...schema, // 标准 schema 配置
51
+ type: '', // 字段类型
52
+ label: '', // 字段中文名
53
+ // 字段在 table 中的相关配置
54
+ tableOption: {
55
+ ...elTableColumnConfig, // 标准 el-table-column 配置
56
+ toFixed: 0, // 保留小数点后几位
57
+ visible: true, // 默认为 true (false时,表示不在表单中显示)
58
+ },
59
+ // 字段在 search-bar 中的相关配置
60
+ searchOption: {
61
+ ...elComponentConfig, // 标准 el-table-column 配置
62
+ comType: '', // 配置组件类型 input/select/...
63
+ default: '', // 默认值
64
+
65
+ // comType === 'select' 时的相关配置
66
+ enumList: [], // 下拉框可选项
67
+
68
+ // comType === 'dynamicSelect' 时的相关配置
69
+ api: ''
70
+ },
71
+ // 字段在不同动态 component 中的相关配置,前缀对应 componentConfig 中的键值
72
+ // 如:componentConfig.createForm,这里对应 createFormOption
73
+ // 字段在 createForm 中的相关配置
74
+ createFormOption: {
75
+ ...elComponentConfig, // 标准 el-component 配置
76
+ comType: '', // 控件类型 input/select/...
77
+ visible: true, // 默认为 true
78
+ disable: false, // 是否禁用,默认false
79
+ default: '', // 默认值
80
+
81
+ // comType === 'select' 时生效
82
+ enumList: [], // 枚举列表
83
+ },
84
+ // 字段在 editForm 表单中的相关配置
85
+ editFormOption: {
86
+ ...elComponentConfig, // 标准 el-component 配置
87
+ comType: '', // 控件类型 input/select/...
88
+ visible: true, // 默认为 true
89
+ disable: false, // 是否禁用,默认false
90
+ default: '', // 默认值
91
+
92
+ // comType === 'select' 时生效
93
+ enumList: [], // 枚举列表
94
+ },
95
+ // 字段在 detail-panel 中的相关配置
96
+ detailPanelOption: {
97
+ ...elComponentConfig, // 标准 el-component 配置
98
+ }
99
+ },
100
+ ...
101
+ },
102
+ required: [], // 标记哪些字段是必填项
103
+ },
104
+ // table 相关配置
105
+ tableConfig: {
106
+ headerButtons: [{
107
+ label: '', // 按钮中文名
108
+ eventKey: '', // 按钮事件名
109
+ // 按钮事件具体配置
110
+ eventOption: {
111
+ // 当 eventKey === 'showComponent'
112
+ comName: '', // 组件名称
113
+ },
114
+ ...elButtonConfig // 标准el-button 配置
115
+ },...],
116
+ rowButtons: [{
117
+ label: '', // 按钮中文名
118
+ eventKey: '', // 按钮事件名
119
+ eventOption: {
120
+ // 当 eventKey === 'showComponent'
121
+ comName: '', // 组件名称
122
+
123
+ // 当 eventKey === 'remove'
124
+ params: {
125
+ // paramsKey = 参数的键值
126
+ // rowValueKey = 参数值,格式为 schema::tableKey 的时候,到table中找相应的字段
127
+ paramsKey: rowValueKey
128
+ }
129
+ }, // 按钮事件具体配置
130
+ ...elButtonConfig // 标准el-button 配置
131
+ },...],
132
+ },
133
+ // search-bar 相关配置
134
+ searchConfig: {},
135
+ // 动态组件 相关配置
136
+ componentConfig: {
137
+ // create-form 表单相关配置
138
+ createForm: {
139
+ title: '', // 表单标题
140
+ saveBtnText: '', // 保存按钮文案
141
+ },
142
+ // edit-form 表单相关配置
143
+ editForm: {
144
+ mainKey: '', // 表单主键,用于唯一标识要修改的数据对象
145
+ title: '', // 表单标题
146
+ saveBtnText: '', // 保存按钮文案
147
+ },
148
+ detailPanel: {
149
+ mainKey: '', // 表单主键,用于唯一标识要修改的数据对象
150
+ title: '', // 表单标题
151
+ }
152
+ // detail-panel 相关配置
153
+ // ...支持用户动态拓展
154
+ },
155
+ },
156
+
157
+ },]
158
+ }
159
+ ```
160
+
161
+ ### 服务端启动
162
+ ```javascript
163
+ const { serverStart } = require('@jiangliffey/elpis');
164
+
165
+ // 启动 elpis 服务
166
+ const app = serverStart({});
167
+ ```
168
+
169
+ ### 自定义服务端
170
+ - router-schema
171
+ - router
172
+ - controller
173
+ - service
174
+ - extend
175
+ - config
176
+
177
+ ### 前端构建
178
+ ```javascript
179
+ const { fontendBuild } = require('@jiangliffey/elpis');
180
+
181
+ // 编译构建前端工程
182
+ fontendBuild(process.env._ENV);
183
+ ```
184
+ ### 自定义页面扩展
185
+ * 在 `app/pages/` 目录下写入口 entry.xxx.js
186
+
187
+ ### dashboard / custom-view 自定义页面扩展
188
+ * 在 `app/pages/dashboard/xxx` 下写页面
189
+
190
+ ### dashboard / schema-view / components 动态组件扩展
191
+ 1. 在 `app/pages/dashboard/complex-view/schema-view/components` 下写组件
192
+ 2. 配置到 `app/pages/dashboard/complex-view/schema-view/components/component-config.js`
193
+
194
+ ### schema-form 控件扩展
195
+ 1. 在 `app/widgets/schema-form/complex-view` 下写控件
196
+ 2. 配置到 `app/widgets/schema-form/form-item-config.js`
197
+
198
+ ### schema-search-bar 控件扩展
199
+ 1. 在 `app/widgets/schema-search-bar/complex-view` 下写控件
200
+ 2. 配置到 `app/widgets/schema-search-bar/search-item-config.js`
@@ -0,0 +1,38 @@
1
+ module.exports = (app) => class BaseController {
2
+ /**
3
+ * controller 基类,所有 controller 都继承自这个类,可以在这里定义一些公共方法或者属性
4
+ */
5
+ constructor() {
6
+ this.app = app;
7
+ this.config = app.config;
8
+ }
9
+
10
+ /**
11
+ * API处理成功时的响应,统一返回结构
12
+ * @param {object} ctx 上下文
13
+ * @param {object} data 核心数据
14
+ * @param {object} metadata 附加数据
15
+ */
16
+ success(ctx, data = null, metadata = {}) {
17
+ ctx.status = 200;
18
+ ctx.body = {
19
+ success: true,
20
+ data,
21
+ metadata
22
+ }
23
+ }
24
+
25
+ /**
26
+ * API处理失败时的响应,统一返回结构
27
+ * @param {object} ctx 上下文
28
+ * @param {object} message 错误信息
29
+ * @param {object} code 错误码
30
+ */
31
+ fail(ctx, message, code) {
32
+ ctx.body = {
33
+ success: false,
34
+ message,
35
+ code
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,74 @@
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 { proj_key: projKey } = ctx.request.query;
9
+
10
+ const { project: projectService } = app.service;
11
+ const projConfig = projectService.get(projKey);
12
+
13
+ if(!projConfig) {
14
+ this.fail(ctx, '获取项目异常', 50000);
15
+ return;
16
+ }
17
+
18
+ this.success(ctx, projConfig);
19
+ }
20
+
21
+ /**
22
+ * 获取当前 projectKey 对应模型下的项目列表(如果无 projKey,全量获取)
23
+ */
24
+ getList(ctx) {
25
+ const { proj_key: projKey } = ctx.request.query;
26
+
27
+ const { project: projectService } = app.service;
28
+ const projectList = projectService.getList({ projKey });
29
+
30
+ // 构造关键数据 list
31
+ const dtoProjectList = projectList.map(item => {
32
+ const { modelKey, key, name, desc, homePage } = item;
33
+ return { modelKey, key, name, desc, homePage };
34
+ });
35
+
36
+ this.success(ctx, dtoProjectList);
37
+ }
38
+
39
+ /**
40
+ * 获取所有模型与项目的结构化数据
41
+ * @param {Object} ctx - 上下文对象
42
+ */
43
+ async getModelList(ctx) {
44
+ const { project: projectService } = app.service;
45
+ const modelList = await projectService.getModelList();
46
+
47
+ // 构造返回结果,只返回关键数据
48
+ const dtoModelList = modelList.reduce((preList, item) => {
49
+ const { model, project } = item;
50
+
51
+ // 构造 model 关键数据
52
+ const { key, name, desc } = model;
53
+ const dtoModel = { key, name, desc };
54
+
55
+ // 构造 project 关键数据
56
+ const dtoProject = Object.keys(project).reduce((preObj, proKey) => {
57
+ const { key, name, desc, homePage } = project[proKey];
58
+ preObj[proKey] = { key, name, desc, homePage };
59
+ return preObj;
60
+ }, {});
61
+
62
+ // 整合返回结构
63
+ preList.push({
64
+ model: dtoModel,
65
+ project: dtoProject
66
+ });
67
+
68
+ return preList;
69
+ }, []);
70
+
71
+ this.success(ctx, dtoModelList);
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,22 @@
1
+ module.exports = (app) => {
2
+ return class ViewController {
3
+ /**
4
+ * 渲染页面
5
+ * @param {Object} ctx - 上下文对象
6
+ */
7
+ async renderPage(ctx) {
8
+ const { query, params } = ctx;
9
+ const { proj_key: projKey } = ctx.request.query;
10
+
11
+ app.logger.info(`[ViewController] query: ${JSON.stringify(query)}`);
12
+ app.logger.info(`[ViewController] params: ${JSON.stringify(params)}`);
13
+
14
+ await ctx.render(`dist/entry.${ctx.params.page}`, {
15
+ projKey: projKey || '',
16
+ name: app.options?.name,
17
+ env: app.env.getEnv(),
18
+ options: JSON.stringify(app.options)
19
+ });
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,35 @@
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: { type: 'console' },
18
+ // 日志文件切分
19
+ dateFile: {
20
+ type: 'dateFile',
21
+ filename: './logs/application.log',
22
+ pattern: 'yyyy-MM-dd',
23
+ }
24
+ },
25
+ categories: {
26
+ default: {
27
+ appenders: ['console', 'dateFile'],
28
+ level: 'trace'
29
+ }
30
+ }
31
+ });
32
+ logger = log4js.getLogger();
33
+ }
34
+ return logger;
35
+ }
@@ -0,0 +1,81 @@
1
+ const Ajv = require("ajv");
2
+ const ajv = new Ajv();
3
+
4
+ /**
5
+ * API 参数校验
6
+ */
7
+ module.exports = (app) => {
8
+ // 校验规则的版本声明(因为JSON Schema 不是只有一个固定版本,不同版本之间会有一些差异)
9
+ const $schema = 'http://json-schema.org/draft-07/schema#';
10
+ return async (ctx, next) => {
11
+ // 只对API请求做参数校验,其他请求直接放行
12
+ if(ctx.path.indexOf('/api/') < 0) {
13
+ return await next();
14
+ }
15
+
16
+ // 获取请求参数
17
+ const { query, body, headers } = ctx.request;
18
+ const { params, path, method } = ctx;
19
+
20
+ app.logger.info(`[-- api params verify ${method} ${path} --] body: ${JSON.stringify(body)}`);
21
+ app.logger.info(`[-- api params verify ${method} ${path} --] query: ${JSON.stringify(query)}`);
22
+ app.logger.info(`[-- api params verify ${method} ${path} --] params: ${JSON.stringify(params)}`);
23
+ app.logger.info(`[-- api params verify ${method} ${path} --] headers: ${JSON.stringify(headers)}`);
24
+
25
+ const schema = app.routerSchema[path]?.[method.toLowerCase()];
26
+ if (!schema) {
27
+ app.logger.warn(`[-- api params verify --]: no schema defined for path=${path}, method=${method}`);
28
+ return await next();
29
+ }
30
+
31
+ let valid = true;
32
+
33
+ // ajv检验器
34
+ let validate;
35
+
36
+ // 校验headers
37
+ if (valid && headers && schema.headers) {
38
+ const headerSchema = { $schema, ...schema.headers};
39
+ validate = ajv.compile(headerSchema);
40
+
41
+ // schema.headers.$schema = $schema;
42
+ // validate = ajv.compile(schema.headers);
43
+ valid = validate(headers);
44
+ }
45
+
46
+ // 校验body
47
+ if (valid && body && schema.body) {
48
+ const bodySchema = { $schema, ...schema.body};
49
+ validate = ajv.compile(bodySchema);
50
+ // schema.body.$schema = $schema;
51
+ // validate = ajv.compile(schema.body);
52
+ valid = validate(body);
53
+ }
54
+
55
+ // 校验query
56
+ if (valid && query && schema.query) {
57
+ const querySchema = { $schema, ...schema.query};
58
+ validate = ajv.compile(querySchema);
59
+ valid = validate(query);
60
+ }
61
+
62
+ // 校验params
63
+ if (valid && params && schema.params) {
64
+ const paramsSchema = { $schema, ...schema.params};
65
+ validate = ajv.compile(paramsSchema);
66
+ valid = validate(params);
67
+ }
68
+
69
+ if (!valid) {
70
+ ctx.status = 200;
71
+ ctx.body = {
72
+ success: false,
73
+ message: `参数校验失败: ${ajv.errorsText(validate.errors)}`,
74
+ code: 442
75
+ }
76
+ return;
77
+ }
78
+
79
+ await next();
80
+ }
81
+ }
@@ -0,0 +1,35 @@
1
+
2
+ const md5 = require('md5');
3
+ /**
4
+ * API 签名合法性校验
5
+ * 1. 从请求头中获取签名信息
6
+ * 2. 验证签名的合法性
7
+ */
8
+
9
+ module.exports = (app) => {
10
+ return async (ctx, next) => {
11
+ // 只对API请求做签名校验,其他请求直接放行
12
+ if(ctx.path.indexOf('/api/') < 0) {
13
+ return await next();
14
+ }
15
+ const { path, method } = ctx;
16
+ const { headers } = ctx.request;
17
+ const { s_sign: sSign, s_t: st } = headers;
18
+
19
+ const signKey = 'dftgyh84adsuh462wef46ef5s6d4fiop'; // 签名密钥,实际项目中应该放在环境变量中
20
+ const signature = md5(`${signKey}_${st}`);
21
+ app.logger.info(`[-- api sign verify --]: path=${path}, method=${method}, s_sign=${sSign}, s_t=${st}, signature=${signature}`);
22
+
23
+ if(!sSign || !st || signature !== sSign.toLowerCase() || Date.now() -st > 600000) {
24
+ ctx.status = 200;
25
+ ctx.body = {
26
+ success: false,
27
+ message: 'signature verification failed or api timeout!!!',
28
+ code: 445
29
+ }
30
+ return;
31
+ }
32
+
33
+ await next();
34
+ }
35
+ }
@@ -0,0 +1,33 @@
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, details } = err;
12
+ app.logger.info(JSON.stringify(err));
13
+ app.logger.error('[-- exception --]:', err);
14
+ app.logger.error('[-- exception --]:', status, message, details);
15
+
16
+ if(message && message.indexOf('template not found') > -1) {
17
+ // 页面重定向
18
+ ctx.status = 302; // 临时重定向
19
+ ctx.redirect(`${app?.options?.homePage}`);
20
+ return;
21
+ }
22
+
23
+ const resBody = {
24
+ success: false,
25
+ code: 50000,
26
+ message: '网络异常,请稍后再试'
27
+ }
28
+
29
+ ctx.status = 200;
30
+ ctx.body = resBody;
31
+ }
32
+ }
33
+ }