forked from typeorm/typeorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubscriberCreateCommand.ts
83 lines (71 loc) · 2.88 KB
/
SubscriberCreateCommand.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
72
73
74
75
76
77
78
79
80
81
82
83
import {ConnectionOptionsReader} from "../connection/ConnectionOptionsReader";
import {CommandUtils} from "./CommandUtils";
import * as yargs from "yargs";
import chalk from "chalk";
/**
* Generates a new subscriber.
*/
export class SubscriberCreateCommand implements yargs.CommandModule {
command = "subscriber:create";
describe = "Generates a new subscriber.";
builder(args: yargs.Argv) {
return args
.option("c", {
alias: "connection",
default: "default",
describe: "Name of the connection on which to run a query"
})
.option("n", {
alias: "name",
describe: "Name of the subscriber class.",
demand: true
})
.option("d", {
alias: "dir",
describe: "Directory where subscriber should be created."
})
.option("f", {
alias: "config",
default: "ormconfig",
describe: "Name of the file with connection configuration."
});
}
async handler(args: yargs.Arguments) {
try {
const fileContent = SubscriberCreateCommand.getTemplate(args.name as any);
const filename = args.name + ".ts";
let directory = args.dir as string;
// if directory is not set then try to open tsconfig and find default path there
if (!directory) {
try {
const connectionOptionsReader = new ConnectionOptionsReader({
root: process.cwd(),
configName: args.config as any
});
const connectionOptions = await connectionOptionsReader.get(args.connection as any);
directory = connectionOptions.cli ? (connectionOptions.cli.entitiesDir || "") : "";
} catch (err) { }
}
const path = (directory.startsWith("/") ? "" : process.cwd() + "/") + (directory ? (directory + "/") : "") + filename;
await CommandUtils.createFile(path, fileContent);
console.log(chalk.green(`Subscriber ${chalk.blue(path)} has been created successfully.`));
} catch (err) {
console.log(chalk.black.bgRed("Error during subscriber creation:"));
console.error(err);
process.exit(1);
}
}
// -------------------------------------------------------------------------
// Protected Static Methods
// -------------------------------------------------------------------------
/**
* Gets contents of the entity file.
*/
protected static getTemplate(name: string): string {
return `import {EventSubscriber, EntitySubscriberInterface} from "typeorm";
@EventSubscriber()
export class ${name} implements EntitySubscriberInterface<any> {
}
`;
}
}