@jayfong/x-server 1.8.0 → 1.10.2

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,47 @@
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
+ ### [1.10.2](https://github.com/jfWorks/x-server/compare/v1.10.1...v1.10.2) (2022-04-19)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * api gen ([cc33df1](https://github.com/jfWorks/x-server/commit/cc33df1bf15c2b367b1a62cf920a1a1184c20339))
11
+
12
+ ### [1.10.1](https://github.com/jfWorks/x-server/compare/v1.10.0...v1.10.1) (2022-04-19)
13
+
14
+ ## [1.10.0](https://github.com/jfWorks/x-server/compare/v1.8.0...v1.10.0) (2022-04-19)
15
+
16
+
17
+ ### Features
18
+
19
+ * use esbuild-register ([0b004db](https://github.com/jfWorks/x-server/commit/0b004db9a048d0faaf528c0d8030bf0ccfb8e2b3))
20
+
21
+
22
+ ### Bug Fixes
23
+
24
+ * template ([0f9bd05](https://github.com/jfWorks/x-server/commit/0f9bd0589d101de6f78f13f185ef9220edc887a7))
25
+ * watcher initial ([82511a1](https://github.com/jfWorks/x-server/commit/82511a1bc9d1ccf4d96aa7a8ae7ee3d50a8ec2db))
26
+
27
+ ## [1.9.0](https://github.com/jfWorks/x-server/compare/v1.7.2...v1.9.0) (2022-04-18)
28
+
29
+
30
+ ### Features
31
+
32
+ * 更改包名为 @jayfong/x-server ([1be9998](https://github.com/jfWorks/x-server/commit/1be9998070cc0960aeef2d333356f66a22bb5766))
33
+ * 移除 cwd 选项 ([12cfa42](https://github.com/jfWorks/x-server/commit/12cfa4222ec8d69d73f2b38a68ea6aa975dbe575))
34
+ * npc ([5d314ea](https://github.com/jfWorks/x-server/commit/5d314ea341a72ae5b09db979d5d2b63ffadf0670))
35
+ * plugins ([1df0cd1](https://github.com/jfWorks/x-server/commit/1df0cd10ccf170d9e7180abf9d27416304856894))
36
+ * service 通过 x 提供 ([a159154](https://github.com/jfWorks/x-server/commit/a1591541e865e755d4d6dbdeb405d5d08b334a4a))
37
+ * templates ([deeb0d6](https://github.com/jfWorks/x-server/commit/deeb0d643bdf04d04533d20bd1d5a068b178347a))
38
+ * use esbuild-register ([0b004db](https://github.com/jfWorks/x-server/commit/0b004db9a048d0faaf528c0d8030bf0ccfb8e2b3))
39
+
40
+
41
+ ### Bug Fixes
42
+
43
+ * template ([0f9bd05](https://github.com/jfWorks/x-server/commit/0f9bd0589d101de6f78f13f185ef9220edc887a7))
44
+ * test ([994845b](https://github.com/jfWorks/x-server/commit/994845b0e2ac84ce050494de27b705c1e45fb343))
45
+
5
46
  ## [1.8.0](https://github.com/jfWorks/x-server/compare/v1.7.2...v1.8.0) (2022-04-18)
6
47
 
7
48
 
@@ -273,7 +273,7 @@ class ApiGenerator {
273
273
  tsConfigFilePath: node_path_1.default.join(this.cwd, 'tsconfig.json'),
274
274
  });
275
275
  this.debug('加载文件...');
276
- const sourceFile = this.project.getSourceFileOrThrow(node_path_1.default.join(this.cwd, 'src/generated/handlers.ts'));
276
+ const sourceFile = this.project.createSourceFile(node_path_1.default.join(this.cwd, 'src/generated/handlers.ts'), await fs_extra_1.default.readFile(node_path_1.default.join(this.cwd, 'node_modules/.x/handlers.ts'), 'utf-8'));
277
277
  this.debug('导出处理器...');
278
278
  const handlerGroup = sourceFile.getExportSymbols();
279
279
  const handles = [];
package/lib/cli/cli.js CHANGED
@@ -27,9 +27,6 @@ yargs_1.default
27
27
  type: 'string',
28
28
  }), async (argv) => {
29
29
  process.env.NODE_ENV = 'development';
30
- const watcher = chokidar_1.default.watch(['src', '.env'], {
31
- cwd: process.cwd(),
32
- });
33
30
  let lastRun;
34
31
  const run = () => {
35
32
  lastRun = (0, execa_1.default)('node', ['-r', require.resolve('./register'), 'src/main.ts'], {
@@ -51,7 +48,13 @@ yargs_1.default
51
48
  stdio: 'inherit',
52
49
  });
53
50
  }
54
- await template_util_1.TemplateUtil.init(process.cwd());
51
+ await Promise.all([
52
+ template_util_1.TemplateUtil.initHelperPackage(process.cwd()),
53
+ template_util_1.TemplateUtil.initModels(process.cwd()),
54
+ ]);
55
+ const watcher = chokidar_1.default.watch(['src', '.env'], {
56
+ cwd: process.cwd(),
57
+ });
55
58
  watcher.on('all', (0, vtils_1.debounce)(async () => {
56
59
  await env_util_1.EnvUtil.importFile({
57
60
  cwd: process.cwd(),
@@ -101,7 +104,7 @@ yargs_1.default
101
104
  value: 'production',
102
105
  comment: '',
103
106
  });
104
- await template_util_1.TemplateUtil.init(process.cwd());
107
+ await template_util_1.TemplateUtil.initHelperPackage(process.cwd());
105
108
  await (0, vscode_generate_index_standalone_1.generateManyIndex)({
106
109
  cwd: process.cwd(),
107
110
  patterns: ['src/.x/*.ts'],
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
- require('esbuild-runner').install({
3
- type: 'transform',
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_1 = require("esbuild-register/dist/node");
4
+ (0, node_1.register)({
5
+ hookIgnoreNodeModules: false,
6
+ hookMatcher: filename => filename.includes('/.x/') || !filename.includes('/node_modules/'),
4
7
  });
5
- require('tsconfig-paths/register');
@@ -1,3 +1,10 @@
1
1
  export declare class TemplateUtil {
2
- static init(cwd: string): Promise<void>;
2
+ /**
3
+ * 初始化辅助包。
4
+ */
5
+ static initHelperPackage(cwd: string): Promise<void>;
6
+ /**
7
+ * 初始化模型。
8
+ */
9
+ static initModels(cwd: string): Promise<void>;
3
10
  }
@@ -6,13 +6,51 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.TemplateUtil = void 0;
7
7
  const fs_extra_1 = __importDefault(require("fs-extra"));
8
8
  const path_1 = __importDefault(require("path"));
9
+ const vtils_1 = require("vtils");
9
10
  class TemplateUtil {
10
- static async init(cwd) {
11
+ /**
12
+ * 初始化辅助包。
13
+ */
14
+ static async initHelperPackage(cwd) {
11
15
  const fromDir = path_1.default.join(__dirname, 'templates');
12
16
  const toDir = path_1.default.join(cwd, 'node_modules/.x');
13
17
  await fs_extra_1.default.copy(fromDir, toDir, {
14
18
  overwrite: true,
15
19
  });
16
20
  }
21
+ /**
22
+ * 初始化模型。
23
+ */
24
+ static async initModels(cwd) {
25
+ const modelsDir = path_1.default.join(cwd, 'src/models');
26
+ const indexFile = path_1.default.join(modelsDir, 'index.ts');
27
+ if (!(await fs_extra_1.default.pathExists(indexFile))) {
28
+ await fs_extra_1.default.outputFile(indexFile, (0, vtils_1.dedent) `
29
+ // @index(['./**/*.ts', '!**/*.test.ts', '!**/_*'], f => \`export * from '\${f.path}'\`)
30
+ // @endindex
31
+ `);
32
+ }
33
+ const prismaClientFile = path_1.default.join(cwd, 'node_modules/.prisma/client/index.d.ts');
34
+ const prismaClientFileContent = await fs_extra_1.default.readFile(prismaClientFile, 'utf8');
35
+ const modelNames = [
36
+ ...prismaClientFileContent
37
+ .match(/(?<=const ModelName:).+?(?=\})/s)[0]
38
+ .matchAll(/(\S+?):/g),
39
+ ].map(match => (0, vtils_1.camelCase)(match[1]));
40
+ await Promise.all(modelNames.map(async (modelName) => {
41
+ const model_name = (0, vtils_1.snakeCase)(modelName);
42
+ const ModelName = (0, vtils_1.upperFirst)(modelName);
43
+ const modelFile = path_1.default.join(modelsDir, `${model_name}.ts`);
44
+ if (!(await fs_extra_1.default.pathExists(modelFile))) {
45
+ await fs_extra_1.default.outputFile(modelFile, (0, vtils_1.dedent) `
46
+ import { ${ModelName}BaseModel } from '@jayfong/x-server'
47
+
48
+ export class ${ModelName}Model extends ${ModelName}BaseModel {}
49
+
50
+ export const ${modelName}Model = new ${ModelName}Model()
51
+ `);
52
+ }
53
+ }));
54
+ }
17
55
  }
18
56
  exports.TemplateUtil = TemplateUtil;
@@ -1,3 +1,3 @@
1
- // @index('../../src/handlers/**/*.ts', (f, _) => `export * as __${_.pascal(f.path.replace('handlers', ''))}__ from '${f.path}'`)
1
+ // @index('../../src/handlers/**/*.ts', (f, _) => `export * as __${_.pascal(f.path.replace('/src/handlers/', ''))}__ from '${f.path}'`)
2
2
 
3
3
  // @endindex
@@ -0,0 +1,3 @@
1
+ {
2
+ "name": ".x"
3
+ }
@@ -2,7 +2,7 @@ import * as handlers from './handlers'
2
2
  import { Handler, XServer } from '@jayfong/x-server'
3
3
 
4
4
  const basePathWithHandlers: Array<[string, Record<string, Handler>]> = [
5
- // @index('../../src/handlers/**/*.ts', (f, _) => `['${('/'+_.snake(f.path.replace('handlers', '')).replace(/_/g, '/')+'/').replace(/\/{2,}/g, '/')}', handlers.__${_.pascal(f.path.replace('handlers', ''))}__ as any],`)
5
+ // @index('../../src/handlers/**/*.ts', (f, _) => `['${('/'+_.snake(f.path.replace('/src/handlers/', '')).replace(/_/g, '/')+'/').replace(/\/{2,}/g, '/')}', handlers.__${_.pascal(f.path.replace('/src/handlers/', ''))}__ as any],`)
6
6
  // @endindex
7
7
  ]
8
8
 
@@ -5,12 +5,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.defineTask = void 0;
7
7
  const bull_1 = __importDefault(require("bull"));
8
- const server_1 = require("./server");
9
8
  const x_1 = require("../x");
10
9
  async function defineTask(options) {
11
10
  const queue = new bull_1.default(options.name, {
12
11
  redis: x_1.x.redis.options,
13
- prefix: `${server_1.Server.options.name}_task`,
12
+ prefix: `${x_1.x.appName}_task`,
14
13
  });
15
14
  queue.process(async (job) => {
16
15
  return options.handle(job.data);
@@ -9,8 +9,11 @@ export declare class Server {
9
9
  close(): Promise<void>;
10
10
  private prepareFastify;
11
11
  private startFastify;
12
+ private prepareRoutes;
13
+ private applyHooks;
12
14
  private applyServices;
13
15
  private applyPlugins;
14
16
  private applyRoutes;
17
+ private startTasks;
15
18
  private applyAutoClose;
16
19
  }
@@ -29,27 +29,23 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.Server = void 0;
30
30
  const fastify_1 = __importDefault(require("fastify"));
31
31
  const vtils_1 = require("vtils");
32
- const dispose_1 = require("../services/dispose");
33
32
  const http_method_1 = require("./http_method");
34
33
  const x_1 = require("../x");
35
- // @ts-ignore
36
- const routes_1 = require(".x/routes");
37
34
  class Server {
38
35
  constructor(options) {
39
36
  this.options = options;
40
- this.routes = routes_1.routes;
37
+ this.routes = [];
41
38
  Server.options = options;
42
39
  }
43
40
  async start() {
44
41
  this.applyServices();
45
42
  await this.prepareFastify();
46
43
  this.applyPlugins();
44
+ await this.prepareRoutes();
47
45
  await this.applyRoutes();
48
- // @ts-ignore
49
- await Promise.resolve().then(() => __importStar(require('.x/hooks')));
46
+ await this.applyHooks();
50
47
  await this.startFastify();
51
- // @ts-ignore
52
- await Promise.resolve().then(() => __importStar(require('.x/tasks')));
48
+ await this.startTasks();
53
49
  await this.applyAutoClose();
54
50
  }
55
51
  async close() {
@@ -70,10 +66,17 @@ class Server {
70
66
  port: this.options.port,
71
67
  });
72
68
  }
69
+ async prepareRoutes() {
70
+ // @ts-ignore
71
+ const { routes } = await Promise.resolve().then(() => __importStar(require('.x/routes')));
72
+ this.routes = routes;
73
+ }
74
+ async applyHooks() {
75
+ // @ts-ignore
76
+ await Promise.resolve().then(() => __importStar(require('.x/hooks')));
77
+ }
73
78
  applyServices() {
74
- x_1.x.register(new dispose_1.DisposeService({
75
- disposeOnExit: true,
76
- }), ...(this.options.services || []));
79
+ x_1.x.register(...(this.options.services || []));
77
80
  }
78
81
  applyPlugins() {
79
82
  const plugins = this.options.plugins || [];
@@ -129,6 +132,10 @@ class Server {
129
132
  });
130
133
  }
131
134
  }
135
+ async startTasks() {
136
+ // @ts-ignore
137
+ await Promise.resolve().then(() => __importStar(require('.x/tasks')));
138
+ }
132
139
  async applyAutoClose() {
133
140
  x_1.x.dispose.add(() => this.close());
134
141
  }
@@ -21,10 +21,6 @@ export declare namespace XServer {
21
21
  handler: Handler;
22
22
  }
23
23
  interface Options {
24
- /**
25
- * 应用名称
26
- */
27
- name: string;
28
24
  /**
29
25
  * 监听主机
30
26
  */
@@ -4,9 +4,7 @@ import { MsValue } from 'vtils/date';
4
4
  export declare type CacheTTL = MsValue;
5
5
  export interface CacheOptions {
6
6
  /** 默认过期时间 */
7
- defaultTTL: CacheTTL;
8
- /** 存储键前缀 */
9
- prefix: string;
7
+ ttl: CacheTTL;
10
8
  }
11
9
  declare type Data = {
12
10
  [K in string]: (...args: any[]) => any;
@@ -11,7 +11,7 @@ class CacheService {
11
11
  constructor(options) {
12
12
  this.options = options;
13
13
  this.serviceName = 'cache';
14
- this.prefix = `${options.prefix}:`;
14
+ this.prefix = `${x_1.x.appName}:`;
15
15
  }
16
16
  toRedisKey(key) {
17
17
  return `${this.prefix}${Array.isArray(key) ? key.join('_') : String(key)}`;
@@ -25,10 +25,10 @@ class CacheService {
25
25
  * @returns 返回设置的缓存内容
26
26
  */
27
27
  async set(key, value, ttl = this.options
28
- .defaultTTL) {
28
+ .ttl) {
29
29
  const redisKey = this.toRedisKey(key);
30
30
  const redisValue = JSON.stringify(value);
31
- const redisTtl = typeof ttl === 'function' ? ttl(value, this.options.defaultTTL) : ttl;
31
+ const redisTtl = typeof ttl === 'function' ? ttl(value, this.options.ttl) : ttl;
32
32
  await x_1.x.redis.set(redisKey, redisValue,
33
33
  // 毫秒
34
34
  'PX', (0, date_1.ms)(redisTtl));
@@ -40,7 +40,7 @@ class CacheService {
40
40
  * @param value 值
41
41
  * @param ttl 存活时间
42
42
  */
43
- async save(value, ttl = this.options.defaultTTL) {
43
+ async save(value, ttl = this.options.ttl) {
44
44
  const key = `X__${(0, cuid_1.default)()}`;
45
45
  await this.set(key, typeof value === 'function' ? await value(key) : value, ttl);
46
46
  return key;
@@ -93,7 +93,7 @@ class CacheService {
93
93
  * @returns 返回获取到的内容
94
94
  */
95
95
  async remember(key, action, ttl = this.options
96
- .defaultTTL) {
96
+ .ttl) {
97
97
  let value = await this.get(key);
98
98
  if (value === null) {
99
99
  value = await action();
package/lib/x.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { BaseService } from './services/base';
2
+ import './services/dispose';
2
3
  export interface X {
4
+ readonly appName: string;
3
5
  readonly register: (...services: BaseService[]) => void;
4
6
  }
5
7
  export declare const x: X;
package/lib/x.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.x = void 0;
4
+ const dispose_1 = require("./services/dispose");
4
5
  exports.x = {
6
+ appName: process.env.APP_NAME,
5
7
  register: (...services) => {
6
8
  for (const service of services) {
7
9
  // @ts-ignore
@@ -9,3 +11,6 @@ exports.x = {
9
11
  }
10
12
  },
11
13
  };
14
+ exports.x.register(new dispose_1.DisposeService({
15
+ disposeOnExit: true,
16
+ }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jayfong/x-server",
3
- "version": "1.8.0",
3
+ "version": "1.10.2",
4
4
  "license": "ISC",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -38,7 +38,7 @@
38
38
  "cuid": "^2.1.8",
39
39
  "debug": "^4.3.4",
40
40
  "esbuild": "^0.14.36",
41
- "esbuild-runner": "^2.2.1",
41
+ "esbuild-register": "^3.3.2",
42
42
  "execa": "^5.1.1",
43
43
  "exit-hook": "^2.2.1",
44
44
  "fast-xml-parser": "^3.21.1",
@@ -57,7 +57,6 @@
57
57
  "supports-color": "^8",
58
58
  "svg-captcha": "^1.4.0",
59
59
  "ts-morph": "^12.2.0",
60
- "tsconfig-paths": "^3.14.1",
61
60
  "utf-8-validate": "^5.0.9",
62
61
  "vscode-generate-index-standalone": "^1.6.0",
63
62
  "vtils": "^4.60.0",