koatty 3.6.0-1 → 3.6.3

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [3.6.3](https://github.com/thinkkoa/koatty/compare/v3.6.2...v3.6.3) (2022-02-25)
6
+
7
+ ### [3.6.2](https://github.com/thinkkoa/koatty/compare/v3.6.0...v3.6.2) (2022-02-23)
8
+
9
+ ## [3.6.0](https://github.com/thinkkoa/koatty/compare/v3.6.0-1...v3.6.0) (2022-02-22)
10
+
5
11
  ## [3.6.0-1](https://github.com/thinkkoa/koatty/compare/v3.6.0-0...v3.6.0-1) (2022-02-21)
6
12
 
7
13
  ## [3.6.0-0](https://github.com/thinkkoa/koatty/compare/v3.5.16...v3.6.0-0) (2022-02-21)
package/README.md CHANGED
@@ -51,33 +51,18 @@ koatty service test
51
51
 
52
52
  ```
53
53
 
54
- ### 3.Create a Middleware (Optional)
55
-
56
- ```shell
57
- koatty middleware test
58
-
59
- ```
60
- ### 4.Create a Model(Optional)
61
-
62
- Supports [typeorm](https://github.com/typeorm/typeorm). Please expand other ORM by yourself.
63
-
64
- ```shell
65
- //typeorm
66
- koatty middleware test
67
-
68
- ```
69
-
70
- ### 5.Create a DTOClass (Optional)
54
+ ### 4.Create a DTOClass (Optional)
71
55
 
72
56
  ```shell
73
57
  koatty dto test
74
58
 
75
59
  ```
76
60
 
77
- ### 6.Define TestController
61
+ ### 5.Define TestController
78
62
 
79
63
  ```javascript
80
- import { Controller, BaseController, Autowired, GetMapping, RequestBody, PathVariable, PostMapping, RequestMapping, RequestMethod, Valid } from "koatty";
64
+ import { Controller, BaseController, Autowired, GetMapping, RequestBody, PathVariable,
65
+ PostMapping, RequestMapping, RequestMethod, Valid } from "koatty";
81
66
  import { TestDTO } from "../model/dto/TestDTO";
82
67
  import { TestService } from "../service/TestService";
83
68
  import { App } from "../App";
@@ -111,6 +96,33 @@ export class IndexController extends BaseController {
111
96
  }
112
97
  ```
113
98
 
99
+ ## How to do Unit Testing
100
+
101
+ >now only support `jest` UT framework
102
+
103
+ ```javascript
104
+ import request from 'supertest';
105
+ import { ExecBootStrap } from 'koatty';
106
+
107
+ import { App } from '../src/App';
108
+
109
+ describe('UT example', () => {
110
+
111
+ let server;
112
+ beforeAll(async () => {
113
+ const appInstance = await ExecBootStrap()(App);
114
+ server = appInstance.callback();
115
+ });
116
+
117
+ it('request', async (done) => {
118
+ const rsp = await request(server).get('/path/to/server');
119
+ expect(rsp.status).toBe(200);
120
+ done();
121
+ });
122
+ });
123
+
124
+ ```
125
+
114
126
  ## How to debug
115
127
 
116
128
  if you use vscode , edit the `.vscode/launch.json` , like this:
package/dist/README.md CHANGED
@@ -51,33 +51,18 @@ koatty service test
51
51
 
52
52
  ```
53
53
 
54
- ### 3.Create a Middleware (Optional)
55
-
56
- ```shell
57
- koatty middleware test
58
-
59
- ```
60
- ### 4.Create a Model(Optional)
61
-
62
- Supports [typeorm](https://github.com/typeorm/typeorm). Please expand other ORM by yourself.
63
-
64
- ```shell
65
- //typeorm
66
- koatty middleware test
67
-
68
- ```
69
-
70
- ### 5.Create a DTOClass (Optional)
54
+ ### 4.Create a DTOClass (Optional)
71
55
 
72
56
  ```shell
73
57
  koatty dto test
74
58
 
75
59
  ```
76
60
 
77
- ### 6.Define TestController
61
+ ### 5.Define TestController
78
62
 
79
63
  ```javascript
80
- import { Controller, BaseController, Autowired, GetMapping, RequestBody, PathVariable, PostMapping, RequestMapping, RequestMethod, Valid } from "koatty";
64
+ import { Controller, BaseController, Autowired, GetMapping, RequestBody, PathVariable,
65
+ PostMapping, RequestMapping, RequestMethod, Valid } from "koatty";
81
66
  import { TestDTO } from "../model/dto/TestDTO";
82
67
  import { TestService } from "../service/TestService";
83
68
  import { App } from "../App";
@@ -111,6 +96,33 @@ export class IndexController extends BaseController {
111
96
  }
112
97
  ```
113
98
 
99
+ ## How to do Unit Testing
100
+
101
+ >now only support `jest` UT framework
102
+
103
+ ```javascript
104
+ import request from 'supertest';
105
+ import { ExecBootStrap } from 'koatty';
106
+
107
+ import { App } from '../src/App';
108
+
109
+ describe('UT example', () => {
110
+
111
+ let server;
112
+ beforeAll(async () => {
113
+ const appInstance = await ExecBootStrap()(App);
114
+ server = appInstance.callback();
115
+ });
116
+
117
+ it('request', async (done) => {
118
+ const rsp = await request(server).get('/path/to/server');
119
+ expect(rsp.status).toBe(200);
120
+ done();
121
+ });
122
+ });
123
+
124
+ ```
125
+
114
126
  ## How to debug
115
127
 
116
128
  if you use vscode , edit the `.vscode/launch.json` , like this:
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
2
  * @Author: richen
3
- * @Date: 2022-02-21 18:29:33
3
+ * @Date: 2022-02-25 14:16:40
4
4
  * @License: BSD (3-Clause)
5
5
  * @Copyright (c) - <richenlin(at)gmail.com>
6
6
  * @HomePage: https://koatty.org/
@@ -164,6 +164,15 @@ export declare function ConfigurationScan(scanPath?: string | string[]): ClassDe
164
164
  */
165
165
  export declare function Controller(path?: string): ClassDecorator;
166
166
 
167
+ /**
168
+ * Actively perform dependency injection
169
+ * Parse the decorator, return the instantiated app.
170
+ * @export ExecBootStrap
171
+ * @param {Function} [bootFunc] callback function
172
+ * @returns
173
+ */
174
+ export declare function ExecBootStrap(bootFunc?: Function): (target: any) => Promise<void>;
175
+
167
176
  export { Helper }
168
177
 
169
178
  /**
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
2
  * @Author: richen
3
- * @Date: 2022-02-21 18:29:18
3
+ * @Date: 2022-02-25 14:16:22
4
4
  * @License: BSD (3-Clause)
5
5
  * @Copyright (c) - <richenlin(at)gmail.com>
6
6
  * @HomePage: https://koatty.org/
@@ -11,10 +11,11 @@ Object.defineProperty(exports, '__esModule', { value: true });
11
11
 
12
12
  var koatty_lib = require('koatty_lib');
13
13
  require('reflect-metadata');
14
- var koatty_router = require('koatty_router');
14
+ var fs = require('fs');
15
15
  var koatty_core = require('koatty_core');
16
- var koatty_serve = require('koatty_serve');
16
+ var koatty_router = require('koatty_router');
17
17
  var koatty_container = require('koatty_container');
18
+ var koatty_serve = require('koatty_serve');
18
19
  var path = require('path');
19
20
  var koatty_loader = require('koatty_loader');
20
21
  var koatty_config = require('koatty_config');
@@ -23,6 +24,8 @@ var koatty_exception = require('koatty_exception');
23
24
  var koatty_trace = require('koatty_trace');
24
25
  var koatty_payload = require('koatty_payload');
25
26
 
27
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
28
+
26
29
  function _interopNamespace(e) {
27
30
  if (e && e.__esModule) return e;
28
31
  var n = Object.create(null);
@@ -41,6 +44,7 @@ function _interopNamespace(e) {
41
44
  return Object.freeze(n);
42
45
  }
43
46
 
47
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
44
48
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
45
49
 
46
50
  /**
@@ -446,14 +450,14 @@ const Logger = koatty_logger.DefaultLogger;
446
450
  * logFilePath?: string;
447
451
  * }} config
448
452
  */
449
- function SetLogger(config) {
453
+ function SetLogger(app, config) {
450
454
  if (config.logLevel !== undefined) {
451
455
  koatty_logger.DefaultLogger.setLevel(config.logLevel);
452
456
  }
453
- if (config.logConsole !== undefined) {
457
+ if (config.logConsole !== undefined && !app.silent) {
454
458
  koatty_logger.DefaultLogger.setLogConsole(config.logConsole);
455
459
  }
456
- if (config.logFile !== undefined) {
460
+ if (config.logFile !== undefined && !app.silent) {
457
461
  koatty_logger.DefaultLogger.setLogFile(config.logFile);
458
462
  koatty_logger.DefaultLogger.setLogFilePath(config.logFilePath);
459
463
  }
@@ -650,7 +654,7 @@ class Loader {
650
654
  if (opt.logs_path) {
651
655
  logFilePath = opt.logs_path;
652
656
  }
653
- SetLogger({ logLevel, logConsole, logFile, logFileLevel, logFilePath });
657
+ SetLogger(app, { logLevel, logConsole, logFile, logFileLevel, logFilePath });
654
658
  }
655
659
  }
656
660
  /**
@@ -721,13 +725,13 @@ class Loader {
721
725
  });
722
726
  const middlewareConfList = middlewareConf.list;
723
727
  const defaultList = ["TraceMiddleware", "PayloadMiddleware"];
728
+ //de-duplication
729
+ const appMList = new Set(defaultList);
724
730
  middlewareConfList.forEach((item) => {
725
731
  if (!defaultList.includes(item)) {
726
- defaultList.push(item);
732
+ appMList.add(item);
727
733
  }
728
734
  });
729
- //de-duplication
730
- const appMList = [...new Set(defaultList)];
731
735
  //Automatically call middleware
732
736
  for (const key of appMList) {
733
737
  const handle = koatty_container.IOCContainer.get(key, "MIDDLEWARE");
@@ -868,7 +872,7 @@ class Loader {
868
872
  }
869
873
  }
870
874
 
871
- var version = "3.6.0-1";
875
+ var version = "3.6.3";
872
876
  var engines = {
873
877
  node: ">12.0.0"
874
878
  };
@@ -878,7 +882,7 @@ var engines = {
878
882
  * @Usage:
879
883
  * @Author: richen
880
884
  * @Date: 2021-12-17 11:54:06
881
- * @LastEditTime: 2021-12-17 13:13:00
885
+ * @LastEditTime: 2022-02-23 16:12:34
882
886
  */
883
887
  const KOATTY_VERSION = version;
884
888
  const ENGINES_VERSION = engines.node.slice(1) || '12.0.0';
@@ -898,7 +902,21 @@ function checkRuntime() {
898
902
  Logger.Error(`Koatty need node version > ${nodeEngines}, current version is ${nodeVersion}, please upgrade it.`);
899
903
  process.exit(-1);
900
904
  }
901
- }
905
+ }
906
+ /**
907
+ * unittest running environment detection
908
+ * only support jest
909
+ * @returns {boolean}
910
+ */
911
+ const checkUTRuntime = () => {
912
+ let isUTRuntime = false;
913
+ // UT运行环境判断,暂时先只判断jest
914
+ const argv = JSON.stringify(process.argv[1]);
915
+ if (argv.indexOf('jest') > -1) {
916
+ isUTRuntime = true;
917
+ }
918
+ return isUTRuntime;
919
+ };
902
920
 
903
921
  /**
904
922
  * @ author: richen
@@ -911,14 +929,27 @@ function checkRuntime() {
911
929
  *
912
930
  * @param {*} target
913
931
  * @param {Function} bootFunc
932
+ * @param {boolean} [isInitiative=false] Whether to actively execute app instantiation,
933
+ * mainly for unittest scenarios, you need to actively obtain app instances
914
934
  * @returns {Promise<void>}
915
935
  */
916
- const ExecBootstrap = async function (target, bootFunc) {
936
+ const executeBootstrap = async function (target, bootFunc, isInitiative = false) {
917
937
  // checked runtime
918
938
  checkRuntime();
939
+ // unittest running environment
940
+ const isUTRuntime = checkUTRuntime();
941
+ if (!isInitiative && isUTRuntime) {
942
+ return;
943
+ }
919
944
  const app = Reflect.construct(target, []);
945
+ // unittest does not print startup logs
946
+ if (isUTRuntime) {
947
+ app.silent = true;
948
+ Logger.setLogConsole(false);
949
+ Logger.setLogFile(false);
950
+ }
920
951
  try {
921
- console.log(LOGO);
952
+ !app.silent && console.log(LOGO);
922
953
  if (!(app instanceof koatty_core.Koatty)) {
923
954
  throw new Error(`class ${target.name} does not inherit from Koatty`);
924
955
  }
@@ -971,14 +1002,14 @@ const ExecBootstrap = async function (target, bootFunc) {
971
1002
  // Load Routers
972
1003
  Logger.Log('think', '', 'Load Routers ...');
973
1004
  KoattyRouter.LoadRouter(app.getMetaData("_controllers"));
974
- // Emit app started event
975
- Logger.Log('think', '', 'Emit App Start ...');
976
- // app.emit("appStart");
977
- const server = newServe(app);
978
- await asyncEvent(app, 'appStart');
979
1005
  Logger.Log('think', '', '====================================');
980
1006
  // Start server
981
- app.listen(server);
1007
+ const server = newServe(app);
1008
+ app.listen(server, listenCallback(app, server.options));
1009
+ // app.emit("appStart");
1010
+ // Emit app started event
1011
+ Logger.Log('think', '', 'Emit App Start ...');
1012
+ asyncEvent(app, 'appStart');
982
1013
  // binding event "appStop"
983
1014
  koatty_serve.BindProcessEvent(app, 'appStop');
984
1015
  }
@@ -1002,6 +1033,24 @@ const newRouter = function (app) {
1002
1033
  koatty_lib.Helper.define(app, "router", router);
1003
1034
  return router;
1004
1035
  };
1036
+ /**
1037
+ * Listening callback function
1038
+ *
1039
+ * @param {Koatty} app
1040
+ * @param {ListeningOptions} options
1041
+ * @returns {*}
1042
+ */
1043
+ const listenCallback = (app, options) => {
1044
+ return function () {
1045
+ Logger.Log("think", "", `Nodejs Version: ${process.version}`);
1046
+ Logger.Log("think", "", `Koatty Version: v${app.version}`);
1047
+ Logger.Log("think", "", `App Environment: ${app.env}`);
1048
+ Logger.Log("think", "", `Server running at ${options.protocol === "http2" ? "https" : options.protocol}://${options.hostname || '127.0.0.1'}:${options.port}/`);
1049
+ Logger.Log("think", "", "====================================");
1050
+ // tslint:disable-next-line: no-unused-expression
1051
+ app.appDebug && Logger.Warn(`Running in debug mode.`);
1052
+ };
1053
+ };
1005
1054
  /**
1006
1055
  * create serve
1007
1056
  *
@@ -1009,8 +1058,37 @@ const newRouter = function (app) {
1009
1058
  * @returns {*}
1010
1059
  */
1011
1060
  const newServe = function (app) {
1061
+ var _a, _b, _c;
1012
1062
  const protocol = app.config("protocol") || "http";
1013
- const server = koatty_serve.Serve(app, protocol);
1063
+ const port = process.env.PORT || process.env.APP_PORT ||
1064
+ app.config('app_port') || 3000;
1065
+ const hostname = process.env.IP ||
1066
+ ((_a = process.env.HOSTNAME) === null || _a === void 0 ? void 0 : _a.replace(/-/g, '.')) || app.config('app_host') || '127.0.0.1';
1067
+ const options = {
1068
+ hostname,
1069
+ port,
1070
+ protocol,
1071
+ ext: {
1072
+ key: "",
1073
+ cert: "",
1074
+ protoFile: "",
1075
+ },
1076
+ };
1077
+ const pm = new Set(["https", "http2", "wss"]);
1078
+ if (pm.has(options.protocol)) {
1079
+ const keyFile = (_b = app.config("key_file")) !== null && _b !== void 0 ? _b : "";
1080
+ const crtFile = (_c = app.config("crt_file")) !== null && _c !== void 0 ? _c : "";
1081
+ options.ext.key = fs__default["default"].readFileSync(keyFile).toString();
1082
+ options.ext.cert = fs__default["default"].readFileSync(crtFile).toString();
1083
+ }
1084
+ if (options.protocol === "https" || options.protocol === "http2") {
1085
+ options.port = options.port == 80 ? 443 : options.port;
1086
+ }
1087
+ if (options.protocol === "grpc") {
1088
+ const proto = app.config("protoFile", "router");
1089
+ options.ext.protoFile = proto;
1090
+ }
1091
+ const server = koatty_serve.Serve(app, options);
1014
1092
  koatty_lib.Helper.define(app, "server", server);
1015
1093
  return server;
1016
1094
  };
@@ -1042,7 +1120,22 @@ function Bootstrap(bootFunc) {
1042
1120
  if (!(target.prototype instanceof koatty_core.Koatty)) {
1043
1121
  throw new Error(`class does not inherit from Koatty`);
1044
1122
  }
1045
- ExecBootstrap(target, bootFunc);
1123
+ executeBootstrap(target, bootFunc);
1124
+ };
1125
+ }
1126
+ /**
1127
+ * Actively perform dependency injection
1128
+ * Parse the decorator, return the instantiated app.
1129
+ * @export ExecBootStrap
1130
+ * @param {Function} [bootFunc] callback function
1131
+ * @returns
1132
+ */
1133
+ function ExecBootStrap(bootFunc) {
1134
+ return async (target) => {
1135
+ if (!(target.prototype instanceof koatty_core.Koatty)) {
1136
+ throw new Error(`class ${target.name} does not inherit from TKoatty`);
1137
+ }
1138
+ return await executeBootstrap(target, bootFunc, true);
1046
1139
  };
1047
1140
  }
1048
1141
  /**
@@ -1220,27 +1313,22 @@ exports.Component = Component;
1220
1313
  exports.ComponentScan = ComponentScan;
1221
1314
  exports.ConfigurationScan = ConfigurationScan;
1222
1315
  exports.Controller = Controller;
1316
+ exports.ExecBootStrap = ExecBootStrap;
1223
1317
  exports.HttpController = HttpController;
1224
1318
  exports.Logger = Logger;
1225
1319
  exports.Middleware = Middleware;
1226
1320
  exports.Plugin = Plugin;
1227
1321
  exports.Service = Service;
1228
- Object.keys(koatty_router).forEach(function (k) {
1229
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1230
- enumerable: true,
1231
- get: function () { return koatty_router[k]; }
1232
- });
1233
- });
1234
1322
  Object.keys(koatty_core).forEach(function (k) {
1235
1323
  if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1236
1324
  enumerable: true,
1237
1325
  get: function () { return koatty_core[k]; }
1238
1326
  });
1239
1327
  });
1240
- Object.keys(koatty_serve).forEach(function (k) {
1328
+ Object.keys(koatty_router).forEach(function (k) {
1241
1329
  if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1242
1330
  enumerable: true,
1243
- get: function () { return koatty_serve[k]; }
1331
+ get: function () { return koatty_router[k]; }
1244
1332
  });
1245
1333
  });
1246
1334
  Object.keys(koatty_container).forEach(function (k) {
@@ -1249,6 +1337,12 @@ Object.keys(koatty_container).forEach(function (k) {
1249
1337
  get: function () { return koatty_container[k]; }
1250
1338
  });
1251
1339
  });
1340
+ Object.keys(koatty_serve).forEach(function (k) {
1341
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1342
+ enumerable: true,
1343
+ get: function () { return koatty_serve[k]; }
1344
+ });
1345
+ });
1252
1346
  Object.keys(koatty_exception).forEach(function (k) {
1253
1347
  if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1254
1348
  enumerable: true,
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
2
  * @Author: richen
3
- * @Date: 2022-02-21 18:29:18
3
+ * @Date: 2022-02-25 14:16:22
4
4
  * @License: BSD (3-Clause)
5
5
  * @Copyright (c) - <richenlin(at)gmail.com>
6
6
  * @HomePage: https://koatty.org/
@@ -8,14 +8,15 @@
8
8
  import { Helper } from 'koatty_lib';
9
9
  export { Helper } from 'koatty_lib';
10
10
  import 'reflect-metadata';
11
- import { NewRouter, CONTROLLER_ROUTER } from 'koatty_router';
12
- export * from 'koatty_router';
11
+ import fs from 'fs';
13
12
  import { Koatty } from 'koatty_core';
14
13
  export * from 'koatty_core';
15
- import { BindProcessEvent, Serve } from 'koatty_serve';
16
- export * from 'koatty_serve';
14
+ import { NewRouter, CONTROLLER_ROUTER } from 'koatty_router';
15
+ export * from 'koatty_router';
17
16
  import { IOCContainer, TAGGED_CLS } from 'koatty_container';
18
17
  export * from 'koatty_container';
18
+ import { BindProcessEvent, Serve } from 'koatty_serve';
19
+ export * from 'koatty_serve';
19
20
  import * as path from 'path';
20
21
  import { Load } from 'koatty_loader';
21
22
  import { LoadConfigs } from 'koatty_config';
@@ -429,14 +430,14 @@ const Logger = DefaultLogger;
429
430
  * logFilePath?: string;
430
431
  * }} config
431
432
  */
432
- function SetLogger(config) {
433
+ function SetLogger(app, config) {
433
434
  if (config.logLevel !== undefined) {
434
435
  DefaultLogger.setLevel(config.logLevel);
435
436
  }
436
- if (config.logConsole !== undefined) {
437
+ if (config.logConsole !== undefined && !app.silent) {
437
438
  DefaultLogger.setLogConsole(config.logConsole);
438
439
  }
439
- if (config.logFile !== undefined) {
440
+ if (config.logFile !== undefined && !app.silent) {
440
441
  DefaultLogger.setLogFile(config.logFile);
441
442
  DefaultLogger.setLogFilePath(config.logFilePath);
442
443
  }
@@ -633,7 +634,7 @@ class Loader {
633
634
  if (opt.logs_path) {
634
635
  logFilePath = opt.logs_path;
635
636
  }
636
- SetLogger({ logLevel, logConsole, logFile, logFileLevel, logFilePath });
637
+ SetLogger(app, { logLevel, logConsole, logFile, logFileLevel, logFilePath });
637
638
  }
638
639
  }
639
640
  /**
@@ -704,13 +705,13 @@ class Loader {
704
705
  });
705
706
  const middlewareConfList = middlewareConf.list;
706
707
  const defaultList = ["TraceMiddleware", "PayloadMiddleware"];
708
+ //de-duplication
709
+ const appMList = new Set(defaultList);
707
710
  middlewareConfList.forEach((item) => {
708
711
  if (!defaultList.includes(item)) {
709
- defaultList.push(item);
712
+ appMList.add(item);
710
713
  }
711
714
  });
712
- //de-duplication
713
- const appMList = [...new Set(defaultList)];
714
715
  //Automatically call middleware
715
716
  for (const key of appMList) {
716
717
  const handle = IOCContainer.get(key, "MIDDLEWARE");
@@ -851,7 +852,7 @@ class Loader {
851
852
  }
852
853
  }
853
854
 
854
- var version = "3.6.0-1";
855
+ var version = "3.6.3";
855
856
  var engines = {
856
857
  node: ">12.0.0"
857
858
  };
@@ -861,7 +862,7 @@ var engines = {
861
862
  * @Usage:
862
863
  * @Author: richen
863
864
  * @Date: 2021-12-17 11:54:06
864
- * @LastEditTime: 2021-12-17 13:13:00
865
+ * @LastEditTime: 2022-02-23 16:12:34
865
866
  */
866
867
  const KOATTY_VERSION = version;
867
868
  const ENGINES_VERSION = engines.node.slice(1) || '12.0.0';
@@ -881,7 +882,21 @@ function checkRuntime() {
881
882
  Logger.Error(`Koatty need node version > ${nodeEngines}, current version is ${nodeVersion}, please upgrade it.`);
882
883
  process.exit(-1);
883
884
  }
884
- }
885
+ }
886
+ /**
887
+ * unittest running environment detection
888
+ * only support jest
889
+ * @returns {boolean}
890
+ */
891
+ const checkUTRuntime = () => {
892
+ let isUTRuntime = false;
893
+ // UT运行环境判断,暂时先只判断jest
894
+ const argv = JSON.stringify(process.argv[1]);
895
+ if (argv.indexOf('jest') > -1) {
896
+ isUTRuntime = true;
897
+ }
898
+ return isUTRuntime;
899
+ };
885
900
 
886
901
  /**
887
902
  * @ author: richen
@@ -894,14 +909,27 @@ function checkRuntime() {
894
909
  *
895
910
  * @param {*} target
896
911
  * @param {Function} bootFunc
912
+ * @param {boolean} [isInitiative=false] Whether to actively execute app instantiation,
913
+ * mainly for unittest scenarios, you need to actively obtain app instances
897
914
  * @returns {Promise<void>}
898
915
  */
899
- const ExecBootstrap = async function (target, bootFunc) {
916
+ const executeBootstrap = async function (target, bootFunc, isInitiative = false) {
900
917
  // checked runtime
901
918
  checkRuntime();
919
+ // unittest running environment
920
+ const isUTRuntime = checkUTRuntime();
921
+ if (!isInitiative && isUTRuntime) {
922
+ return;
923
+ }
902
924
  const app = Reflect.construct(target, []);
925
+ // unittest does not print startup logs
926
+ if (isUTRuntime) {
927
+ app.silent = true;
928
+ Logger.setLogConsole(false);
929
+ Logger.setLogFile(false);
930
+ }
903
931
  try {
904
- console.log(LOGO);
932
+ !app.silent && console.log(LOGO);
905
933
  if (!(app instanceof Koatty)) {
906
934
  throw new Error(`class ${target.name} does not inherit from Koatty`);
907
935
  }
@@ -954,14 +982,14 @@ const ExecBootstrap = async function (target, bootFunc) {
954
982
  // Load Routers
955
983
  Logger.Log('think', '', 'Load Routers ...');
956
984
  KoattyRouter.LoadRouter(app.getMetaData("_controllers"));
957
- // Emit app started event
958
- Logger.Log('think', '', 'Emit App Start ...');
959
- // app.emit("appStart");
960
- const server = newServe(app);
961
- await asyncEvent(app, 'appStart');
962
985
  Logger.Log('think', '', '====================================');
963
986
  // Start server
964
- app.listen(server);
987
+ const server = newServe(app);
988
+ app.listen(server, listenCallback(app, server.options));
989
+ // app.emit("appStart");
990
+ // Emit app started event
991
+ Logger.Log('think', '', 'Emit App Start ...');
992
+ asyncEvent(app, 'appStart');
965
993
  // binding event "appStop"
966
994
  BindProcessEvent(app, 'appStop');
967
995
  }
@@ -985,6 +1013,24 @@ const newRouter = function (app) {
985
1013
  Helper.define(app, "router", router);
986
1014
  return router;
987
1015
  };
1016
+ /**
1017
+ * Listening callback function
1018
+ *
1019
+ * @param {Koatty} app
1020
+ * @param {ListeningOptions} options
1021
+ * @returns {*}
1022
+ */
1023
+ const listenCallback = (app, options) => {
1024
+ return function () {
1025
+ Logger.Log("think", "", `Nodejs Version: ${process.version}`);
1026
+ Logger.Log("think", "", `Koatty Version: v${app.version}`);
1027
+ Logger.Log("think", "", `App Environment: ${app.env}`);
1028
+ Logger.Log("think", "", `Server running at ${options.protocol === "http2" ? "https" : options.protocol}://${options.hostname || '127.0.0.1'}:${options.port}/`);
1029
+ Logger.Log("think", "", "====================================");
1030
+ // tslint:disable-next-line: no-unused-expression
1031
+ app.appDebug && Logger.Warn(`Running in debug mode.`);
1032
+ };
1033
+ };
988
1034
  /**
989
1035
  * create serve
990
1036
  *
@@ -992,8 +1038,37 @@ const newRouter = function (app) {
992
1038
  * @returns {*}
993
1039
  */
994
1040
  const newServe = function (app) {
1041
+ var _a, _b, _c;
995
1042
  const protocol = app.config("protocol") || "http";
996
- const server = Serve(app, protocol);
1043
+ const port = process.env.PORT || process.env.APP_PORT ||
1044
+ app.config('app_port') || 3000;
1045
+ const hostname = process.env.IP ||
1046
+ ((_a = process.env.HOSTNAME) === null || _a === void 0 ? void 0 : _a.replace(/-/g, '.')) || app.config('app_host') || '127.0.0.1';
1047
+ const options = {
1048
+ hostname,
1049
+ port,
1050
+ protocol,
1051
+ ext: {
1052
+ key: "",
1053
+ cert: "",
1054
+ protoFile: "",
1055
+ },
1056
+ };
1057
+ const pm = new Set(["https", "http2", "wss"]);
1058
+ if (pm.has(options.protocol)) {
1059
+ const keyFile = (_b = app.config("key_file")) !== null && _b !== void 0 ? _b : "";
1060
+ const crtFile = (_c = app.config("crt_file")) !== null && _c !== void 0 ? _c : "";
1061
+ options.ext.key = fs.readFileSync(keyFile).toString();
1062
+ options.ext.cert = fs.readFileSync(crtFile).toString();
1063
+ }
1064
+ if (options.protocol === "https" || options.protocol === "http2") {
1065
+ options.port = options.port == 80 ? 443 : options.port;
1066
+ }
1067
+ if (options.protocol === "grpc") {
1068
+ const proto = app.config("protoFile", "router");
1069
+ options.ext.protoFile = proto;
1070
+ }
1071
+ const server = Serve(app, options);
997
1072
  Helper.define(app, "server", server);
998
1073
  return server;
999
1074
  };
@@ -1025,7 +1100,22 @@ function Bootstrap(bootFunc) {
1025
1100
  if (!(target.prototype instanceof Koatty)) {
1026
1101
  throw new Error(`class does not inherit from Koatty`);
1027
1102
  }
1028
- ExecBootstrap(target, bootFunc);
1103
+ executeBootstrap(target, bootFunc);
1104
+ };
1105
+ }
1106
+ /**
1107
+ * Actively perform dependency injection
1108
+ * Parse the decorator, return the instantiated app.
1109
+ * @export ExecBootStrap
1110
+ * @param {Function} [bootFunc] callback function
1111
+ * @returns
1112
+ */
1113
+ function ExecBootStrap(bootFunc) {
1114
+ return async (target) => {
1115
+ if (!(target.prototype instanceof Koatty)) {
1116
+ throw new Error(`class ${target.name} does not inherit from TKoatty`);
1117
+ }
1118
+ return await executeBootstrap(target, bootFunc, true);
1029
1119
  };
1030
1120
  }
1031
1121
  /**
@@ -1183,4 +1273,4 @@ class BaseService {
1183
1273
  }
1184
1274
  }
1185
1275
 
1186
- export { BaseController, BaseService, BindAppReadyHook, Bootstrap, Component, ComponentScan, ConfigurationScan, Controller, HttpController, Logger, Middleware, Plugin, Service };
1276
+ export { BaseController, BaseService, BindAppReadyHook, Bootstrap, Component, ComponentScan, ConfigurationScan, Controller, ExecBootStrap, HttpController, Logger, Middleware, Plugin, Service };
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koatty",
3
- "version": "3.6.0-1",
3
+ "version": "3.6.3",
4
4
  "description": "Koa2 + Typescript = koatty. Use Typescript's decorator implement auto injection.",
5
5
  "scripts": {
6
6
  "build": "npm run build:js && npm run build:dts && npm run build:doc && npm run build:cp",
@@ -15,7 +15,6 @@
15
15
  "release:pre": "npm run release -- --prerelease",
16
16
  "release:major": "npm run release -- --release-as major",
17
17
  "release:minor": "npm run release -- --release-as minor",
18
- "pub": "git push --follow-tags origin && npm publish",
19
18
  "test": "npm run eslint && jest --passWithNoTests",
20
19
  "test:cov": "jest --collectCoverage --detectOpenHandles",
21
20
  "version": "conventional-changelog -p angular -i CHANGELOG.md -s"
@@ -81,18 +80,18 @@
81
80
  "dependencies": {
82
81
  "koa": "2.13.4",
83
82
  "koatty_config": "1.1.2",
84
- "koatty_container": "1.7.4",
85
- "koatty_core": "1.6.0",
83
+ "koatty_container": "1.7.5",
84
+ "koatty_core": "1.6.1",
86
85
  "koatty_exception": "1.2.2",
87
86
  "koatty_lib": "1.2.10",
88
87
  "koatty_loader": "1.0.2",
89
88
  "koatty_logger": "1.3.12",
90
89
  "koatty_payload": "1.3.14",
91
90
  "koatty_proto": "1.1.6",
92
- "koatty_router": "1.7.0",
93
- "koatty_serve": "1.4.6",
91
+ "koatty_router": "1.7.2",
92
+ "koatty_serve": "1.4.8",
94
93
  "koatty_trace": "1.6.1",
95
- "koatty_validation": "1.1.0",
94
+ "koatty_validation": "1.2.2",
96
95
  "reflect-metadata": "0.1.13",
97
96
  "tslib": "2.3.1"
98
97
  }
@@ -1 +1 @@
1
- window.jest_html_reporters_callback__({"numFailedTestSuites":0,"numFailedTests":0,"numPassedTestSuites":0,"numPassedTests":0,"numPendingTestSuites":0,"numPendingTests":0,"numRuntimeErrorTestSuites":0,"numTodoTests":0,"numTotalTestSuites":0,"numTotalTests":0,"startTime":1645439355758,"success":false,"testResults":[],"wasInterrupted":false,"config":{"bail":0,"changedFilesWithAncestor":false,"collectCoverage":true,"collectCoverageFrom":[],"coverageDirectory":"coverage","coverageProvider":"babel","coverageReporters":["html","lcov","json","text","clover","text-summary"],"detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"expand":false,"findRelatedTests":false,"forceExit":false,"json":false,"lastCommit":false,"listTests":false,"logHeapUsage":false,"maxConcurrency":5,"maxWorkers":7,"noStackTrace":false,"nonFlagArgs":[],"notify":false,"notifyMode":"failure-change","onlyChanged":false,"onlyFailures":false,"passWithNoTests":true,"projects":[],"reporters":[["default",{}],["/Users/richen/Workspace/nodejs/koatty/node_modules/jest-html-reporters/index.js",{}]],"rootDir":"/Users/richen/Workspace/nodejs/koatty","runTestsByPath":false,"skipFilter":false,"testFailureExitCode":1,"testPathPattern":"","testSequencer":"/Users/richen/Workspace/nodejs/koatty/node_modules/@jest/test-sequencer/build/index.js","updateSnapshot":"new","useStderr":false,"watch":false,"watchAll":false,"watchman":true},"endTime":1645439355796,"_reporterOptions":{"publicPath":"/Users/richen/Workspace/nodejs/koatty","filename":"jest_html_reporters.html","expand":false,"pageTitle":"","hideIcon":false,"testCommand":"npx jest","openReport":false,"failureMessageOnly":false,"enableMergeData":false,"dataMergeLevel":1},"attachInfos":{}})
1
+ window.jest_html_reporters_callback__({"numFailedTestSuites":0,"numFailedTests":0,"numPassedTestSuites":0,"numPassedTests":0,"numPendingTestSuites":0,"numPendingTests":0,"numRuntimeErrorTestSuites":0,"numTodoTests":0,"numTotalTestSuites":0,"numTotalTests":0,"startTime":1645769779815,"success":false,"testResults":[],"wasInterrupted":false,"config":{"bail":0,"changedFilesWithAncestor":false,"collectCoverage":true,"collectCoverageFrom":[],"coverageDirectory":"coverage","coverageProvider":"babel","coverageReporters":["html","lcov","json","text","clover","text-summary"],"detectLeaks":false,"detectOpenHandles":false,"errorOnDeprecated":false,"expand":false,"findRelatedTests":false,"forceExit":false,"json":false,"lastCommit":false,"listTests":false,"logHeapUsage":false,"maxConcurrency":5,"maxWorkers":7,"noStackTrace":false,"nonFlagArgs":[],"notify":false,"notifyMode":"failure-change","onlyChanged":false,"onlyFailures":false,"passWithNoTests":true,"projects":[],"reporters":[["default",{}],["/Users/richen/Workspace/nodejs/koatty/node_modules/jest-html-reporters/index.js",{}]],"rootDir":"/Users/richen/Workspace/nodejs/koatty","runTestsByPath":false,"skipFilter":false,"testFailureExitCode":1,"testPathPattern":"","testSequencer":"/Users/richen/Workspace/nodejs/koatty/node_modules/@jest/test-sequencer/build/index.js","updateSnapshot":"new","useStderr":false,"watch":false,"watchAll":false,"watchman":true},"endTime":1645769780030,"_reporterOptions":{"publicPath":"/Users/richen/Workspace/nodejs/koatty","filename":"jest_html_reporters.html","expand":false,"pageTitle":"","hideIcon":false,"testCommand":"npx jest","openReport":false,"failureMessageOnly":false,"enableMergeData":false,"dataMergeLevel":1},"attachInfos":{}})
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koatty",
3
- "version": "3.6.0-1",
3
+ "version": "3.6.3",
4
4
  "description": "Koa2 + Typescript = koatty. Use Typescript's decorator implement auto injection.",
5
5
  "scripts": {
6
6
  "build": "npm run build:js && npm run build:dts && npm run build:doc && npm run build:cp",
@@ -15,7 +15,6 @@
15
15
  "release:pre": "npm run release -- --prerelease",
16
16
  "release:major": "npm run release -- --release-as major",
17
17
  "release:minor": "npm run release -- --release-as minor",
18
- "pub": "git push --follow-tags origin && npm publish",
19
18
  "test": "npm run eslint && jest --passWithNoTests",
20
19
  "test:cov": "jest --collectCoverage --detectOpenHandles",
21
20
  "version": "conventional-changelog -p angular -i CHANGELOG.md -s"
@@ -81,18 +80,18 @@
81
80
  "dependencies": {
82
81
  "koa": "2.13.4",
83
82
  "koatty_config": "1.1.2",
84
- "koatty_container": "1.7.4",
85
- "koatty_core": "1.6.0",
83
+ "koatty_container": "1.7.5",
84
+ "koatty_core": "1.6.1",
86
85
  "koatty_exception": "1.2.2",
87
86
  "koatty_lib": "1.2.10",
88
87
  "koatty_loader": "1.0.2",
89
88
  "koatty_logger": "1.3.12",
90
89
  "koatty_payload": "1.3.14",
91
90
  "koatty_proto": "1.1.6",
92
- "koatty_router": "1.7.0",
93
- "koatty_serve": "1.4.6",
91
+ "koatty_router": "1.7.2",
92
+ "koatty_serve": "1.4.8",
94
93
  "koatty_trace": "1.6.1",
95
- "koatty_validation": "1.1.0",
94
+ "koatty_validation": "1.2.2",
96
95
  "reflect-metadata": "0.1.13",
97
96
  "tslib": "2.3.1"
98
97
  }