@joktec/mysql 0.0.68 → 0.0.70
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/LICENSE +22 -22
- package/README.md +118 -118
- package/bin/generate-entity.sh +189 -189
- package/dist/__tests__/mysql.utils.spec.d.ts +1 -1
- package/dist/__tests__/mysql.utils.spec.js +25 -25
- package/dist/index.d.ts +10 -10
- package/dist/index.js +28 -28
- package/dist/models/index.d.ts +3 -3
- package/dist/models/index.js +19 -19
- package/dist/models/mysql.model.d.ts +6 -6
- package/dist/models/mysql.model.js +35 -35
- package/dist/models/mysql.request.d.ts +10 -10
- package/dist/models/mysql.request.js +2 -2
- package/dist/models/mysql.response.d.ts +3 -3
- package/dist/models/mysql.response.js +2 -2
- package/dist/mysql.client.d.ts +8 -8
- package/dist/mysql.client.js +2 -2
- package/dist/mysql.config.d.ts +34 -34
- package/dist/mysql.config.js +119 -119
- package/dist/mysql.exception.d.ts +5 -5
- package/dist/mysql.exception.js +35 -35
- package/dist/mysql.module.d.ts +2 -2
- package/dist/mysql.module.js +22 -22
- package/dist/mysql.repo.d.ts +22 -22
- package/dist/mysql.repo.js +118 -118
- package/dist/mysql.service.d.ts +12 -12
- package/dist/mysql.service.js +81 -81
- package/dist/mysql.utils.d.ts +6 -6
- package/dist/mysql.utils.js +49 -49
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -3
package/LICENSE
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
(The MIT License)
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2023 JokTec <trangiabao1203@gmail.com>
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining
|
|
6
|
-
a copy of this software and associated documentation files (the
|
|
7
|
-
'Software'), to deal in the Software without restriction, including
|
|
8
|
-
without limitation the rights to use, copy, modify, merge, publish,
|
|
9
|
-
distribute, sublicense, and/or sell copies of the Software, and to
|
|
10
|
-
permit persons to whom the Software is furnished to do so, subject to
|
|
11
|
-
the following conditions:
|
|
12
|
-
|
|
13
|
-
The above copyright notice and this permission notice shall be
|
|
14
|
-
included in all copies or substantial portions of the Software.
|
|
15
|
-
|
|
16
|
-
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
-
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
-
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
19
|
-
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
20
|
-
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
21
|
-
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
22
|
-
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
1
|
+
(The MIT License)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 JokTec <trangiabao1203@gmail.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
6
|
+
a copy of this software and associated documentation files (the
|
|
7
|
+
'Software'), to deal in the Software without restriction, including
|
|
8
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
9
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
10
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
11
|
+
the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be
|
|
14
|
+
included in all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
19
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
20
|
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
21
|
+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
22
|
+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,118 +1,118 @@
|
|
|
1
|
-
<div align="center">
|
|
2
|
-
<h1>@joktec/mysql</h1>
|
|
3
|
-
<p>A NestJS library that provides a wrapper around the `sequelize` and `sequelize-typescript` libraries for MySQL databases.</p>
|
|
4
|
-
</div>
|
|
5
|
-
|
|
6
|
-
## Table of Contents
|
|
7
|
-
1. [Introduction](#introduction)
|
|
8
|
-
2. [Installation](#installation)
|
|
9
|
-
3. [Getting Started](#getting-started)
|
|
10
|
-
4. [Reference](#reference)
|
|
11
|
-
5. [Contributing](#contributing)
|
|
12
|
-
|
|
13
|
-
## Introduction
|
|
14
|
-
This library provides an easy-to-use interface for working with MySQL databases in NestJS applications. It is built on top of the popular `sequelize` and `sequelize-typescript` libraries, and provides a set of convenient abstractions for working with these libraries.
|
|
15
|
-
|
|
16
|
-
## Installation
|
|
17
|
-
To install this library, use either `npm` or `yarn`:
|
|
18
|
-
|
|
19
|
-
```bash
|
|
20
|
-
npm install @joktec/mysql
|
|
21
|
-
# or
|
|
22
|
-
yarn add @joktec/mysql
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
## Getting Started
|
|
26
|
-
### Configuration
|
|
27
|
-
To use this library, you must first provide the necessary configuration. This can be done by creating a config.yml file in your application's root directory, with the following content:
|
|
28
|
-
```yaml
|
|
29
|
-
mysql:
|
|
30
|
-
host: localhost
|
|
31
|
-
port: 3306
|
|
32
|
-
user: my_user
|
|
33
|
-
password: my_pass
|
|
34
|
-
database: my_database
|
|
35
|
-
```
|
|
36
|
-
Replace the values with your actual database connection information.
|
|
37
|
-
|
|
38
|
-
### Module
|
|
39
|
-
Once you have provided the configuration, you can create a MysqlModule in your NestJS application:
|
|
40
|
-
```typescript
|
|
41
|
-
import { CoreModule, Module } from '@joktec/core';
|
|
42
|
-
import { MysqlModule } from '@joktec/mysql';
|
|
43
|
-
|
|
44
|
-
@Module({
|
|
45
|
-
imports: [CoreModule, MysqlModule],
|
|
46
|
-
})
|
|
47
|
-
export class AppModule {}
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
### Service
|
|
51
|
-
You can then use the MysqlService to interact with the database:
|
|
52
|
-
```typescript
|
|
53
|
-
import { Injectable } from '@joktec/core';
|
|
54
|
-
import { MysqlService } from '@joktec/mysql';
|
|
55
|
-
|
|
56
|
-
@Injectable()
|
|
57
|
-
export class UserService {
|
|
58
|
-
constructor(private readonly mysqlService: MysqlService) {}
|
|
59
|
-
|
|
60
|
-
async getUsers() {
|
|
61
|
-
const users = await this.mysqlService.getModel(User).findAll();
|
|
62
|
-
return users;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
### Repository
|
|
68
|
-
#### Define a Model
|
|
69
|
-
You can define a model using `@joktec/mysql` (based on interface of `sequelize-typescript`):
|
|
70
|
-
```typescript
|
|
71
|
-
import { Table, Column, Model } from '@joktec/mysql';
|
|
72
|
-
|
|
73
|
-
@Table
|
|
74
|
-
export class User extends Model<User> {
|
|
75
|
-
@Column
|
|
76
|
-
name: string;
|
|
77
|
-
|
|
78
|
-
@Column
|
|
79
|
-
email: string;
|
|
80
|
-
}
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
#### Define a Repository
|
|
84
|
-
You can create a repository for your model by extending the MysqlRepository class and providing the model type as a generic argument:
|
|
85
|
-
```typescript
|
|
86
|
-
import { Injectable } from '@nestjs/common';
|
|
87
|
-
import { MysqlRepository } from '@joktec/mysql';
|
|
88
|
-
import { User } from './user.model';
|
|
89
|
-
|
|
90
|
-
@Injectable()
|
|
91
|
-
export class UserRepository extends MysqlRepository<User> {}
|
|
92
|
-
```
|
|
93
|
-
#### Using Repository in Service
|
|
94
|
-
You can then use the repository in your service:
|
|
95
|
-
```typescript
|
|
96
|
-
import { Injectable } from '@nestjs/common';
|
|
97
|
-
import { UserRepository } from './user.repository';
|
|
98
|
-
|
|
99
|
-
@Injectable()
|
|
100
|
-
export class UserService {
|
|
101
|
-
constructor(private readonly userRepository: UserRepository) {}
|
|
102
|
-
|
|
103
|
-
async getUsers() {
|
|
104
|
-
const users = await this.userRepository.findAll();
|
|
105
|
-
return users;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
```
|
|
109
|
-
|
|
110
|
-
## Reference
|
|
111
|
-
[sequelize](https://www.npmjs.com/package/sequelize)
|
|
112
|
-
|
|
113
|
-
[sequelize-typescript](https://www.npmjs.com/package/sequelize-typescript)
|
|
114
|
-
|
|
115
|
-
## Contributing
|
|
116
|
-
Contributions to `@joktec/mysql` are welcome. If you would like to contribute, please fork the repository, make your changes, and submit a pull request.
|
|
117
|
-
|
|
118
|
-
Please make sure to update tests as appropriate.
|
|
1
|
+
<div align="center">
|
|
2
|
+
<h1>@joktec/mysql</h1>
|
|
3
|
+
<p>A NestJS library that provides a wrapper around the `sequelize` and `sequelize-typescript` libraries for MySQL databases.</p>
|
|
4
|
+
</div>
|
|
5
|
+
|
|
6
|
+
## Table of Contents
|
|
7
|
+
1. [Introduction](#introduction)
|
|
8
|
+
2. [Installation](#installation)
|
|
9
|
+
3. [Getting Started](#getting-started)
|
|
10
|
+
4. [Reference](#reference)
|
|
11
|
+
5. [Contributing](#contributing)
|
|
12
|
+
|
|
13
|
+
## Introduction
|
|
14
|
+
This library provides an easy-to-use interface for working with MySQL databases in NestJS applications. It is built on top of the popular `sequelize` and `sequelize-typescript` libraries, and provides a set of convenient abstractions for working with these libraries.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
To install this library, use either `npm` or `yarn`:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @joktec/mysql
|
|
21
|
+
# or
|
|
22
|
+
yarn add @joktec/mysql
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Getting Started
|
|
26
|
+
### Configuration
|
|
27
|
+
To use this library, you must first provide the necessary configuration. This can be done by creating a config.yml file in your application's root directory, with the following content:
|
|
28
|
+
```yaml
|
|
29
|
+
mysql:
|
|
30
|
+
host: localhost
|
|
31
|
+
port: 3306
|
|
32
|
+
user: my_user
|
|
33
|
+
password: my_pass
|
|
34
|
+
database: my_database
|
|
35
|
+
```
|
|
36
|
+
Replace the values with your actual database connection information.
|
|
37
|
+
|
|
38
|
+
### Module
|
|
39
|
+
Once you have provided the configuration, you can create a MysqlModule in your NestJS application:
|
|
40
|
+
```typescript
|
|
41
|
+
import { CoreModule, Module } from '@joktec/core';
|
|
42
|
+
import { MysqlModule } from '@joktec/mysql';
|
|
43
|
+
|
|
44
|
+
@Module({
|
|
45
|
+
imports: [CoreModule, MysqlModule],
|
|
46
|
+
})
|
|
47
|
+
export class AppModule {}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Service
|
|
51
|
+
You can then use the MysqlService to interact with the database:
|
|
52
|
+
```typescript
|
|
53
|
+
import { Injectable } from '@joktec/core';
|
|
54
|
+
import { MysqlService } from '@joktec/mysql';
|
|
55
|
+
|
|
56
|
+
@Injectable()
|
|
57
|
+
export class UserService {
|
|
58
|
+
constructor(private readonly mysqlService: MysqlService) {}
|
|
59
|
+
|
|
60
|
+
async getUsers() {
|
|
61
|
+
const users = await this.mysqlService.getModel(User).findAll();
|
|
62
|
+
return users;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Repository
|
|
68
|
+
#### Define a Model
|
|
69
|
+
You can define a model using `@joktec/mysql` (based on interface of `sequelize-typescript`):
|
|
70
|
+
```typescript
|
|
71
|
+
import { Table, Column, Model } from '@joktec/mysql';
|
|
72
|
+
|
|
73
|
+
@Table
|
|
74
|
+
export class User extends Model<User> {
|
|
75
|
+
@Column
|
|
76
|
+
name: string;
|
|
77
|
+
|
|
78
|
+
@Column
|
|
79
|
+
email: string;
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
#### Define a Repository
|
|
84
|
+
You can create a repository for your model by extending the MysqlRepository class and providing the model type as a generic argument:
|
|
85
|
+
```typescript
|
|
86
|
+
import { Injectable } from '@nestjs/common';
|
|
87
|
+
import { MysqlRepository } from '@joktec/mysql';
|
|
88
|
+
import { User } from './user.model';
|
|
89
|
+
|
|
90
|
+
@Injectable()
|
|
91
|
+
export class UserRepository extends MysqlRepository<User> {}
|
|
92
|
+
```
|
|
93
|
+
#### Using Repository in Service
|
|
94
|
+
You can then use the repository in your service:
|
|
95
|
+
```typescript
|
|
96
|
+
import { Injectable } from '@nestjs/common';
|
|
97
|
+
import { UserRepository } from './user.repository';
|
|
98
|
+
|
|
99
|
+
@Injectable()
|
|
100
|
+
export class UserService {
|
|
101
|
+
constructor(private readonly userRepository: UserRepository) {}
|
|
102
|
+
|
|
103
|
+
async getUsers() {
|
|
104
|
+
const users = await this.userRepository.findAll();
|
|
105
|
+
return users;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Reference
|
|
111
|
+
[sequelize](https://www.npmjs.com/package/sequelize)
|
|
112
|
+
|
|
113
|
+
[sequelize-typescript](https://www.npmjs.com/package/sequelize-typescript)
|
|
114
|
+
|
|
115
|
+
## Contributing
|
|
116
|
+
Contributions to `@joktec/mysql` are welcome. If you would like to contribute, please fork the repository, make your changes, and submit a pull request.
|
|
117
|
+
|
|
118
|
+
Please make sure to update tests as appropriate.
|
package/bin/generate-entity.sh
CHANGED
|
@@ -1,189 +1,189 @@
|
|
|
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));
|
|
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));
|