@joktec/mysql 0.0.84 → 0.0.86

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@joktec/mysql",
3
3
  "description": "JokTec - MySql Service",
4
- "version": "0.0.84",
4
+ "version": "0.0.86",
5
5
  "private": false,
6
6
  "license": "MIT",
7
7
  "author": "JokTec",
@@ -39,7 +39,7 @@
39
39
  "prepublishOnly": "yarn build",
40
40
  "format": "prettier \"./src/**/*.ts\" --ignore-path ./.prettierignore --write",
41
41
  "lint": "eslint --fix \"./src/**/*.ts\"",
42
- "dep:upgrade": "ncu -p yarn -f /^@joktec*/ -u",
42
+ "dep:upgrade": "ncu -p yarn -u",
43
43
  "gen:entity": "./bin/generate-entity.sh && yarn format && yarn lint",
44
44
  "test": "jest",
45
45
  "test:watch": "jest --watch",
@@ -48,17 +48,17 @@
48
48
  "test:e2e": "jest --config ./test/jest-e2e.json"
49
49
  },
50
50
  "dependencies": {
51
- "@joktec/core": "0.0.83",
51
+ "@joktec/core": "0.0.85",
52
52
  "lodash": "^4.17.21",
53
53
  "mysql": "2.18.1",
54
- "mysql2": "^3.1.2",
54
+ "mysql2": "^3.6.0",
55
55
  "reflect-metadata": "*",
56
- "sequelize": "^6.28.0",
56
+ "sequelize": "^6.32.1",
57
57
  "sequelize-typescript": "^2.1.5"
58
58
  },
59
59
  "devDependencies": {
60
- "@types/mysql": "^2.15.17",
61
- "@types/validator": "^13.7.12"
60
+ "@types/mysql": "^2.15.21",
61
+ "@types/validator": "^13.11.1"
62
62
  },
63
63
  "lint-staged": {
64
64
  "*.ts": [
@@ -85,5 +85,5 @@
85
85
  "!**/*.{d,enum}.ts"
86
86
  ]
87
87
  },
88
- "gitHead": "ca5cddaa27792a85f6b053a8168531f89b45b0fc"
88
+ "gitHead": "cf28d274a91ee7ddd3dcb5ef278af177ab791751"
89
89
  }
@@ -1,189 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const { camelCase, upperFirst, kebabCase, filter, orderBy } = require('lodash');
4
- const fs = require('fs');
5
- const knex = require('knex');
6
- const pluralize = require('pluralize');
7
- const schemaInspector = require('knex-schema-inspector');
8
- const { Command } = require('commander');
9
-
10
- const program = new Command();
11
- program
12
- .version('0.0.1')
13
- .option('-m, --mysql-url <string>', 'MySQL URL')
14
- .option('-t, --table-name <string>', 'Table name')
15
- .option('-e, --only-entity', 'Only Entity');
16
-
17
- program.parse(process.argv);
18
- const options = program.opts();
19
-
20
- // Connect to DB and get inspector
21
- const connUrl = options.mysqlUrl;
22
- const database = knex({ client: 'mysql', connection: connUrl });
23
- const inspector = schemaInspector.SchemaInspector(database);
24
-
25
- // Generate Entity
26
- const writeEntity = async (tableName) => {
27
- const entityPrefix = pluralize(tableName.split('_')[0]);
28
- const dir = `./src/entities/${entityPrefix}`;
29
- if (!fs.existsSync(dir)) fs.mkdirSync(dir);
30
- const filePath = `${dir}/${kebabCase(tableName)}.entity.ts`;
31
-
32
- const columns = await inspector.columnInfo(tableName);
33
- const className = upperFirst(camelCase(tableName + 'Entity'));
34
- const classMapper = upperFirst(camelCase(tableName + 'Mapper'));
35
-
36
- const lines = [
37
- `import { BaseEntity, MysqlMapper, linkTransform, toBool } from '@joktec/core';`,
38
- `import { ClassTransformOptions, Expose, instanceToPlain, plainToInstance, Transform } from 'class-transformer';`,
39
- `import { IsBoolean, IsDate, IsInt, IsNotEmpty, IsOptional, IsString } from 'class-validator';`,
40
- ``,
41
- `@Expose({ name: '${tableName}' })`,
42
- `export class ${className} extends BaseEntity {`,
43
- `\tconstructor(payload: Partial<${className}>) {`,
44
- `\t\tsuper(payload);`,
45
- `\t\tObject.assign(this, { ...payload });`,
46
- `\t}`,
47
- ];
48
-
49
- columns.map(column => {
50
- const { name, data_type, is_nullable, is_primary_key } = column;
51
- lines.push(`\t@Expose({ name: '${name}' })`);
52
- lines.push(is_nullable ? '\n@IsOptional()' : `\t@IsNotEmpty()`);
53
- const optional = is_nullable ? '?' : '!';
54
- const tsType =
55
- (['bit', 'boolean'].includes(data_type) && 'boolean') ||
56
- (['varchar', 'text', 'longtext'].includes(data_type) && 'string') ||
57
- (['int', 'tinyint', 'bigint', 'decimal', 'double'].includes(data_type) && 'number') ||
58
- (data_type.includes('unsigned') && 'number') ||
59
- (['datetime', 'date', 'timestamp', 'time'].includes(data_type) && 'Date') ||
60
- (['json'].includes(data_type) && 'any') ||
61
- 'unknown';
62
-
63
- const validator =
64
- (tsType == 'string' && `\t@IsString()`) ||
65
- (tsType == 'number' && `\t@IsInt()`) ||
66
- (tsType == 'Date' && `\t@IsDate()`) ||
67
- (tsType == 'boolean' && `\t@IsBoolean()\n\t@Transform(({ value }) => toBool(value), { toClassOnly: true })`) ||
68
- (tsType == 'any' && `\t@Transform(({ value }) => JSON.parse(value), { toClassOnly: true })\n\t@Transform(({ value }) => JSON.stringify(value), { toPlainOnly: true })`) ||
69
- undefined;
70
-
71
- if (validator) {
72
- lines.push(validator);
73
- }
74
-
75
- if (is_primary_key) {
76
- lines.push(`\t_id: ${tsType};`);
77
- } else {
78
- lines.push(`\t${camelCase(name)}${optional}: ${tsType};`);
79
- }
80
-
81
- lines.push('');
82
- });
83
- lines.push(`@Expose({ name: 'sqlId', toClassOnly: true })\nget sqlId() {return this._id;}`);
84
- lines.push('}');
85
-
86
- // Generate Mapper
87
- const mapperContent = `
88
- export class ${classMapper} extends MysqlMapper<${className}> {
89
- toPersistence = (domainModel: ${className}, opts?: ClassTransformOptions) => instanceToPlain<${className}>(domainModel, opts);
90
- toDomain = (persistenceModel: any, opts?: ClassTransformOptions): ${className} => plainToInstance<${className}, any>(${className}, persistenceModel, opts);
91
- }
92
- `;
93
- lines.push(mapperContent);
94
-
95
- // Create file
96
- fs.writeFileSync(filePath, lines.join('\n'));
97
- console.log('CREATE FILE:', filePath);
98
-
99
- // Update sub index
100
- const appendContent = `export * from './${kebabCase(tableName)}.entity';`;
101
- const indexPath = `${dir}/index.ts`;
102
- if (!fs.existsSync(indexPath)) {
103
- fs.closeSync(fs.openSync(indexPath, 'w'));
104
- console.log('CREATE FILE:', indexPath);
105
- }
106
-
107
- const indexContent = fs.readFileSync(indexPath).toString();
108
- if (!indexContent.includes(appendContent)) {
109
- fs.appendFileSync(indexPath, appendContent);
110
- console.log('UPDATE FILE:', indexPath);
111
- }
112
-
113
- // Update entity index
114
- const appendIndex = `export * from './${entityPrefix}';`;
115
- const rootIndexPath = `./src/entities/index.ts`;
116
- const rootIndexContent = fs.readFileSync(rootIndexPath).toString();
117
- if (!rootIndexContent.includes(appendIndex)) {
118
- fs.appendFileSync(rootIndexPath, appendIndex);
119
- console.log('UPDATE FILE:', rootIndexPath);
120
- }
121
- };
122
-
123
- const writeRepo = async (tableName) => {
124
- const entityPrefix = pluralize(tableName.split('_')[0]);
125
- const dir = `./src/repositories/${entityPrefix}`;
126
- if (!fs.existsSync(dir)) fs.mkdirSync(dir);
127
- const filePath = `${dir}/${kebabCase(tableName)}.repo.ts`;
128
-
129
- // Check primary key
130
- const columns = await inspector.columnInfo(tableName);
131
- const primaryKey = filter(columns, c => c.is_primary_key).pop();
132
- const tsType =
133
- (['varchar', 'text', 'longtext'].includes(primaryKey?.data_type) && 'string') ||
134
- (['int', 'tinyint', 'bigint', 'decimal', 'double', 'bit'].includes(primaryKey?.data_type) && 'number') ||
135
- (primaryKey?.data_type.includes('unsigned') && 'number') ||
136
- 'any';
137
-
138
- // Create file
139
- const entityName = upperFirst(camelCase(tableName + 'Entity'));
140
- const className = upperFirst(camelCase(tableName + 'Repo'));
141
- const classMapper = upperFirst(camelCase(tableName + 'Mapper'));
142
-
143
- const fileContent = `
144
- import { Injectable, MysqlRepo, MysqlService } from '@joktec/core';
145
- import { ${entityName}, ${classMapper} } from '../../entities';
146
-
147
- @Injectable()
148
- export class ${className} extends MysqlRepo<${entityName}, ${tsType}> {
149
- constructor(protected mysqlService: MysqlService) {
150
- super('${tableName}', mysqlService, new ${classMapper}());
151
- }
152
- }
153
- `;
154
- fs.writeFileSync(filePath, fileContent);
155
- console.log('CREATE FILE:', filePath);
156
-
157
- // Update index
158
- const appendContent = `export * from './${kebabCase(tableName)}.repo';`;
159
- const indexPath = `${dir}/index.ts`;
160
- if (!fs.existsSync(indexPath)) {
161
- fs.closeSync(fs.openSync(indexPath, 'w'));
162
- console.log('CREATE FILE:', indexPath);
163
- }
164
-
165
- const indexContent = fs.readFileSync(indexPath).toString();
166
- if (!indexContent.includes(appendContent)) {
167
- fs.appendFileSync(indexPath, appendContent);
168
- console.log('UPDATE FILE:', indexPath);
169
- }
170
-
171
- // Update repositories index
172
- const appendIndex = `export * from './${entityPrefix}';`;
173
- const rootIndexPath = `./src/repositories/index.ts`;
174
- const rootIndexContent = fs.readFileSync(rootIndexPath).toString();
175
- if (!rootIndexContent.includes(appendIndex)) {
176
- fs.appendFileSync(rootIndexPath, appendIndex);
177
- console.log('UPDATE FILE:', rootIndexPath);
178
- }
179
- };
180
-
181
- (async () => {
182
- console.log(`Generate from table:`, options.tableName);
183
-
184
- if (!fs.existsSync('./src/entities/')) fs.mkdirSync('./src/entities/');
185
- await writeEntity(options.tableName);
186
-
187
- if (!fs.existsSync('./src/repositories/')) fs.mkdirSync('./src/repositories/');
188
- await writeRepo(options.tableName);
189
- })().then(() => process.exit(0));