-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
MigrationCreateCommand.ts
109 lines (93 loc) · 3.19 KB
/
MigrationCreateCommand.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { CommandUtils } from "./CommandUtils"
import { camelCase } from "../util/StringUtils"
import * as yargs from "yargs"
import chalk from "chalk"
import { PlatformTools } from "../platform/PlatformTools"
import path from "path"
/**
* Creates a new migration file.
*/
export class MigrationCreateCommand implements yargs.CommandModule {
command = "migration:create <path>"
describe = "Creates a new migration file."
builder(args: yargs.Argv) {
return args
.option("o", {
alias: "outputJs",
type: "boolean",
default: false,
describe:
"Generate a migration file on Javascript instead of Typescript",
})
.option("t", {
alias: "timestamp",
type: "number",
default: false,
describe: "Custom timestamp for the migration name",
})
}
async handler(args: yargs.Arguments) {
try {
const timestamp = CommandUtils.getTimestamp(args.timestamp)
const inputPath = (args.path as string).startsWith("/")
? (args.path as string)
: path.resolve(process.cwd(), args.path as string)
const filename = path.basename(inputPath)
const fullPath =
path.dirname(inputPath) + "/" + timestamp + "-" + filename
const fileContent = args.outputJs
? MigrationCreateCommand.getJavascriptTemplate(
filename,
timestamp,
)
: MigrationCreateCommand.getTemplate(filename, timestamp)
await CommandUtils.createFile(
fullPath + (args.outputJs ? ".js" : ".ts"),
fileContent,
)
console.log(
`Migration ${chalk.blue(
fullPath + (args.outputJs ? ".js" : ".ts"),
)} has been generated successfully.`,
)
} catch (err) {
PlatformTools.logCmdErr("Error during migration creation:", err)
process.exit(1)
}
}
// -------------------------------------------------------------------------
// Protected Static Methods
// -------------------------------------------------------------------------
/**
* Gets contents of the migration file.
*/
protected static getTemplate(name: string, timestamp: number): string {
return `import { MigrationInterface, QueryRunner } from "typeorm"
export class ${camelCase(
name,
true,
)}${timestamp} implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
}
public async down(queryRunner: QueryRunner): Promise<void> {
}
}
`
}
/**
* Gets contents of the migration file in Javascript.
*/
protected static getJavascriptTemplate(
name: string,
timestamp: number,
): string {
return `const { MigrationInterface, QueryRunner } = require("typeorm");
module.exports = class ${camelCase(name, true)}${timestamp} {
async up(queryRunner) {
}
async down(queryRunner) {
}
}
`
}
}