@jayfong/x-server 2.12.14 → 2.12.16

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 (79) hide show
  1. package/lib/_cjs/cli/api_generator.js +20 -54
  2. package/lib/_cjs/cli/build_util.js +16 -45
  3. package/lib/_cjs/cli/cli.js +17 -29
  4. package/lib/_cjs/cli/deploy_util.js +0 -12
  5. package/lib/_cjs/cli/dev_util.js +18 -0
  6. package/lib/_cjs/cli/env_util.js +16 -49
  7. package/lib/_cjs/cli/{register.js → esbuild_register.js} +0 -1
  8. package/lib/_cjs/cli/template_util.js +26 -29
  9. package/lib/_cjs/core/define_bus.js +9 -6
  10. package/lib/_cjs/core/define_cron.js +0 -2
  11. package/lib/_cjs/core/define_handler.js +10 -12
  12. package/lib/_cjs/core/define_hook.js +0 -2
  13. package/lib/_cjs/core/define_server.js +0 -2
  14. package/lib/_cjs/core/define_task.js +7 -13
  15. package/lib/_cjs/core/get_handler_url.js +1 -2
  16. package/lib/_cjs/core/handler.js +8 -29
  17. package/lib/_cjs/core/http_error.js +0 -3
  18. package/lib/_cjs/core/http_header.js +8 -12
  19. package/lib/_cjs/core/server.js +8 -41
  20. package/lib/_cjs/core/types.js +0 -7
  21. package/lib/_cjs/index.js +0 -72
  22. package/lib/_cjs/plugins/cors.js +0 -7
  23. package/lib/_cjs/plugins/file_parser.js +2 -9
  24. package/lib/_cjs/plugins/form_body_parser.js +0 -6
  25. package/lib/_cjs/plugins/ws_parser.js +0 -6
  26. package/lib/_cjs/plugins/xml_parser.js +0 -12
  27. package/lib/_cjs/services/cache.js +18 -58
  28. package/lib/_cjs/services/captcha.js +0 -14
  29. package/lib/_cjs/services/dingtalk.js +0 -14
  30. package/lib/_cjs/services/dispose.js +0 -9
  31. package/lib/_cjs/services/emoji.js +2 -5
  32. package/lib/_cjs/services/jwt.js +0 -21
  33. package/lib/_cjs/services/log.js +0 -17
  34. package/lib/_cjs/services/mail.js +0 -9
  35. package/lib/_cjs/services/pay.js +9 -40
  36. package/lib/_cjs/services/rate_limit.js +0 -12
  37. package/lib/_cjs/services/redis.js +0 -4
  38. package/lib/_cjs/services/request.js +0 -5
  39. package/lib/_cjs/services/sensitive_words.js +13 -19
  40. package/lib/_cjs/x.js +0 -11
  41. package/lib/cli/api_generator.js +20 -42
  42. package/lib/cli/build_util.js +16 -19
  43. package/lib/cli/cli.js +17 -14
  44. package/lib/cli/deploy_util.js +0 -4
  45. package/lib/cli/dev_util.d.ts +8 -0
  46. package/lib/cli/dev_util.js +12 -0
  47. package/lib/cli/env_util.js +16 -37
  48. package/lib/cli/template_util.d.ts +1 -0
  49. package/lib/cli/template_util.js +26 -14
  50. package/lib/core/define_bus.js +7 -5
  51. package/lib/core/define_handler.js +10 -9
  52. package/lib/core/define_task.js +7 -6
  53. package/lib/core/get_handler_url.js +2 -1
  54. package/lib/core/handler.js +9 -22
  55. package/lib/core/http_header.js +6 -9
  56. package/lib/core/server.js +8 -31
  57. package/lib/core/types.js +0 -7
  58. package/lib/index.js +4 -3
  59. package/lib/plugins/cors.js +0 -3
  60. package/lib/plugins/file_parser.js +2 -5
  61. package/lib/plugins/form_body_parser.js +0 -3
  62. package/lib/plugins/ws_parser.js +0 -3
  63. package/lib/plugins/xml_parser.js +0 -10
  64. package/lib/services/cache.js +18 -52
  65. package/lib/services/captcha.js +0 -7
  66. package/lib/services/dingtalk.js +0 -7
  67. package/lib/services/dispose.js +0 -5
  68. package/lib/services/emoji.js +2 -3
  69. package/lib/services/jwt.js +0 -13
  70. package/lib/services/log.js +0 -8
  71. package/lib/services/mail.js +0 -3
  72. package/lib/services/pay.js +9 -30
  73. package/lib/services/rate_limit.js +0 -8
  74. package/lib/services/redis.js +0 -1
  75. package/lib/services/request.js +0 -1
  76. package/lib/services/sensitive_words.js +13 -15
  77. package/package.json +3 -3
  78. /package/lib/cli/{register.d.ts → esbuild_register.d.ts} +0 -0
  79. /package/lib/cli/{register.js → esbuild_register.js} +0 -0
@@ -1,18 +1,12 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
-
5
4
  exports.__esModule = true;
6
5
  exports.EnvUtil = void 0;
7
-
8
6
  var _fsExtra = _interopRequireDefault(require("fs-extra"));
9
-
10
7
  var _nodePath = _interopRequireDefault(require("node:path"));
11
-
12
8
  var _vtils = require("vtils");
13
-
14
9
  var _yaml = require("yaml");
15
-
16
10
  class EnvUtil {
17
11
  static normalizeValue(value) {
18
12
  if (typeof value === 'string') {
@@ -20,27 +14,21 @@ class EnvUtil {
20
14
  const [devValue, prodValue] = value.split(/\s+\|\|\s+/);
21
15
  return (0, _vtils.devOrProd)(() => EnvUtil.normalizeValue(devValue), () => EnvUtil.normalizeValue(prodValue));
22
16
  }
23
-
24
17
  return value === 'true' ? true : value === 'false' ? false : value.startsWith('[') && value.endsWith(']') || value.startsWith('{') && value.endsWith('}') ? JSON.parse(value) : (0, _vtils.isNumeric)(value) ? Number(value) : value;
25
18
  } else if (value && typeof value === 'object') {
26
19
  if (value.dev != null && value.prod != null) {
27
20
  return (0, _vtils.devOrProd)(() => value.dev, () => value.prod);
28
21
  }
29
-
30
22
  return value;
31
23
  }
32
-
33
24
  return value;
34
25
  }
35
-
36
26
  static parseContent(src, isYaml = false) {
37
27
  const envs = [];
38
-
39
28
  if (isYaml) {
40
29
  const envObj = (0, _yaml.parse)(src);
41
30
  Object.keys(envObj).forEach(key => {
42
31
  var _src$match;
43
-
44
32
  envs.push({
45
33
  key: key,
46
34
  value: this.normalizeValue(envObj[key]),
@@ -49,56 +37,54 @@ class EnvUtil {
49
37
  });
50
38
  } else {
51
39
  // https://github.com/andreialecu/dotenv/blob/feat-multiline/lib/main.js
52
- const multilineLineBreaks = true; // convert Buffers before splitting into lines and processing
40
+ const multilineLineBreaks = true;
53
41
 
42
+ // convert Buffers before splitting into lines and processing
54
43
  const lines = src.split(EnvUtil.NEWLINES_MATCH);
55
44
  let lastComment = '';
56
-
57
45
  for (let idx = 0; idx < lines.length; idx++) {
58
- let line = lines[idx]; // matching "KEY' and 'VAL' in 'KEY=VAL'
59
-
60
- const keyValueArr = line.match(EnvUtil.RE_INI_KEY_VAL); // matched?
46
+ let line = lines[idx];
61
47
 
48
+ // matching "KEY' and 'VAL' in 'KEY=VAL'
49
+ const keyValueArr = line.match(EnvUtil.RE_INI_KEY_VAL);
50
+ // matched?
62
51
  if (keyValueArr != null) {
63
- const key = keyValueArr[1]; // default undefined or missing values to empty string
64
-
52
+ const key = keyValueArr[1];
53
+ // default undefined or missing values to empty string
65
54
  let val = keyValueArr[2] || '';
66
55
  let end = val.length - 1;
67
56
  const isDoubleQuoted = val[0] === '"' && val[end] === '"';
68
57
  const isSingleQuoted = val[0] === "'" && val[end] === "'";
69
58
  const isMultilineDoubleQuoted = val[0] === '"' && (val.length === 1 || val[end] !== '"');
70
- const isMultilineSingleQuoted = val[0] === "'" && (val.length === 1 || val[end] !== "'"); // if parsing line breaks and the value starts with a quote
59
+ const isMultilineSingleQuoted = val[0] === "'" && (val.length === 1 || val[end] !== "'");
71
60
 
61
+ // if parsing line breaks and the value starts with a quote
72
62
  if (multilineLineBreaks && (isMultilineDoubleQuoted || isMultilineSingleQuoted)) {
73
63
  const quoteChar = isMultilineDoubleQuoted ? '"' : "'";
74
64
  val = val.substring(1);
75
-
76
65
  while (idx++ < lines.length - 1) {
77
66
  line = lines[idx];
78
67
  end = line.length - 1;
79
-
80
68
  if (line[end] === quoteChar) {
81
69
  val += EnvUtil.NEWLINE + line.substring(0, end);
82
70
  break;
83
71
  }
84
-
85
72
  val += EnvUtil.NEWLINE + line;
86
73
  }
87
-
88
- val = (0, _vtils.dedent)(val); // if single or double quoted, remove quotes
74
+ val = (0, _vtils.dedent)(val);
75
+ // if single or double quoted, remove quotes
89
76
  } else if (isSingleQuoted || isDoubleQuoted) {
90
- val = val.substring(1, end); // if double quoted, expand newlines
77
+ val = val.substring(1, end);
91
78
 
79
+ // if double quoted, expand newlines
92
80
  if (isDoubleQuoted) {
93
81
  val = val.replace(EnvUtil.RE_NEWLINES, EnvUtil.NEWLINE);
94
82
  }
95
-
96
83
  val = (0, _vtils.dedent)(val);
97
84
  } else {
98
85
  // remove surrounding whitespace
99
86
  val = (0, _vtils.dedent)(val).trim();
100
87
  }
101
-
102
88
  envs.push({
103
89
  key: key,
104
90
  value: EnvUtil.normalizeValue(val),
@@ -107,61 +93,47 @@ class EnvUtil {
107
93
  lastComment = '';
108
94
  } else {
109
95
  const commentArr = line.match(EnvUtil.COMMENT_MATCH);
110
-
111
96
  if (commentArr) {
112
97
  lastComment = commentArr[1];
113
98
  }
114
99
  }
115
100
  }
116
101
  }
117
-
118
102
  return envs;
119
103
  }
120
-
121
104
  static async parseFile(options) {
122
105
  const envFile = _nodePath.default.join(options.cwd, options.file);
123
-
124
106
  const envYmlFile = _nodePath.default.join(options.cwd, `${options.file}.yml`);
125
-
126
107
  const envYamlFile = _nodePath.default.join(options.cwd, `${options.file}.yaml`);
127
-
128
108
  const file = (await _fsExtra.default.pathExists(envYmlFile)) ? envYmlFile : (await _fsExtra.default.pathExists(envYamlFile)) ? envYamlFile : (await _fsExtra.default.pathExists(envFile)) ? envFile : '';
129
-
130
109
  if (file) {
131
110
  const envContent = await _fsExtra.default.readFile(file, 'utf-8');
132
111
  const envs = EnvUtil.parseContent(envContent, /\.ya?ml$/i.test(file));
133
112
  return envs;
134
113
  }
135
-
136
114
  return [];
137
115
  }
138
-
139
116
  static async parseFileAsMap(options) {
140
117
  const envs = await EnvUtil.parseFile(options);
141
118
  const envsObj = {};
142
-
143
119
  for (const env of envs) {
144
120
  envsObj[env.key] = env.value;
145
121
  }
146
-
147
122
  return envsObj;
148
123
  }
149
-
150
124
  static async importFile(options) {
151
125
  const envs = await EnvUtil.parseFile(options);
152
126
  const envsObj = {};
153
-
154
127
  for (const env of envs) {
155
128
  envsObj[env.key] = env.value;
156
129
  process.env[env.key] = env.value;
157
130
  }
158
-
159
- process.env.X_SERVER_ENVS = JSON.stringify({ // @ts-ignore
131
+ process.env.X_SERVER_ENVS = JSON.stringify({
132
+ // @ts-ignore
160
133
  ...JSON.parse(process.env.X_SERVER_ENVS || '{}'),
161
134
  ...envsObj
162
135
  });
163
136
  }
164
-
165
137
  static makeTypes(envs) {
166
138
  return (0, _vtils.dedent)`
167
139
  declare namespace NodeJS {
@@ -182,18 +154,13 @@ class EnvUtil {
182
154
  }
183
155
  `;
184
156
  }
185
-
186
157
  static async outputTypes(options) {
187
158
  const envs = await EnvUtil.parseFile(options);
188
-
189
159
  const outFile = _nodePath.default.join(options.cwd, options.outFile);
190
-
191
160
  const types = EnvUtil.makeTypes(envs);
192
161
  await _fsExtra.default.outputFile(outFile, types);
193
162
  }
194
-
195
163
  }
196
-
197
164
  exports.EnvUtil = EnvUtil;
198
165
  EnvUtil.NEWLINE = '\n';
199
166
  EnvUtil.RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/;
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
 
3
3
  var _node = require("esbuild-register/dist/node");
4
-
5
4
  (0, _node.register)({
6
5
  hookIgnoreNodeModules: false,
7
6
  hookMatcher: filename => filename.includes('/.x/') || !filename.includes('/node_modules/')
@@ -1,18 +1,13 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
-
5
4
  exports.__esModule = true;
6
5
  exports.TemplateUtil = void 0;
7
-
8
6
  var _fsExtra = _interopRequireDefault(require("fs-extra"));
9
-
7
+ var _globby = _interopRequireDefault(require("globby"));
10
8
  var _path = _interopRequireDefault(require("path"));
11
-
12
9
  var _vtils = require("vtils");
13
-
14
10
  var _vscodeGenerateIndexStandalone = require("vscode-generate-index-standalone");
15
-
16
11
  class TemplateUtil {
17
12
  /**
18
13
  * 初始化。
@@ -20,35 +15,39 @@ class TemplateUtil {
20
15
  static async init(cwd) {
21
16
  await Promise.all([this.initHelperPackage(cwd), this.initTasks(cwd)]);
22
17
  }
18
+
23
19
  /**
24
20
  * 初始化辅助包。
25
21
  */
26
-
27
-
28
22
  static async initHelperPackage(cwd) {
23
+ const prismaClientFile = TemplateUtil.getPrismaClientTypeFile();
29
24
  const fromDir = _path.default.join(__dirname, 'templates');
30
-
31
25
  const toDir = _path.default.join(cwd, 'node_modules/.x');
32
-
33
- await _fsExtra.default.copy(fromDir, toDir, {
34
- overwrite: true
26
+ const fromFiles = await (0, _globby.default)('*', {
27
+ cwd: fromDir,
28
+ onlyFiles: true,
29
+ absolute: true
35
30
  });
31
+ await _fsExtra.default.ensureDir(toDir);
32
+ await Promise.all(fromFiles.map(async fromFile => {
33
+ const toFile = fromFile.replace(fromDir, toDir);
34
+ let fromFileContent = await _fsExtra.default.readFile(fromFile, 'utf-8');
35
+ fromFileContent = fromFileContent.replaceAll('../.prisma/client/index.d.ts', _path.default.relative(toDir, prismaClientFile)).replaceAll('../../src', _path.default.relative(toDir, `${cwd}/src`));
36
+ await _fsExtra.default.writeFile(toFile, fromFileContent);
37
+ }));
36
38
  await (0, _vscodeGenerateIndexStandalone.generateManyIndex)({
37
39
  cwd: cwd,
38
40
  patterns: ['node_modules/.x/*.ts'],
39
41
  replaceFile: true
40
42
  });
41
43
  }
44
+
42
45
  /**
43
46
  * 初始化任务。
44
47
  */
45
-
46
-
47
48
  static async initTasks(cwd) {
48
49
  const tasksDir = _path.default.join(cwd, 'src/tasks');
49
-
50
50
  const tasksIndexFile = _path.default.join(tasksDir, 'index.ts');
51
-
52
51
  if (!(await _fsExtra.default.pathExists(tasksIndexFile))) {
53
52
  await _fsExtra.default.outputFile(tasksIndexFile, (0, _vtils.dedent)`
54
53
  // @index(['./**/*.ts', '!**/*.test.ts', '!**/_*'], f => \`export * from '\${f.path}'\`)
@@ -56,28 +55,21 @@ class TemplateUtil {
56
55
  `);
57
56
  }
58
57
  }
58
+
59
59
  /**
60
60
  * 初始化模型。
61
61
  */
62
-
63
-
64
62
  static async initModels(cwd) {
65
63
  const modelsDir = _path.default.join(cwd, 'src/models');
66
-
67
64
  const indexFile = _path.default.join(modelsDir, 'index.ts');
68
-
69
65
  const indexFile2 = _path.default.join(cwd, 'node_modules/.x/models.ts');
70
-
71
- const prismaClientFile = _path.default.join(cwd, 'node_modules/.prisma/client/index.d.ts');
72
-
66
+ const prismaClientFile = TemplateUtil.getPrismaClientTypeFile();
73
67
  const prismaClientFileContent = await _fsExtra.default.readFile(prismaClientFile, 'utf8');
74
68
  const modelNames = [...prismaClientFileContent.match(/(?<=const ModelName:).+?(?=\})/s)[0].matchAll(/(\S+?):/g)].map(match => (0, _vtils.camelCase)(match[1]));
75
69
  await Promise.all(modelNames.map(async modelName => {
76
70
  const model_name = (0, _vtils.snakeCase)(modelName);
77
71
  const ModelName = (0, _vtils.upperFirst)(modelName);
78
-
79
72
  const modelFile = _path.default.join(modelsDir, `${model_name}.ts`);
80
-
81
73
  if (!(await _fsExtra.default.pathExists(modelFile))) {
82
74
  await _fsExtra.default.outputFile(modelFile, (0, _vtils.dedent)`
83
75
  import { ${ModelName}BaseModel } from '@jayfong/x-server'
@@ -88,21 +80,26 @@ class TemplateUtil {
88
80
  `);
89
81
  }
90
82
  }));
91
-
92
83
  if (!(await _fsExtra.default.pathExists(indexFile))) {
93
84
  await _fsExtra.default.outputFile(indexFile, (0, _vtils.dedent)`
94
85
  // @index(['./**/*.ts', '!**/*.test.ts', '!**/_*'], f => \`export * from '\${f.path}'\`)
95
86
  // @endindex
96
87
  `);
97
88
  }
98
-
99
89
  await (0, _vscodeGenerateIndexStandalone.generateManyIndex)({
100
90
  cwd: cwd,
101
91
  patterns: [indexFile, indexFile2],
102
92
  replaceFile: true
103
93
  });
104
94
  }
105
-
95
+ static getPrismaClientTypeFile() {
96
+ // const prismaClientFile = path.join(
97
+ // cwd,
98
+ // 'node_modules/.prisma/client/index.d.ts',
99
+ // )
100
+ // 用 require.resolve 以兼容 pnpm
101
+ const prismaClientFile = require.resolve('@prisma/client/package.json').replace('@prisma/client/package.json', '.prisma/client/index.d.ts');
102
+ return prismaClientFile;
103
+ }
106
104
  }
107
-
108
105
  exports.TemplateUtil = TemplateUtil;
@@ -2,22 +2,21 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.defineBus = defineBus;
5
-
6
5
  var _nodeEvents = require("node:events");
7
-
8
6
  class EventBus extends _nodeEvents.EventEmitter {
9
7
  onReturnOff(event, listener) {
10
8
  this.on(event, listener);
11
9
  return () => this.off(event, listener);
12
10
  }
13
-
14
11
  }
15
-
16
12
  function defineBus() {
17
13
  const eventEmitter = new EventBus();
18
14
  return eventEmitter;
19
- } // strict-event-emitter-types
15
+ }
16
+
17
+ // strict-event-emitter-types
20
18
  // https://github.com/bterlson/strict-event-emitter-types/blob/9ed45fc68a69f0b7f85ce4e5fe11ff53cc6a009e/src/index.ts
19
+
21
20
  // the overridden signatures need to be assignment compatible, but
22
21
  // due to how tuple types work[0] it's not possible to be assignment
23
22
  // compatible anymore. This hack fixes it with a unique symbol that
@@ -25,4 +24,8 @@ function defineBus() {
25
24
  //
26
25
  // Unfortunately, this has the result of giving a poor error message when
27
26
  // you mix up types.
28
- // 0: https://github.com/Microsoft/TypeScript/issues/26013)
27
+ // 0: https://github.com/Microsoft/TypeScript/issues/26013)
28
+
29
+ // TODO: Stash under a symbol key once TS compiler bug is fixed
30
+
31
+ // EventEmitter method overrides
@@ -2,9 +2,7 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.defineCron = defineCron;
5
-
6
5
  var _cron = require("cron");
7
-
8
6
  function defineCron(options) {
9
7
  return new _cron.CronJob({
10
8
  cronTime: options.expression,
@@ -2,41 +2,39 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.defineHandler = defineHandler;
5
-
6
5
  var _handler = require("./handler");
7
-
8
6
  function defineHandler(options) {
9
- const handler = new _handler.Handler({ ...options,
7
+ const handler = new _handler.Handler({
8
+ ...options,
10
9
  requestMethod: 'POST'
11
10
  });
12
11
  return handler;
13
12
  }
14
-
15
13
  defineHandler.POST = defineHandler;
16
-
17
14
  defineHandler.GET = options => {
18
- const handler = new _handler.Handler({ ...options,
15
+ const handler = new _handler.Handler({
16
+ ...options,
19
17
  requestMethod: 'GET'
20
18
  });
21
19
  return handler;
22
20
  };
23
-
24
21
  defineHandler.FILE = options => {
25
- const handler = new _handler.Handler({ ...options,
22
+ const handler = new _handler.Handler({
23
+ ...options,
26
24
  requestMethod: 'FILE'
27
25
  });
28
26
  return handler;
29
27
  };
30
-
31
28
  defineHandler.WS = options => {
32
- const handler = new _handler.Handler({ ...options,
29
+ const handler = new _handler.Handler({
30
+ ...options,
33
31
  requestMethod: 'WS'
34
32
  });
35
33
  return handler;
36
34
  };
37
-
38
35
  defineHandler.XML = options => {
39
- const handler = new _handler.Handler({ ...options,
36
+ const handler = new _handler.Handler({
37
+ ...options,
40
38
  requestMethod: 'XML'
41
39
  });
42
40
  return handler;
@@ -2,9 +2,7 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.defineHook = defineHook;
5
-
6
5
  var _handler = require("./handler");
7
-
8
6
  function defineHook(hook) {
9
7
  _handler.Handler.addHook(hook);
10
8
  }
@@ -2,9 +2,7 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.defineServer = defineServer;
5
-
6
5
  var _server = require("./server");
7
-
8
6
  async function defineServer(options) {
9
7
  const server = new _server.Server(options);
10
8
  await server.start();
@@ -1,22 +1,17 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
-
5
4
  exports.__esModule = true;
6
5
  exports.defineSliceTask = defineSliceTask;
7
6
  exports.defineTask = defineTask;
8
-
9
7
  var _assert = _interopRequireDefault(require("assert"));
10
-
11
8
  var _bull = _interopRequireDefault(require("bull"));
12
-
13
9
  var _vtils = require("vtils");
14
-
15
10
  var _x = require("../x");
16
-
17
11
  function defineTask(options) {
18
12
  const queue = new _bull.default(options.name, {
19
- redis: { ..._x.x.redis.options,
13
+ redis: {
14
+ ..._x.x.redis.options,
20
15
  // https://github.com/OptimalBits/bull/issues/2186
21
16
  maxRetriesPerRequest: null,
22
17
  enableReadyCheck: false
@@ -33,7 +28,6 @@ function defineTask(options) {
33
28
  });
34
29
  return queue;
35
30
  }
36
-
37
31
  function defineSliceTask(options) {
38
32
  const task = defineTask({
39
33
  name: options.name,
@@ -41,7 +35,6 @@ function defineSliceTask(options) {
41
35
  handle: async data => {
42
36
  const res = data.count ? await _x.x.redis.multi([['lrange', data.redisKey, `-${data.count}`, '-1'], ['ltrim', data.redisKey, '0', `-${data.count + 1}`]]).exec() : await _x.x.redis.multi([['lrange', data.redisKey, '0', '-1'], ['del', data.redisKey]]).exec();
43
37
  const list = res[0][1].reverse().map(item => JSON.parse(item));
44
-
45
38
  if (list.length) {
46
39
  return options.handle(list, data.key);
47
40
  }
@@ -57,9 +50,10 @@ function defineSliceTask(options) {
57
50
  (0, _assert.default)(duration != null || threshold != null, '参数 threshold 和 duration 必须至少设置 1 个');
58
51
  const redisKey = !key ? redisKeyPrefix : `${redisKeyPrefix}_${key}`;
59
52
  const res = await _x.x.redis.multi([['llen', redisKey], ['lpush', redisKey, JSON.stringify(data)]]).exec();
60
- const count = parseInt(res[0][1], 10) + 1; // 仅时段
61
- // 1分钟内的合并推送
53
+ const count = parseInt(res[0][1], 10) + 1;
62
54
 
55
+ // 仅时段
56
+ // 1分钟内的合并推送
63
57
  if (duration != null) {
64
58
  if (count === 1) {
65
59
  await task.add({
@@ -69,7 +63,8 @@ function defineSliceTask(options) {
69
63
  delay: duration
70
64
  });
71
65
  }
72
- } // 仅阈值
66
+ }
67
+ // 仅阈值
73
68
  // 满10条推送
74
69
  else if (threshold != null) {
75
70
  if (thresholdTimeout) {
@@ -83,7 +78,6 @@ function defineSliceTask(options) {
83
78
  delay: thresholdTimeout
84
79
  });
85
80
  }
86
-
87
81
  if (count === threshold) {
88
82
  await task.add({
89
83
  key: key,
@@ -2,10 +2,9 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.getHandlerUrl = getHandlerUrl;
5
-
6
5
  var _vtils = require("vtils");
7
-
8
6
  var _x = require("../x");
7
+ // @ts-ignore
9
8
 
10
9
  function getHandlerUrl(path, query) {
11
10
  return `${_x.x.env.APP_URL.replace(/\/+$/, '')}${path}${query ? `?${(0, _vtils.createUrlQueryString)(query)}` : ''}`;
@@ -1,38 +1,30 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
-
5
4
  exports.__esModule = true;
6
5
  exports.Handler = void 0;
7
-
8
6
  var _lzString = _interopRequireDefault(require("lz-string"));
9
-
10
7
  var _vtils = require("vtils");
11
-
12
8
  var _dispose = require("../services/dispose");
13
-
14
9
  var _http_error = require("../core/http_error");
15
-
16
10
  var _validator = require("vtils/validator");
11
+ // @ts-ignore
12
+ // prettier-ignore
17
13
 
18
14
  class Handler {
19
15
  constructor(options) {
20
16
  this.options = options;
21
17
  this.requestDataSchema = void 0;
22
-
23
18
  this.handle = async (data, ctx) => {
24
19
  // 前置 hook
25
20
  if (Handler.hooks.length) {
26
21
  await Promise.all(Handler.hooks.map(hook => hook(this.options, data, ctx)));
27
22
  }
28
-
29
23
  if (this.options.requestMethod === 'WS') {
30
24
  return this.handleWs(data, ctx);
31
25
  }
32
-
33
26
  return this.handleHttp(data, ctx);
34
27
  };
35
-
36
28
  this.handleHttp = async (data, ctx) => {
37
29
  // 请求数据验证
38
30
  if (this.requestDataSchema) {
@@ -45,45 +37,40 @@ class Handler {
45
37
  throw new _http_error.HttpError.BadRequest(err.message);
46
38
  }
47
39
  }
40
+ let res = await this.options.handle(data, ctx);
48
41
 
49
- let res = await this.options.handle(data, ctx); // 设置响应的 Content-Type 头
50
-
42
+ // 设置响应的 Content-Type 头
51
43
  if (this.options.responseContentType) {
52
44
  ctx.setHeader('Content-Type', this.options.responseContentType);
53
- } // 打包返回数据
54
-
45
+ }
55
46
 
47
+ // 打包返回数据
56
48
  if (this.options.responseDataPack) {
57
49
  res = _vtils.DataPacker.packAsRawType(res);
58
- } // 混淆返回数据
59
-
50
+ }
60
51
 
52
+ // 混淆返回数据
61
53
  if (this.options.responseDataObfuscate) {
62
54
  res = {
63
55
  '_#': _lzString.default.compress(JSON.stringify(res))
64
56
  };
65
57
  }
66
-
67
58
  return res == null ? {} : res;
68
59
  };
69
-
70
60
  this.handleWs = async (data, ctx) => {
71
61
  const dispose = new _dispose.DisposeService();
72
62
  ctx.ws.socket.on('message', async payload => {
73
63
  try {
74
64
  const _ = JSON.parse(payload.toString('utf8'));
75
-
76
65
  const send = data => {
77
66
  ctx.ws.socket.send(JSON.stringify({
78
67
  id: _.id,
79
68
  data: data
80
69
  }));
81
70
  };
82
-
83
71
  const process = async (type, fn) => {
84
72
  if (_.type === type) {
85
73
  let sent = false;
86
-
87
74
  try {
88
75
  await fn({
89
76
  data: _.data,
@@ -93,13 +80,11 @@ class Handler {
93
80
  },
94
81
  dispose: dispose
95
82
  });
96
-
97
83
  if (!sent) {
98
84
  send();
99
85
  }
100
86
  } catch (err) {
101
87
  const _err = _http_error.HttpError.isHttpError(err) ? err : new _http_error.HttpError.InternalServerError();
102
-
103
88
  send({
104
89
  statusCode: _err.statusCode,
105
90
  error: _err.name,
@@ -108,7 +93,6 @@ class Handler {
108
93
  }
109
94
  }
110
95
  };
111
-
112
96
  if (_.type === 'ping') {
113
97
  send();
114
98
  } else {
@@ -116,7 +100,6 @@ class Handler {
116
100
  }
117
101
  } catch (err) {
118
102
  const _err = _http_error.HttpError.isHttpError(err) ? err : new _http_error.HttpError.InternalServerError();
119
-
120
103
  ctx.ws.socket.send(JSON.stringify({
121
104
  statusCode: _err.statusCode,
122
105
  error: _err.name,
@@ -128,17 +111,13 @@ class Handler {
128
111
  dispose.dispose();
129
112
  });
130
113
  };
131
-
132
114
  if (options.requestDataSchema) {
133
115
  this.requestDataSchema = options.requestDataSchema(_validator.yup);
134
116
  }
135
117
  }
136
-
137
118
  static addHook(hook) {
138
119
  this.hooks.push(hook);
139
120
  }
140
-
141
121
  }
142
-
143
122
  exports.Handler = Handler;
144
123
  Handler.hooks = [];