chanjs 1.0.21 → 1.0.23

Sign up to get free protection for your applications and to get access to all the features.
package/README.md CHANGED
@@ -76,7 +76,7 @@ Chan.js 基于express 纯js研发的轻量级mvc框架。基于函数式编程
76
76
  * 多模块mvc
77
77
  * 插件mvc
78
78
  * 支持cors跨域配置
79
- * mysql数据库支持
79
+ * mysql数据库支持
80
80
  * 路由控制
81
81
  * art-template模板
82
82
  * 静态资源
package/core/chan.js CHANGED
@@ -1,26 +1,34 @@
1
1
  const express = require("express");
2
2
  const config = require("./lib/config/config.js");
3
3
  const bindClass = require("./lib/extend/bindClass.js");
4
+ const Controller = require("./lib/controller/controller.js")
5
+ const Service = require("./lib/service/service.js")
4
6
  const path = require("path");
5
7
  const fs = require("fs");
6
- const core = require("./lib/core.js");
7
- const cors = require('cors')
8
+ const core = require("./lib/index.js");
9
+ const cors = require('cors');
10
+
8
11
  /**
9
12
  * @description 基于express封装的mvc框架,遵循约定优于配置原则
10
13
  */
11
14
  class Chan {
15
+ static config = {};
16
+ //模块
17
+ static modules = {};
18
+ //插件
19
+ static plugins = {};
20
+ //工具
21
+ static helper = {};
22
+ static Controller = null;
23
+ static Service = null;
12
24
  constructor(options={}) {
13
25
  //配置
14
26
  Chan.config = {...config,...options};
15
- //模块
16
- Chan.modules ={};
17
- //插件
18
- Chan.plugins ={};
19
- //工具
20
- Chan.helper ={};
27
+ //控制器基类
28
+ Chan.Controller = Controller;
21
29
  //应用实例
22
30
  this.app = express();
23
- this.app.config = Chan.config;
31
+ // this.app.config = Chan.config;
24
32
  this.router = express.Router();
25
33
  //加载配置
26
34
  this.loadConfig();
@@ -30,6 +38,7 @@ class Chan {
30
38
  this.loadCore();
31
39
  //加载实例化数据库
32
40
  this.loadKnex();
41
+
33
42
  //生命周期钩子:开始启动
34
43
  this.beforeStart();
35
44
  //解决跨域
@@ -46,17 +55,18 @@ class Chan {
46
55
 
47
56
  // 加载配置
48
57
  loadConfig() {
49
- const configPath = path.join(config.APP_PATH, "config/index.js");
58
+ const configPath = path.join(Chan.config.APP_PATH, "config/index.js");
50
59
  if (fs.existsSync(configPath)) {
51
60
  const config = require(configPath);
52
- let allConfig = {...Chan.config,...config};
53
- this.app.config = Chan.config = allConfig;
61
+ // let allConfig = {...Chan.config,...config};
62
+ // this.app.config = Chan.config = allConfig;
63
+ Chan.config = {...Chan.config,...config};
54
64
  }
55
65
  }
56
66
 
57
67
  // 加载扩展
58
68
  loadExtends() {
59
- const extendPath = path.join(config.APP_PATH, "extend");
69
+ const extendPath = path.join(Chan.config.APP_PATH, "extend");
60
70
  if (fs.existsSync(extendPath)) {
61
71
  let controllers = fs
62
72
  .readdirSync(extendPath)
@@ -74,7 +84,16 @@ class Chan {
74
84
  //数据库操作
75
85
  loadKnex(){
76
86
  // 连接数据库
77
- const {host,port,user,password,database,client='mysql2',charset} = Chan.config.database;
87
+ const {
88
+ host='localhost',
89
+ port='3306',
90
+ user,
91
+ password,
92
+ database,
93
+ client='mysql2',
94
+ charset='utf8mb4'
95
+ } = Chan.config.database;
96
+
78
97
  const knex = require("knex")({
79
98
  client: client,
80
99
  connection: {
@@ -85,7 +104,7 @@ class Chan {
85
104
  database,
86
105
  charset,
87
106
  },
88
- debug: config.debug, //指明是否开启debug模式,默认为true表示开启
107
+ debug: Chan.config.debug, //指明是否开启debug模式,默认为true表示开启
89
108
  pool: {
90
109
  //指明数据库连接池的大小,默认为{min: 2, max: 10}
91
110
  min: 0,
@@ -100,7 +119,11 @@ class Chan {
100
119
  },
101
120
  },
102
121
  });
122
+
123
+ //数据库操作实例
103
124
  Chan.knex = knex;
125
+ //数据库操作基类
126
+ Chan.Service = Service(knex);
104
127
  }
105
128
 
106
129
  //开始启动
@@ -129,14 +152,15 @@ class Chan {
129
152
  * @description app核心模块:日志、favicon 图标、cookie、json、url、模板引擎、静态资源
130
153
  */
131
154
  loadCore(){
132
- core(this.app);
155
+ console.log()
156
+ core(this.app, Chan.config);
133
157
  }
134
158
 
135
159
  /**
136
160
  * @description 模块加载入口(路由&控制器& 服务)
137
161
  */
138
162
  loadModules(modules='modules') {
139
- const configPath = path.join(config.APP_PATH,modules);
163
+ const configPath = path.join(Chan.config.APP_PATH,modules);
140
164
  if (fs.existsSync(configPath)) {
141
165
  const dirs = fs
142
166
  .readdirSync(configPath, { withFileTypes: true })
@@ -174,7 +198,7 @@ class Chan {
174
198
  * @param {*} moduleName 模块名称
175
199
  */
176
200
  loadServices(modules,moduleName) {
177
- const servicesDir = path.join(config.APP_PATH, modules, moduleName,"service");
201
+ const servicesDir = path.join(Chan.config.APP_PATH, modules, moduleName,"service");
178
202
  if (fs.existsSync(servicesDir)) {
179
203
  let services = fs
180
204
  .readdirSync(servicesDir)
@@ -197,7 +221,7 @@ class Chan {
197
221
  * @param {*} moduleName 模块名称
198
222
  */
199
223
  loadControllers(modules,moduleName) {
200
- const controllersDir = path.join(config.APP_PATH, modules, moduleName,"controller");
224
+ const controllersDir = path.join(Chan.config.APP_PATH, modules, moduleName,"controller");
201
225
  if (fs.existsSync(controllersDir)) {
202
226
  let controllers = fs
203
227
  .readdirSync(controllersDir)
@@ -218,7 +242,7 @@ class Chan {
218
242
  * @param {*} moduleName 模块名称
219
243
  */
220
244
  loadRoutes(modules,moduleName) {
221
- const routersDir = path.join(config.APP_PATH, modules, moduleName,"router.js");
245
+ const routersDir = path.join(Chan.config.APP_PATH, modules, moduleName,"router.js");
222
246
  if (fs.existsSync(routersDir)) {
223
247
  const routes = require(routersDir);
224
248
  routes({router:this.router,modules:Chan[modules],app:this.app});
@@ -228,10 +252,10 @@ class Chan {
228
252
  //通用路由,加载错误处理和500路由和爬虫处理
229
253
  loadCommonRouter(){
230
254
  try {
231
- const baseRouterPath = path.join(config.APP_PATH, "router.js");
255
+ const baseRouterPath = path.join(Chan.config.APP_PATH, "router.js");
232
256
  if (fs.existsSync(baseRouterPath)) {
233
257
  const _router = require(baseRouterPath);
234
- _router(this.app, this.router);
258
+ _router(this.app, this.router,Chan.config);
235
259
  }
236
260
  } catch (error) {
237
261
  console.log(error);
@@ -239,7 +263,7 @@ class Chan {
239
263
  }
240
264
 
241
265
  run() {
242
- const port = this.app.config.port || '81';
266
+ const port = Chan.config.port || '81';
243
267
  this.app.listen(port, () => {
244
268
  console.log(`Server is running on port ${port}`);
245
269
  });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @description
3
+ * 控制器基类
4
+ */
5
+ class Controller{
6
+
7
+ constructor(){
8
+
9
+ }
10
+
11
+ download(res,file){
12
+ res.download(file)
13
+ }
14
+
15
+ success(res,data=null){
16
+ res.json({code:200,msg:'success',data:data})
17
+ }
18
+
19
+ fail(res,msg='操作失败,请稍后再试'){
20
+ res.json({code:400,msg:msg})
21
+ }
22
+
23
+ error(res,msg){
24
+ res.json({code:500,msg:msg})
25
+ }
26
+ }
27
+
28
+
29
+
30
+ module.exports = Controller;
@@ -3,10 +3,10 @@ const cookieParser = require("cookie-parser");
3
3
  const favicon = require("serve-favicon");
4
4
  const morgan = require("morgan");
5
5
  const path = require("path");
6
- const view = require("./middleware/view.js");
7
- module.exports = async function (app) {
6
+ const template = require("./middleware/template.js");
7
+ module.exports = async function (app,config) {
8
8
  const { logger, APP_PATH, cookieKey, maxAge, JSON_LIMIT, appName, version } =
9
- app.config;
9
+ config;
10
10
  //日志
11
11
  app.use(morgan(logger.level));
12
12
 
@@ -21,7 +21,7 @@ module.exports = async function (app) {
21
21
  app.use(express.urlencoded({ extended: false }));
22
22
 
23
23
  //配置模板引擎
24
- view(app);
24
+ template(app,config);
25
25
 
26
26
  //使用静态资源 ,
27
27
  app.use(
@@ -33,7 +33,7 @@ module.exports = async function (app) {
33
33
 
34
34
  //设置头信息
35
35
  app.use((req, res, next) => {
36
- res.setHeader("mvc", "Chanjs");
36
+ res.setHeader("Create-By", "Chanjs");
37
37
  res.setHeader("X-Powered-By", appName);
38
38
  res.setHeader(appName, version);
39
39
  next();
@@ -1,7 +1,7 @@
1
1
  const path = require("path");
2
- module.exports = (app) => {
2
+ module.exports = (app,config) => {
3
3
  const
4
- { APP_PATH, views,env } = app.config;
4
+ { APP_PATH, views,env } = config;
5
5
  //默认home view
6
6
  const home = path.join(APP_PATH, `modules/web/view`);
7
7
  //合并插件中的view
@@ -0,0 +1,195 @@
1
+ class BaseService {
2
+ /**
3
+ * @description 构造函数
4
+ * @param {*} knex - knex实例
5
+ * @param {*} model - 模型名称
6
+ */
7
+ constructor(knex, model='') {
8
+ this.knex = knex;
9
+ this.model = model;
10
+ }
11
+
12
+ /**
13
+ * @description 查找所有符合条件的记录
14
+ * @param {*} query - 查询条件,例如:{name: 'test', age: 18}
15
+ * @returns {Promise} 返回符合条件的记录
16
+ */
17
+ query(query) {
18
+ return this.knex(this.model).where(query);
19
+ }
20
+
21
+ /**
22
+ * @description 查询表所有记录,慎用
23
+ * @returns {Promise} 返回所有记录
24
+ */
25
+ all() {
26
+ return this.knex(this.model).select();
27
+ }
28
+
29
+ /**
30
+ * @description 查询指定id的记录
31
+ * @param {*} id
32
+ * @returns {Promise} 返回指定id的记录
33
+ */
34
+ findById(id) {
35
+ return this.knex(this.model).where('id', id).first();
36
+ }
37
+
38
+ /**
39
+ * @description 查询分页数据
40
+ * @param {*} current
41
+ * @param {*} pageSize
42
+ * @param {*} query
43
+ * @returns {Promise} 返回分页数据
44
+ */
45
+ async findListAndQuery(current = 1, pageSize = 10, query = {}) {
46
+ const offset = (current - 1) * pageSize;
47
+
48
+ let countQuery = this.knex(this.model).count('* as total');
49
+ let dataQuery = this.knex(this.model);
50
+
51
+ // 应用查询条件
52
+ for (const key in query) {
53
+ dataQuery = dataQuery.where(key, query[key]);
54
+ countQuery = countQuery.where(key, query[key]);
55
+ }
56
+
57
+ // 获取总记录数
58
+ const total = await countQuery.first();
59
+
60
+ // 获取分页数据
61
+ const data = await dataQuery.offset(offset).limit(pageSize);
62
+
63
+ return { data, total: parseInt(total.total, 10) };
64
+ }
65
+
66
+ /**
67
+ * @description 查询指定id的记录
68
+ * @param {*} id - 记录id
69
+ * @returns {Promise} 返回指定id的记录
70
+ */
71
+ findOneById(id) {
72
+ return this.knex(this.model).where('id', id).select();
73
+ }
74
+
75
+ /**
76
+ * @description 查询指定条件的记录
77
+ * @param {Object} query - {<key>:<value>}
78
+ * @returns {Promise} 返回指定条件的记录
79
+ */
80
+ findOne(query) {
81
+ return this.knex(this.model).where(query).first();
82
+ }
83
+
84
+ /**
85
+ * @description 更新指定id的记录
86
+ * @param {*} id - 记录id
87
+ * @param {*} params - {<key>:<value>}
88
+ * @returns {Promise} 返回更新后的记录
89
+ */
90
+ findOneAndUpdate(id, params) {
91
+ return this.knex(this.model).where('id', id).update(params).returning('*');
92
+ }
93
+
94
+
95
+ /**
96
+ * @description 查询指定条件的记录数量
97
+ * @param {*} query - {<key>:<value>}
98
+ * @returns {Promise} 返回指定条件的记录数量
99
+ */
100
+ count(query) {
101
+ return this.knex(this.model).where(query).count('* as total').first();
102
+ }
103
+
104
+ /**
105
+ * @description 插入一条记录
106
+ * @param {*} params - {<key>:<value>}
107
+ * @returns {Promise} 返回插入后的记录
108
+ */
109
+ insert(params) {
110
+ return this.knex(this.model).insert(params);
111
+ }
112
+
113
+ /**
114
+ * @description 插入多条记录
115
+ * @param {*} records - [{<key>:<value>}, {<key>:<value>}, ...]
116
+ * @returns {Promise} 返回插入后的记录
117
+ */
118
+ insertMany(records) {
119
+ return this.knex(this.model).insert(records);
120
+ }
121
+
122
+ /**
123
+ * @description 更新指定id的记录
124
+ * @param {*} id - 记录id
125
+ * @param {*} params - {<key>:<value>}
126
+ * @returns {Promise} 返回更新后的记录
127
+ */
128
+ updateById(id, params) {
129
+ return this.knex(this.model).where('id', id).update(params);
130
+ }
131
+
132
+ /**
133
+ * @description 更新数据
134
+ * @param {*} query - {<key>:<value>}
135
+ * @param {*} update - {<key>:<value>}
136
+ * @returns {Promise<*>} - 返回更新后的数据
137
+ */
138
+ update(query, update) {
139
+ return this.knex(this.model).where(query).update(update);
140
+ }
141
+
142
+ /**
143
+ * @description 查询并更新
144
+ * @param {*} query - {<key>:<value>}
145
+ * @param {*} update - {<key>:<value>}
146
+ * @returns {Promise<*>} - 返回更新后的记录
147
+ */
148
+ findAndModify(query, update) {
149
+ return this.knex(this.model).where(query).update(update);
150
+ }
151
+
152
+ /**
153
+ *
154
+ * @param {*} id - id
155
+ * @param {*} update - {<key>:<value>}
156
+ * @returns {Promise<*>} - 返回更新后的记录
157
+ */
158
+ findByIdAndUpdate(id, update) {
159
+ return this.knex(this.model).where('id', id).update(update);
160
+ }
161
+
162
+ /**
163
+ * @description 根据条件更新记录
164
+ * @param {*} query - {<key>:<value>}
165
+ * @param {*} update - {<key>:<value>}
166
+ * @returns {Promise} - 返回更新后的记录
167
+ */
168
+ findOneAndUpdate(query, update) {
169
+ return this.knex(this.model).where(query).update(update);
170
+ }
171
+
172
+ /**
173
+ * @description 根据id删除一条记录
174
+ * @param {*} id - 记录id
175
+ * @returns {Promise} - 返回删除的记录
176
+ */
177
+ findByIdAndRemove(id) {
178
+ return this.knex(this.model).where('id', id).del();
179
+ }
180
+
181
+ /**
182
+ * @description 根据条件删除一条记录
183
+ * @param {*} query
184
+ * @returns {Promise} - 返回删除的记录
185
+ */
186
+ findOneAndRemove(query) {
187
+ return this.knex(this.model).where(query).del();
188
+ }
189
+ }
190
+
191
+ const Service = (knex, model='') => {
192
+ return new BaseService(knex, model);
193
+ };
194
+
195
+ module.exports = Service;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chanjs",
3
- "version": "1.0.21",
3
+ "version": "1.0.23",
4
4
  "description": "Chan.js基于express 纯js研发的轻量级mvc框架。",
5
5
  "main": "core/chan.js",
6
6
  "module": "core/chan.js",
@@ -22,5 +22,8 @@
22
22
  "knex": "^3.1.0",
23
23
  "morgan": "^1.10.0",
24
24
  "mysql2": "^3.11.0"
25
- }
25
+ },
26
+ "__npminstall_done": true,
27
+ "_from": "chanjs@1.0.22",
28
+ "_resolved": "https://registry.npmmirror.com/chanjs/-/chanjs-1.0.22.tgz"
26
29
  }
package/core/lib/base.js DELETED
@@ -1,35 +0,0 @@
1
- const express = require("express");
2
- const cookieParser = require("cookie-parser");
3
- const favicon = require("serve-favicon");
4
- const morgan = require("morgan");
5
- const path = require("path");
6
-
7
- const view = require("./middleware/view.js");
8
- module.exports = async function (app) {
9
-
10
- const { logger,APP_PATH, cookieKey, maxAge } = app.config;
11
- //日志
12
- app.use(morgan(logger.level));
13
-
14
- // favicon 图标
15
- app.use(favicon(path.join(APP_PATH, "public/favicon.ico")));
16
-
17
- //cookie
18
- app.use(cookieParser(cookieKey));
19
-
20
- //解析接口 json & url
21
- app.use(express.json());
22
- app.use(express.urlencoded({ extended: false }));
23
-
24
- //配置模板引擎
25
- view(app);
26
-
27
- //使用静态资源 ,
28
- app.use(
29
- "/public",
30
- express.static(path.join(APP_PATH, "public"), {
31
- maxAge:maxAge,
32
- })
33
- );
34
-
35
- };
@@ -1,13 +0,0 @@
1
- class Base{
2
- constructor(config){
3
- this.config = config;
4
- }
5
-
6
- log(...args){
7
- console.log(...args);
8
- }
9
-
10
- success(){
11
-
12
- }
13
- }
@@ -1,217 +0,0 @@
1
-
2
- /**
3
- * extend controller
4
- */
5
- module.exports = {
6
- /**
7
- * body getter
8
- */
9
- get body() {
10
-
11
- },
12
- /**
13
- * body setter
14
- */
15
- set body(value) {
16
-
17
- },
18
- /**
19
- * get client ip
20
- */
21
- get ip() {
22
-
23
- },
24
- /**
25
- * get client ips
26
- */
27
- get ips() {
28
-
29
- },
30
- /**
31
- * get status code
32
- */
33
- get status() {
34
-
35
- },
36
- /**
37
- * set status code
38
- */
39
- set status(status) {
40
-
41
- },
42
- /**
43
- * get content type
44
- */
45
- get type() {
46
-
47
- },
48
- /**
49
- * set content type
50
- */
51
- set type(contentType) {
52
-
53
- },
54
- /**
55
- * get userAgent header
56
- */
57
- get userAgent() {
58
-
59
- },
60
- /**
61
- * get request method
62
- */
63
- get method() {
64
-
65
- },
66
- /**
67
- * is get method
68
- */
69
- get isGet() {
70
-
71
- },
72
- /**
73
- * is post method
74
- */
75
- get isPost() {
76
-
77
- },
78
- /**
79
- * is command line invoke
80
- */
81
- get isCli() {
82
-
83
- },
84
- /**
85
- * get or set config
86
- * @param {String} name
87
- * @param {Mix} value
88
- * @param {String} m
89
- */
90
- config(name, value, m ) {
91
-
92
- },
93
- /**
94
- * is method
95
- * @param {String} method
96
- */
97
- isMethod(method) {
98
-
99
- },
100
- /**
101
- * check if is ajax request
102
- * @param {String} method
103
- */
104
- isAjax(method) {
105
-
106
- },
107
- /**
108
- * is jsonp request
109
- * @param {String} callback
110
- */
111
- isJsonp(callbackField) {
112
-
113
- },
114
- /**
115
- * send jsonp data
116
- */
117
- jsonp(data, callbackField) {
118
-
119
- },
120
- /**
121
- * send json data
122
- */
123
- json(data) {
124
-
125
- },
126
- /**
127
- * send success data
128
- */
129
- success(data, message) {
130
-
131
- },
132
- /**
133
- * send fail data
134
- */
135
- fail(errno, errmsg, data) {
136
-
137
- },
138
- /**
139
- * set expires header
140
- * @param {Number} time
141
- */
142
- expires(time) {
143
-
144
- },
145
- /**
146
- * get query data
147
- * @param {String} name
148
- * @param {Mixed} value
149
- */
150
- get(name, value) {
151
-
152
- },
153
- /**
154
- * get query data
155
- * @param {String} name
156
- * @param {Mixed} value
157
- */
158
- query(name, value) {
159
-
160
- },
161
- /**
162
- * get or set post data
163
- * @param {String} name
164
- * @param {Mixed} value
165
- */
166
- post(name, value) {
167
-
168
- },
169
- /**
170
- * get or set file data
171
- * @param {String} name
172
- * @param {Mixed} value
173
- */
174
- file(name, value) {
175
-
176
- },
177
- /**
178
- * get or set cookies
179
- * @param {String} name
180
- * @param {String} value
181
- * @param {Object} options
182
- */
183
- cookie(name, value, options) {
184
-
185
- },
186
-
187
- /**
188
- * get referer header
189
- */
190
- referrer(onlyHost) {
191
-
192
- },
193
- /**
194
- * get referer header
195
- */
196
- referer(onlyHost) {
197
-
198
- },
199
- /**
200
- * Perform a 302 redirect to `url`.
201
- * @param {String} url
202
- * @param {String} alt
203
- */
204
- redirect(url, alt) {
205
-
206
- },
207
-
208
-
209
- /**
210
- * download
211
- * @param {String} filepath
212
- * @param {String} filename
213
- */
214
- download(filepath, filename) {
215
-
216
- }
217
- };
@@ -1,31 +0,0 @@
1
- const path = require("path");
2
- const dealRouter = (app,router) => {
3
-
4
- const {config:{template='default',APP_PATH}} = app;
5
- //机器人抓取
6
- router.get("/robots.txt", function (req, res, next) {
7
- res.type('text/plain');
8
- res.sendFile(path.join(APP_PATH, "/public/robots.txt"));
9
- });
10
-
11
- //404处理
12
- router.use((req, res, next) => {
13
- let ip = req.headers["x-forwarded-for"] || req.ip;
14
- console.log("404-->", `${req.method}-${decodeURI(req.url)}-${ip}`);
15
- res.render(`${template}/404.html`);
16
- });
17
-
18
- //处理错误
19
- router.use((err, req, res) => {
20
- console.error("500-->", req.method, req.url, err);
21
- let data = { url: req.url, method: req.method, error: err.message };
22
- if (req.is("html") || req.is("html") == null) {
23
- res.render(`${template}/500.html`, { data });
24
- } else {
25
- res.json({ code: 500, data, msg: data.error });
26
- }
27
- });
28
-
29
- };
30
-
31
- module.exports = dealRouter;
File without changes