@zenorm/generate 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,6 +4,42 @@
4
4
 
5
5
  表结构代码生成工具
6
6
 
7
+ ## 安装
8
+ ```bash
9
+ npm i -D @zenorm/generate
10
+ ```
11
+
12
+ ## 配置
13
+
14
+ 新建配置文件 `dbgen.config.js`
15
+
16
+ ```js
17
+ /** @type {import("@zenorm/generate").GenerateConfig} */
18
+ export default {
19
+ "database": "you_db_name", // 数据库名
20
+ "host": "localhost", // 目标数据库地址
21
+ "port": 3306, // 数据库端口
22
+ "user": "root", // 数据库用户名
23
+ "password": "", // 数据库密码
24
+ "outputDir": "./model/", // 代码输出目录
25
+ "bindQuery": true, // 绑定 Query 对象
26
+ }
27
+ ```
28
+
29
+ ## 在 package.json 中添加命令
30
+ ```json
31
+ {
32
+ "scripts": {
33
+ "dbgen": "zenorm-generate dbgen.config.js"
34
+ },
35
+ }
36
+ ```
37
+
38
+ ## 运行命令生成数据库代码
39
+ ```bash
40
+ npm run dbgen
41
+ ```
42
+
7
43
  ## Generate Config - 代码生成配置
8
44
 
9
45
  | 配置项 | 类型 | 默认值 | 说明
@@ -22,3 +58,4 @@
22
58
  | declareRepositoriesToModules | `string[]` | 无 | 是否需将 Repositories 实例定义到目标模块中 - 例如: `["@zenweb/core.Core.repositories"]`
23
59
  | filter | `string` | 无 | 表过滤规则正则
24
60
  | include | `string` | 无 | 表包含规则正则
61
+ | esModule | `boolean` | 无 | 是否输出满足 ESM 导入文件名 (必须带有 .js 扩展名)
@@ -1,25 +1,62 @@
1
1
  #!/usr/bin/env node
2
- import path from 'node:path';
3
- import { pathToFileURL } from 'node:url';
4
- import { generate } from '../generate.js';
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ var __importDefault = (this && this.__importDefault) || function (mod) {
37
+ return (mod && mod.__esModule) ? mod : { "default": mod };
38
+ };
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ const node_path_1 = __importDefault(require("node:path"));
41
+ const generate_1 = require("../generate");
5
42
  async function getConfig(filename) {
6
- const configFile = pathToFileURL(path.join(process.cwd(), filename)).href;
7
- const config = (await import(configFile)).default;
43
+ const configFile = node_path_1.default.join(process.cwd(), filename);
44
+ const config = (await Promise.resolve(`${configFile}`).then(s => __importStar(require(s)))).default;
8
45
  return Object.assign({
9
46
  backend: '@zenorm/generate-mysql',
10
47
  }, config);
11
48
  }
12
49
  async function main(configFilename) {
13
50
  const config = await getConfig(configFilename);
14
- const call = (await import(config.backend)).default;
15
- await generate(call()(config), config);
51
+ const call = (await Promise.resolve(`${config.backend}`).then(s => __importStar(require(s)))).default;
52
+ await (0, generate_1.generate)(call()(config), config);
16
53
  }
17
54
  if (!process.argv[2]) {
18
55
  console.log('zenorm-generate config.js');
19
56
  process.exit(1);
20
57
  }
21
58
  else {
22
- await main(process.argv[2]).then(() => {
59
+ main(process.argv[2]).then(() => {
23
60
  console.log('Done.');
24
61
  process.exit();
25
62
  }, e => {
@@ -1,2 +1,2 @@
1
- import { GenerateConfig, TabelDescribe } from './types.js';
1
+ import { GenerateConfig, TabelDescribe } from './types';
2
2
  export declare function generate(tables: AsyncGenerator<TabelDescribe>, cfg?: GenerateConfig): Promise<void>;
package/dist/generate.js CHANGED
@@ -1,10 +1,16 @@
1
- import { promises as fs } from 'node:fs';
2
- import path from 'node:path';
3
- import { pascalCase } from 'pascal-case';
4
- import { snakeCase } from 'snake-case';
5
- import { checkFileDir, currentDatetime, cwdPath, notExistsPut } from './utils.js';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generate = generate;
7
+ const node_fs_1 = require("node:fs");
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const pascal_case_1 = require("pascal-case");
10
+ const snake_case_1 = require("snake-case");
11
+ const utils_1 = require("./utils");
6
12
  const zenormName = process.env.ZENORM_NAME || 'zenorm';
7
- export async function generate(tables, cfg) {
13
+ async function generate(tables, cfg) {
8
14
  console.log('generate models...');
9
15
  const config = Object.assign({
10
16
  outputDir: './src/model',
@@ -13,19 +19,20 @@ export async function generate(tables, cfg) {
13
19
  staticMethods: true,
14
20
  instanceMethods: true,
15
21
  }, cfg);
16
- const outputDir = cwdPath(config.outputDir);
17
- await checkFileDir(outputDir);
22
+ function importFilename(filename) {
23
+ return cfg?.esModule ? `${filename}.js` : filename;
24
+ }
25
+ const outputDir = (0, utils_1.cwdPath)(config.outputDir);
26
+ await (0, utils_1.checkFileDir)(outputDir);
18
27
  console.log('database:', config.database);
19
28
  const remark = [
20
29
  '// zenorm 自动生成文件',
21
30
  '// 请不要修改此文件,因为此文件在每次重新生成数据库结构时会被覆盖',
22
- `// create at: ${currentDatetime()}`,
23
- `// create by: ${process.env.USER || process.env.USERNAME || '-'}@${process.env.COMPUTERNAME || '-'}`,
24
31
  `// database: ${config.database}`,
25
32
  ];
26
33
  const structs = [
27
34
  ...remark,
28
- config.globalFilename ? `import _Global from './${config.globalFilename}.js';` : null,
35
+ config.globalFilename ? `import _Global from './${importFilename(config.globalFilename)}';` : null,
29
36
  '',
30
37
  ];
31
38
  const typesOut = {};
@@ -40,9 +47,9 @@ export async function generate(tables, cfg) {
40
47
  // console.log('table:', tableName, 'ignore');
41
48
  continue;
42
49
  }
43
- const className = pascalCase(tableName);
44
- const name = snakeCase(tableName);
45
- const outputFilename = path.join(outputDir, name + '.ts');
50
+ const className = (0, pascal_case_1.pascalCase)(tableName);
51
+ const name = (0, snake_case_1.snakeCase)(tableName);
52
+ const outputFilename = node_path_1.default.join(outputDir, name + '.ts');
46
53
  console.log('table:', tableName);
47
54
  // 自定义类型
48
55
  Object.assign(typesOut, t.types);
@@ -78,10 +85,10 @@ export async function generate(tables, cfg) {
78
85
  tablesOut.push('}');
79
86
  tablesOut.push('');
80
87
  // model class
81
- await notExistsPut(outputFilename, () => {
88
+ await (0, utils_1.notExistsPut)(outputFilename, () => {
82
89
  return [
83
90
  `import { Model } from '${zenormName}';`,
84
- `import { ${className}Table } from './${config.tablesFilename}.js';`,
91
+ `import { ${className}Table } from './${importFilename(config.tablesFilename)}';`,
85
92
  '',
86
93
  `@Model({`,
87
94
  pk ? ` pk: '${pk}',` : null,
@@ -100,9 +107,9 @@ export async function generate(tables, cfg) {
100
107
  structs.push(`type ${tname} = ${typesOut[tname]};`);
101
108
  }
102
109
  structs.push(...tablesOut);
103
- const tablesFilename = path.join(outputDir, config.tablesFilename + '.ts');
110
+ const tablesFilename = node_path_1.default.join(outputDir, config.tablesFilename + '.ts');
104
111
  console.log(`write tables file: ${tablesFilename}`);
105
- await fs.writeFile(tablesFilename, structs.filter(i => i !== null).join('\n'));
112
+ await node_fs_1.promises.writeFile(tablesFilename, structs.filter(i => i !== null).join('\n'));
106
113
  const imports = ['createRepositoryQuery'];
107
114
  if (config.generateRepositories || config.bindQuery) {
108
115
  imports.push('QueryParam');
@@ -110,8 +117,8 @@ export async function generate(tables, cfg) {
110
117
  const repositories = [
111
118
  ...remark,
112
119
  `import { ${imports.join(', ')} } from '${zenormName}';`,
113
- `import * as _tables from './${config.tablesFilename}.js';`,
114
- ...models.map(({ name, className }) => `import _${className} from './${name}.js';`),
120
+ `import * as _tables from './${importFilename(config.tablesFilename)}';`,
121
+ ...models.map(({ name, className }) => `import _${className} from './${importFilename(name)}';`),
115
122
  ];
116
123
  // 绑定静态 Query
117
124
  if (config.bindQuery) {
@@ -168,24 +175,24 @@ export async function generate(tables, cfg) {
168
175
  }
169
176
  }
170
177
  }
171
- const repositoriesFilename = path.join(outputDir, config.repositoriesFilename + '.ts');
178
+ const repositoriesFilename = node_path_1.default.join(outputDir, config.repositoriesFilename + '.ts');
172
179
  console.log(`write repositories file: ${repositoriesFilename}`);
173
- await fs.writeFile(repositoriesFilename, repositories.join('\n'));
180
+ await node_fs_1.promises.writeFile(repositoriesFilename, repositories.join('\n'));
174
181
  // 生成 global.ts
175
182
  if (config.globalFilename) {
176
- const globalFilename = path.join(outputDir, config.globalFilename + '.ts');
177
- await notExistsPut(globalFilename, () => {
183
+ const globalFilename = node_path_1.default.join(outputDir, config.globalFilename + '.ts');
184
+ await (0, utils_1.notExistsPut)(globalFilename, () => {
178
185
  console.log(`write file: ${globalFilename}`);
179
186
  return 'export default class Global {}';
180
187
  });
181
188
  }
182
189
  // 生成 index.ts
183
- const indexFilename = path.join(outputDir, 'index.ts');
184
- await notExistsPut(indexFilename, () => {
190
+ const indexFilename = node_path_1.default.join(outputDir, 'index.ts');
191
+ await (0, utils_1.notExistsPut)(indexFilename, () => {
185
192
  console.log(`write file: ${indexFilename}`);
186
193
  return [
187
- `export * from './${config.tablesFilename}.js';`,
188
- `export * from './${config.repositoriesFilename}.js';`,
194
+ `export * from './${importFilename(config.tablesFilename)}';`,
195
+ `export * from './${importFilename(config.repositoriesFilename)}';`,
189
196
  ].join('\n');
190
197
  });
191
198
  }
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export * from './types.js';
1
+ export * from './types';
package/dist/index.js CHANGED
@@ -1 +1,17 @@
1
- export * from './types.js';
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
package/dist/types.d.ts CHANGED
@@ -129,6 +129,10 @@ export interface GenerateConfig {
129
129
  * 表包含规则正则,默认不处理
130
130
  */
131
131
  include?: string;
132
+ /**
133
+ * 是否输出满足 ESM 导入文件名 (必须带有 .js 扩展名)
134
+ */
135
+ esModule?: boolean;
132
136
  }
133
137
  /**
134
138
  * 数据库表信息生成方法
package/dist/types.js CHANGED
@@ -1 +1,2 @@
1
- export {};
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/utils.js CHANGED
@@ -1,29 +1,39 @@
1
- import { promises as fs } from 'node:fs';
2
- import path from 'node:path';
3
- export function cwdPath(p) {
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.cwdPath = cwdPath;
7
+ exports.checkFileDir = checkFileDir;
8
+ exports.fileExists = fileExists;
9
+ exports.notExistsPut = notExistsPut;
10
+ exports.currentDatetime = currentDatetime;
11
+ const node_fs_1 = require("node:fs");
12
+ const node_path_1 = __importDefault(require("node:path"));
13
+ function cwdPath(p) {
4
14
  if (p.startsWith('./')) {
5
- return path.join(process.cwd(), p.slice(2));
15
+ return node_path_1.default.join(process.cwd(), p.slice(2));
6
16
  }
7
17
  return p;
8
18
  }
9
- export function checkFileDir(dir) {
10
- return fs.mkdir(dir, { recursive: true });
19
+ function checkFileDir(dir) {
20
+ return node_fs_1.promises.mkdir(dir, { recursive: true });
11
21
  }
12
- export function fileExists(f) {
13
- return fs.access(f).then(() => true, () => false);
22
+ function fileExists(f) {
23
+ return node_fs_1.promises.access(f).then(() => true, () => false);
14
24
  }
15
25
  /**
16
26
  * 文件不存在则创建并写入内容
17
27
  * @param filename
18
28
  * @param getContent
19
29
  */
20
- export async function notExistsPut(filename, getContent) {
30
+ async function notExistsPut(filename, getContent) {
21
31
  if (!await fileExists(filename)) {
22
- await fs.writeFile(filename, await getContent());
32
+ await node_fs_1.promises.writeFile(filename, await getContent());
23
33
  return true;
24
34
  }
25
35
  return false;
26
36
  }
27
- export function currentDatetime() {
37
+ function currentDatetime() {
28
38
  return new Date().toLocaleString();
29
39
  }
package/package.json CHANGED
@@ -1,8 +1,7 @@
1
1
  {
2
2
  "name": "@zenorm/generate",
3
- "type": "module",
4
3
  "description": "Easy ORM, easy query. easy typing! Auto generate typescript declaration.",
5
- "version": "2.2.0",
4
+ "version": "2.4.0",
6
5
  "exports": "./dist/index.js",
7
6
  "types": "./dist/index.d.ts",
8
7
  "homepage": "https://zenorm.node.ltd",
@@ -15,10 +14,10 @@
15
14
  "dist"
16
15
  ],
17
16
  "scripts": {
18
- "build": "rimraf dist && tsc",
17
+ "build": "rimraf dist && tsc -p tsconfig.build.json",
19
18
  "prepack": "npm run build",
20
- "gen": "cd test && node --loader ts-node/esm ../src/bin/zenorm-generate.ts config.js",
21
- "t1": "cd test && cross-env DEBUG=* node --loader ts-node/esm t1.ts"
19
+ "gen": "cd test && node -r ts-node/register ../src/bin/zenorm-generate.ts config.js",
20
+ "t1": "cd test && cross-env DEBUG=* node -r ts-node/register t1.ts"
22
21
  },
23
22
  "keywords": [
24
23
  "mysql",
@@ -32,11 +31,11 @@
32
31
  "@types/node": "^16.18.126",
33
32
  "@zenorm/generate-mysql": "^2.2.1",
34
33
  "cross-env": "^7.0.3",
35
- "mysql-easy-query": "^3.16.1",
34
+ "mysql-easy-query": "^4.1.0",
36
35
  "rimraf": "^4.4.1",
37
36
  "ts-node": "^10.9.2",
38
- "typescript": "^5.9.3",
39
- "zenorm": "^4.3.0"
37
+ "typescript": "^6.0.3",
38
+ "zenorm": "^4.5.0"
40
39
  },
41
40
  "dependencies": {
42
41
  "pascal-case": "^3.1.2",