UNPKG

20.2 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4var CommandUtils_1 = require("./CommandUtils");
5var path = require("path");
6var chalk = require("chalk");
7/**
8 * Generates a new project with TypeORM.
9 */
10var InitCommand = /** @class */ (function () {
11 function InitCommand() {
12 this.command = "init";
13 this.describe = "Generates initial TypeORM project structure. " +
14 "If name specified then creates files inside directory called as name. " +
15 "If its not specified then creates files inside current directory.";
16 }
17 InitCommand.prototype.builder = function (args) {
18 return args
19 .option("c", {
20 alias: "connection",
21 default: "default",
22 describe: "Name of the connection on which to run a query"
23 })
24 .option("n", {
25 alias: "name",
26 describe: "Name of the project directory."
27 })
28 .option("db", {
29 alias: "database",
30 describe: "Database type you'll use in your project."
31 })
32 .option("express", {
33 describe: "Indicates if express should be included in the project."
34 })
35 .option("docker", {
36 describe: "Set to true if docker-compose must be generated as well. False by default."
37 });
38 };
39 InitCommand.prototype.handler = function (args) {
40 return tslib_1.__awaiter(this, void 0, void 0, function () {
41 var database, isExpress, isDocker, basePath, projectName, packageJsonContents, err_1;
42 return tslib_1.__generator(this, function (_a) {
43 switch (_a.label) {
44 case 0:
45 _a.trys.push([0, 16, , 17]);
46 database = args.database || "mysql";
47 isExpress = args.express !== undefined ? true : false;
48 isDocker = args.docker !== undefined ? true : false;
49 basePath = process.cwd() + (args.name ? ("/" + args.name) : "");
50 projectName = args.name ? path.basename(args.name) : undefined;
51 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/package.json", InitCommand.getPackageJsonTemplate(projectName), false)];
52 case 1:
53 _a.sent();
54 if (!isDocker) return [3 /*break*/, 3];
55 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/docker-compose.yml", InitCommand.getDockerComposeTemplate(database), false)];
56 case 2:
57 _a.sent();
58 _a.label = 3;
59 case 3: return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/.gitignore", InitCommand.getGitIgnoreFile())];
60 case 4:
61 _a.sent();
62 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/README.md", InitCommand.getReadmeTemplate({ docker: isDocker }), false)];
63 case 5:
64 _a.sent();
65 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/tsconfig.json", InitCommand.getTsConfigTemplate())];
66 case 6:
67 _a.sent();
68 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/ormconfig.json", InitCommand.getOrmConfigTemplate(database))];
69 case 7:
70 _a.sent();
71 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/src/entity/User.ts", InitCommand.getUserEntityTemplate(database))];
72 case 8:
73 _a.sent();
74 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/src/index.ts", InitCommand.getAppIndexTemplate(isExpress))];
75 case 9:
76 _a.sent();
77 return [4 /*yield*/, CommandUtils_1.CommandUtils.createDirectories(basePath + "/src/migration")];
78 case 10:
79 _a.sent();
80 if (!isExpress) return [3 /*break*/, 13];
81 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/src/routes.ts", InitCommand.getRoutesTemplate())];
82 case 11:
83 _a.sent();
84 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/src/controller/UserController.ts", InitCommand.getControllerTemplate())];
85 case 12:
86 _a.sent();
87 _a.label = 13;
88 case 13: return [4 /*yield*/, CommandUtils_1.CommandUtils.readFile(basePath + "/package.json")];
89 case 14:
90 packageJsonContents = _a.sent();
91 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(basePath + "/package.json", InitCommand.appendPackageJson(packageJsonContents, database, isExpress))];
92 case 15:
93 _a.sent();
94 if (args.name) {
95 console.log(chalk.green("Project created inside " + chalk.blue(basePath) + " directory."));
96 }
97 else {
98 console.log(chalk.green("Project created inside current directory."));
99 }
100 return [3 /*break*/, 17];
101 case 16:
102 err_1 = _a.sent();
103 console.log(chalk.black.bgRed("Error during project initialization:"));
104 console.error(err_1);
105 process.exit(1);
106 return [3 /*break*/, 17];
107 case 17: return [2 /*return*/];
108 }
109 });
110 });
111 };
112 // -------------------------------------------------------------------------
113 // Protected Static Methods
114 // -------------------------------------------------------------------------
115 /**
116 * Gets contents of the ormconfig file.
117 */
118 InitCommand.getOrmConfigTemplate = function (database) {
119 var options = {};
120 switch (database) {
121 case "mysql":
122 Object.assign(options, {
123 type: "mysql",
124 host: "localhost",
125 port: 3306,
126 username: "test",
127 password: "test",
128 database: "test",
129 });
130 break;
131 case "mariadb":
132 Object.assign(options, {
133 type: "mariadb",
134 host: "localhost",
135 port: 3306,
136 username: "test",
137 password: "test",
138 database: "test",
139 });
140 break;
141 case "sqlite":
142 Object.assign(options, {
143 type: "sqlite",
144 "database": "database.sqlite",
145 });
146 break;
147 case "postgres":
148 Object.assign(options, {
149 "type": "postgres",
150 "host": "localhost",
151 "port": 5432,
152 "username": "test",
153 "password": "test",
154 "database": "test",
155 });
156 break;
157 case "cockroachdb":
158 Object.assign(options, {
159 "type": "cockroachdb",
160 "host": "localhost",
161 "port": 26257,
162 "username": "root",
163 "password": "",
164 "database": "defaultdb",
165 });
166 break;
167 case "mssql":
168 Object.assign(options, {
169 "type": "mssql",
170 "host": "localhost",
171 "username": "sa",
172 "password": "Admin12345",
173 "database": "tempdb",
174 });
175 break;
176 case "oracle":
177 Object.assign(options, {
178 "type": "oracle",
179 "host": "localhost",
180 "username": "system",
181 "password": "oracle",
182 "port": 1521,
183 "sid": "xe.oracle.docker",
184 });
185 break;
186 case "mongodb":
187 Object.assign(options, {
188 "type": "mongodb",
189 "database": "test",
190 });
191 break;
192 }
193 Object.assign(options, {
194 synchronize: true,
195 logging: false,
196 entities: [
197 "src/entity/**/*.ts"
198 ],
199 migrations: [
200 "src/migration/**/*.ts"
201 ],
202 subscribers: [
203 "src/subscriber/**/*.ts"
204 ],
205 cli: {
206 entitiesDir: "src/entity",
207 migrationsDir: "src/migration",
208 subscribersDir: "src/subscriber"
209 }
210 });
211 return JSON.stringify(options, undefined, 3);
212 };
213 /**
214 * Gets contents of the ormconfig file.
215 */
216 InitCommand.getTsConfigTemplate = function () {
217 return JSON.stringify({
218 compilerOptions: {
219 lib: ["es5", "es6"],
220 target: "es5",
221 module: "commonjs",
222 moduleResolution: "node",
223 outDir: "./build",
224 emitDecoratorMetadata: true,
225 experimentalDecorators: true,
226 sourceMap: true
227 }
228 }, undefined, 3);
229 };
230 /**
231 * Gets contents of the .gitignore file.
232 */
233 InitCommand.getGitIgnoreFile = function () {
234 return ".idea/\n.vscode/\nnode_modules/\nbuild/\ntmp/\ntemp/";
235 };
236 /**
237 * Gets contents of the user entity.
238 */
239 InitCommand.getUserEntityTemplate = function (database) {
240 return "import {Entity, " + (database === "mongodb" ? "ObjectIdColumn, ObjectID" : "PrimaryGeneratedColumn") + ", Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n " + (database === "mongodb" ? "@ObjectIdColumn()" : "@PrimaryGeneratedColumn()") + "\n id: " + (database === "mongodb" ? "ObjectID" : "number") + ";\n\n @Column()\n firstName: string;\n\n @Column()\n lastName: string;\n\n @Column()\n age: number;\n\n}\n";
241 };
242 /**
243 * Gets contents of the route file (used when express is enabled).
244 */
245 InitCommand.getRoutesTemplate = function () {
246 return "import {UserController} from \"./controller/UserController\";\n\nexport const Routes = [{\n method: \"get\",\n route: \"/users\",\n controller: UserController,\n action: \"all\"\n}, {\n method: \"get\",\n route: \"/users/:id\",\n controller: UserController,\n action: \"one\"\n}, {\n method: \"post\",\n route: \"/users\",\n controller: UserController,\n action: \"save\"\n}, {\n method: \"delete\",\n route: \"/users/:id\",\n controller: UserController,\n action: \"remove\"\n}];";
247 };
248 /**
249 * Gets contents of the user controller file (used when express is enabled).
250 */
251 InitCommand.getControllerTemplate = function () {
252 return "import {getRepository} from \"typeorm\";\nimport {NextFunction, Request, Response} from \"express\";\nimport {User} from \"../entity/User\";\n\nexport class UserController {\n\n private userRepository = getRepository(User);\n\n async all(request: Request, response: Response, next: NextFunction) {\n return this.userRepository.find();\n }\n\n async one(request: Request, response: Response, next: NextFunction) {\n return this.userRepository.findOne(request.params.id);\n }\n\n async save(request: Request, response: Response, next: NextFunction) {\n return this.userRepository.save(request.body);\n }\n\n async remove(request: Request, response: Response, next: NextFunction) {\n let userToRemove = await this.userRepository.findOne(request.params.id);\n await this.userRepository.remove(userToRemove);\n }\n\n}";
253 };
254 /**
255 * Gets contents of the main (index) application file.
256 */
257 InitCommand.getAppIndexTemplate = function (express) {
258 if (express) {
259 return "import \"reflect-metadata\";\nimport {createConnection} from \"typeorm\";\nimport * as express from \"express\";\nimport * as bodyParser from \"body-parser\";\nimport {Request, Response} from \"express\";\nimport {Routes} from \"./routes\";\nimport {User} from \"./entity/User\";\n\ncreateConnection().then(async connection => {\n\n // create express app\n const app = express();\n app.use(bodyParser.json());\n\n // register express routes from defined application routes\n Routes.forEach(route => {\n (app as any)[route.method](route.route, (req: Request, res: Response, next: Function) => {\n const result = (new (route.controller as any))[route.action](req, res, next);\n if (result instanceof Promise) {\n result.then(result => result !== null && result !== undefined ? res.send(result) : undefined);\n\n } else if (result !== null && result !== undefined) {\n res.json(result);\n }\n });\n });\n\n // setup express app here\n // ...\n\n // start express server\n app.listen(3000);\n\n // insert new users for test\n await connection.manager.save(connection.manager.create(User, {\n firstName: \"Timber\",\n lastName: \"Saw\",\n age: 27\n }));\n await connection.manager.save(connection.manager.create(User, {\n firstName: \"Phantom\",\n lastName: \"Assassin\",\n age: 24\n }));\n\n console.log(\"Express server has started on port 3000. Open http://localhost:3000/users to see results\");\n\n}).catch(error => console.log(error));\n";
260 }
261 else {
262 return "import \"reflect-metadata\";\nimport {createConnection} from \"typeorm\";\nimport {User} from \"./entity/User\";\n\ncreateConnection().then(async connection => {\n\n console.log(\"Inserting a new user into the database...\");\n const user = new User();\n user.firstName = \"Timber\";\n user.lastName = \"Saw\";\n user.age = 25;\n await connection.manager.save(user);\n console.log(\"Saved a new user with id: \" + user.id);\n\n console.log(\"Loading users from the database...\");\n const users = await connection.manager.find(User);\n console.log(\"Loaded users: \", users);\n\n console.log(\"Here you can setup and run express/koa/any other framework.\");\n\n}).catch(error => console.log(error));\n";
263 }
264 };
265 /**
266 * Gets contents of the new package.json file.
267 */
268 InitCommand.getPackageJsonTemplate = function (projectName) {
269 return JSON.stringify({
270 name: projectName || "new-typeorm-project",
271 version: "0.0.1",
272 description: "Awesome project developed with TypeORM.",
273 devDependencies: {},
274 dependencies: {},
275 scripts: {}
276 }, undefined, 3);
277 };
278 /**
279 * Gets contents of the new docker-compose.yml file.
280 */
281 InitCommand.getDockerComposeTemplate = function (database) {
282 switch (database) {
283 case "mysql":
284 return "version: '3'\nservices:\n\n mysql:\n image: \"mysql:5.7.10\"\n ports:\n - \"3306:3306\"\n environment:\n MYSQL_ROOT_PASSWORD: \"admin\"\n MYSQL_USER: \"test\"\n MYSQL_PASSWORD: \"test\"\n MYSQL_DATABASE: \"test\"\n\n";
285 case "mariadb":
286 return "version: '3'\nservices:\n\n mariadb:\n image: \"mariadb:10.1.16\"\n ports:\n - \"3306:3306\"\n environment:\n MYSQL_ROOT_PASSWORD: \"admin\"\n MYSQL_USER: \"test\"\n MYSQL_PASSWORD: \"test\"\n MYSQL_DATABASE: \"test\"\n\n";
287 case "postgres":
288 return "version: '3'\nservices:\n\n postgres:\n image: \"postgres:9.6.1\"\n ports:\n - \"5432:5432\"\n environment:\n POSTGRES_USER: \"test\"\n POSTGRES_PASSWORD: \"test\"\n POSTGRES_DB: \"test\"\n\n";
289 case "cockroachdb":
290 return "version: '3'\nservices:\n\n cockroachdb:\n image: \"cockroachdb/cockroach:v2.1.4\"\n command: start --insecure\n ports:\n - \"26257:26257\"\n\n";
291 case "sqlite":
292 return "version: '3'\nservices:\n";
293 case "oracle":
294 throw new Error("You cannot initialize a project with docker for Oracle driver yet."); // todo: implement for oracle as well
295 case "mssql":
296 return "version: '3'\nservices:\n\n mssql:\n image: \"microsoft/mssql-server-linux:rc2\"\n ports:\n - \"1433:1433\"\n environment:\n SA_PASSWORD: \"Admin12345\"\n ACCEPT_EULA: \"Y\"\n\n";
297 case "mongodb":
298 return "version: '3'\nservices:\n\n mongodb:\n image: \"mongo:4.0.6\"\n container_name: \"typeorm-mongodb\"\n ports:\n - \"27017:27017\"\n\n";
299 }
300 return "";
301 };
302 /**
303 * Gets contents of the new readme.md file.
304 */
305 InitCommand.getReadmeTemplate = function (options) {
306 var template = "# Awesome Project Build with TypeORM\n\nSteps to run this project:\n\n1. Run `npm i` command\n";
307 if (options.docker) {
308 template += "2. Run `docker-compose up` command\n";
309 }
310 else {
311 template += "2. Setup database settings inside `ormconfig.json` file\n";
312 }
313 template += "3. Run `npm start` command\n";
314 return template;
315 };
316 /**
317 * Appends to a given package.json template everything needed.
318 */
319 InitCommand.appendPackageJson = function (packageJsonContents, database, express /*, docker: boolean*/) {
320 var packageJson = JSON.parse(packageJsonContents);
321 if (!packageJson.devDependencies)
322 packageJson.devDependencies = {};
323 Object.assign(packageJson.devDependencies, {
324 "ts-node": "3.3.0",
325 "@types/node": "^8.0.29",
326 "typescript": "3.3.3333"
327 });
328 if (!packageJson.dependencies)
329 packageJson.dependencies = {};
330 Object.assign(packageJson.dependencies, {
331 "typeorm": require("../package.json").version,
332 "reflect-metadata": "^0.1.10"
333 });
334 switch (database) {
335 case "mysql":
336 case "mariadb":
337 packageJson.dependencies["mysql"] = "^2.14.1";
338 break;
339 case "postgres":
340 case "cockroachdb":
341 packageJson.dependencies["pg"] = "^7.3.0";
342 break;
343 case "sqlite":
344 packageJson.dependencies["sqlite3"] = "^4.0.3";
345 break;
346 case "oracle":
347 packageJson.dependencies["oracledb"] = "^1.13.1";
348 break;
349 case "mssql":
350 packageJson.dependencies["mssql"] = "^4.0.4";
351 break;
352 case "mongodb":
353 packageJson.dependencies["mongodb"] = "^3.0.8";
354 break;
355 }
356 if (express) {
357 packageJson.dependencies["express"] = "^4.15.4";
358 packageJson.dependencies["body-parser"] = "^1.18.1";
359 }
360 if (!packageJson.scripts)
361 packageJson.scripts = {};
362 Object.assign(packageJson.scripts, {
363 start: /*(docker ? "docker-compose up && " : "") + */ "ts-node src/index.ts"
364 });
365 return JSON.stringify(packageJson, undefined, 3);
366 };
367 return InitCommand;
368}());
369exports.InitCommand = InitCommand;
370
371//# sourceMappingURL=InitCommand.js.map