forked from CatsMiaow/nestjs-project-structure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entity.ts
executable file
·71 lines (64 loc) · 2.17 KB
/
entity.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* eslint-disable no-console, import/no-extraneous-dependencies */
/// <reference types="../typings/global" />
import { execSync } from 'child_process';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as path from 'path';
import prompts from 'prompts';
import * as rimraf from 'rimraf';
dotenv.config();
if (!process.env.DB_HOST) {
throw new Error('Create a .env file');
}
(async (): Promise<void> => {
const response = await prompts([{
type: 'text',
name: 'db',
message: 'Please enter a database name.',
validate: (value: string): boolean => !!value,
}, /* {
type: 'select',
name: 'db',
message: 'Please select a database name.',
choices: [
{ title: 'db1' },
{ title: 'db2' },
],
} */]);
const { db } = <{ db: string }>response;
const MODEL_DIR = path.join(__dirname, '../src/entity', db);
rimraf.sync(`${MODEL_DIR}/*`);
const generatorConfig = [
'--noConfig',
'--cf none', // file names
'--ce pascal', // class names
'--cp none', // property names
'--strictMode !', // strictPropertyInitialization
`--namingStrategy ${path.join(__dirname, 'NamingStrategy.js')}`,
`-h ${process.env.DB_HOST}`,
`-p ${process.env.DB_PORT}`,
// https://github.com/Kononnable/typeorm-model-generator/issues/204#issuecomment-533709527
// If you use multiple databases, add comma.
`-d ${db}`, // `-d ${db},`,
`-u ${process.env.DB_USER}`,
`-x ${process.env.DB_PASSWORD}`,
`-e ${process.env.DB_TYPE}`,
`-o ${MODEL_DIR}`,
];
try {
execSync(`typeorm-model-generator ${generatorConfig.join(' ')}`, { stdio: 'pipe' });
} catch (error) {
console.error(`> Failed to load '${db}' database.\n${error}`);
return;
}
const files = [];
fs.readdirSync(MODEL_DIR).forEach((file: string) => {
files.push(`export * from './${file.replace('.ts', '')}';`);
});
files.push('');
// export entity db tables
// AS-IS import { Tablename } from './entity/dbname/tablename';
// TO-BE import { Tablename } from './entity/dbname';
fs.writeFileSync(path.join(MODEL_DIR, 'index.ts'), files.join('\n'));
console.log(`> '${db}' database entities has been created: ${MODEL_DIR}`);
})();