@expressots/cli 1.10.0 → 1.11.0

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/bin/cli.js CHANGED
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const process_1 = require("process");
7
9
  const yargs_1 = __importDefault(require("yargs"));
8
10
  const helpers_1 = require("yargs/helpers");
9
11
  const project_commands_1 = require("./commands/project.commands");
@@ -11,10 +13,9 @@ const generate_1 = require("./generate");
11
13
  const cli_1 = require("./help/cli");
12
14
  const info_1 = require("./info");
13
15
  const new_1 = require("./new");
14
- const cli_2 = require("./providers/create/cli");
15
16
  const providers_1 = require("./providers");
16
- const chalk_1 = __importDefault(require("chalk"));
17
- const process_1 = require("process");
17
+ const cli_2 = require("./providers/create/cli");
18
+ const cli_ui_1 = require("./utils/cli-ui");
18
19
  process_1.stdout.write(`\n${[chalk_1.default.bold.green("🐎 Expressots")]}\n\n`);
19
20
  (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
20
21
  .scriptName("expressots")
@@ -28,6 +29,32 @@ process_1.stdout.write(`\n${[chalk_1.default.bold.green("🐎 Expressots")]}\n\n
28
29
  .command((0, info_1.infoProject)())
29
30
  .command((0, cli_1.helpCommand)())
30
31
  .demandCommand(1, "You need at least one command before moving on")
32
+ .strict()
33
+ .fail((msg, err, yargs) => {
34
+ if (msg) {
35
+ if (msg.includes("Unknown argument")) {
36
+ // Get the command name
37
+ const command = process.argv[2];
38
+ if (command === "run") {
39
+ (0, cli_ui_1.printError)(`The "run" command has been removed. Use "dev", "prod" or "build" instead.`, "expressots help");
40
+ }
41
+ else {
42
+ (0, cli_ui_1.printError)(`Unknown command [${command}]. For help type`, "expressots help");
43
+ }
44
+ }
45
+ else {
46
+ (0, cli_ui_1.printError)(msg, "expressots help");
47
+ }
48
+ }
49
+ else if (err) {
50
+ (0, cli_ui_1.printError)(err.message, "command-validator");
51
+ }
52
+ else {
53
+ (0, cli_ui_1.printError)("Command invalid. Consider updating the CLI.", "command-validator");
54
+ yargs.showHelp();
55
+ }
56
+ process.exit(1);
57
+ })
31
58
  .epilog(`${chalk_1.default.bold.green("For more information:")} \n\n` +
32
59
  "🌐 visit:\t https://expresso-ts.com\n" +
33
60
  "💖 Sponsor:\t https://github.com/sponsors/expressots")
@@ -1,7 +1,26 @@
1
1
  import { CommandModule } from "yargs";
2
+ /**
3
+ * Dev command module
4
+ * @type {CommandModule<object, object>}
5
+ * @returns The command module
6
+ */
2
7
  export declare const devCommand: CommandModule<object, object>;
8
+ /**
9
+ * Build command module
10
+ * @type {CommandModule<object, object>}
11
+ * @returns The command module
12
+ */
3
13
  export declare const buildCommand: CommandModule<object, object>;
14
+ /**
15
+ * Prod command module
16
+ * @type {CommandModule<object, object>}
17
+ * @returns The command module
18
+ */
4
19
  export declare const prodCommand: CommandModule<object, object>;
20
+ /**
21
+ * Helper function to run a command
22
+ * @param command The command to run
23
+ */
5
24
  export declare const runCommand: ({ command, }: {
6
25
  command: string;
7
26
  }) => Promise<void>;
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
27
  };
@@ -6,10 +29,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
29
  exports.runCommand = exports.prodCommand = exports.buildCommand = exports.devCommand = void 0;
7
30
  const child_process_1 = require("child_process");
8
31
  const fs_1 = require("fs");
9
- const path_1 = __importDefault(require("path"));
32
+ const os_1 = __importDefault(require("os"));
33
+ const path_1 = __importStar(require("path"));
10
34
  const cli_ui_1 = require("../utils/cli-ui");
11
35
  const compiler_1 = __importDefault(require("../utils/compiler"));
12
- const os_1 = __importDefault(require("os"));
36
+ /**
37
+ * Load tsconfig path and extract outDir
38
+ */
39
+ const tsconfigBuildPath = (0, path_1.join)(process.cwd(), "tsconfig.build.json");
40
+ const tsconfig = JSON.parse((0, fs_1.readFileSync)(tsconfigBuildPath, "utf-8"));
41
+ const outDir = tsconfig.compilerOptions.outDir;
13
42
  /**
14
43
  * Load the configuration from the compiler
15
44
  * @param compiler The compiler to load the configuration from
@@ -31,6 +60,42 @@ const nonOpinionatedConfig = [
31
60
  "dotenv/config",
32
61
  "./src/main.ts",
33
62
  ];
63
+ /**
64
+ * Dev command module
65
+ * @type {CommandModule<object, object>}
66
+ * @returns The command module
67
+ */
68
+ exports.devCommand = {
69
+ command: "dev",
70
+ describe: "Start development server.",
71
+ handler: async () => {
72
+ await (0, exports.runCommand)({ command: "dev" });
73
+ },
74
+ };
75
+ /**
76
+ * Build command module
77
+ * @type {CommandModule<object, object>}
78
+ * @returns The command module
79
+ */
80
+ exports.buildCommand = {
81
+ command: "build",
82
+ describe: "Build the project.",
83
+ handler: async () => {
84
+ await (0, exports.runCommand)({ command: "build" });
85
+ },
86
+ };
87
+ /**
88
+ * Prod command module
89
+ * @type {CommandModule<object, object>}
90
+ * @returns The command module
91
+ */
92
+ exports.prodCommand = {
93
+ command: "prod",
94
+ describe: "Run in production mode.",
95
+ handler: async () => {
96
+ await (0, exports.runCommand)({ command: "prod" });
97
+ },
98
+ };
34
99
  /**
35
100
  * Helper function to execute a command
36
101
  * @param command The command to execute
@@ -55,17 +120,23 @@ function execCmd(command, args, cwd = process.cwd()) {
55
120
  });
56
121
  });
57
122
  }
58
- // Helper to delete the dist directory
123
+ /**
124
+ * Helper function to clean the dist directory
125
+ */
59
126
  const cleanDist = async () => {
60
- await fs_1.promises.rm("./dist", { recursive: true, force: true });
61
- (0, cli_ui_1.printSuccess)("Deleted dist directory", "clean-dist");
127
+ await fs_1.promises.rm(outDir, { recursive: true, force: true });
128
+ (0, cli_ui_1.printSuccess)(`Clean ${outDir} directory`, "clean-dist");
62
129
  };
63
- // Helper to compile TypeScript
130
+ /**
131
+ * Helper function to compile TypeScript
132
+ */
64
133
  const compileTypescript = async () => {
65
134
  await execCmd("npx", ["tsc", "-p", "tsconfig.build.json"]);
66
135
  (0, cli_ui_1.printSuccess)("Built successfully", "compile-typescript");
67
136
  };
68
- // Helper to copy files
137
+ /**
138
+ * Helper function to copy files to the dist directory
139
+ */
69
140
  const copyFiles = async () => {
70
141
  const { opinionated } = await compiler_1.default.loadConfig();
71
142
  let filesToCopy = [];
@@ -80,36 +151,21 @@ const copyFiles = async () => {
80
151
  filesToCopy = ["tsconfig.json", "package.json"];
81
152
  }
82
153
  filesToCopy.forEach((file) => {
83
- fs_1.promises.copyFile(file, path_1.default.join("./dist", path_1.default.basename(file)));
154
+ fs_1.promises.copyFile(file, (0, path_1.join)(outDir, path_1.default.basename(file)));
84
155
  });
85
156
  };
86
- // Helper clear screen
157
+ /**
158
+ * Helper function to clear the screen
159
+ */
87
160
  const clearScreen = () => {
88
161
  const platform = os_1.default.platform();
89
162
  const command = platform === "win32" ? "cls" : "clear";
90
163
  (0, child_process_1.spawn)(command, { stdio: "inherit", shell: true });
91
164
  };
92
- exports.devCommand = {
93
- command: "dev",
94
- describe: "Start development server.",
95
- handler: async () => {
96
- await (0, exports.runCommand)({ command: "dev" });
97
- },
98
- };
99
- exports.buildCommand = {
100
- command: "build",
101
- describe: "Build the project.",
102
- handler: async () => {
103
- await (0, exports.runCommand)({ command: "build" });
104
- },
105
- };
106
- exports.prodCommand = {
107
- command: "prod",
108
- describe: "Run in production mode.",
109
- handler: async () => {
110
- await (0, exports.runCommand)({ command: "prod" });
111
- },
112
- };
165
+ /**
166
+ * Helper function to run a command
167
+ * @param command The command to run
168
+ */
113
169
  const runCommand = async ({ command, }) => {
114
170
  const { opinionated } = await compiler_1.default.loadConfig();
115
171
  try {
@@ -118,23 +174,31 @@ const runCommand = async ({ command, }) => {
118
174
  execCmd("tsnd", opinionated ? opinionatedConfig : nonOpinionatedConfig);
119
175
  break;
120
176
  case "build":
177
+ if (!outDir) {
178
+ (0, cli_ui_1.printError)("Cannot build project. Please provide an outDir in tsconfig.build.json", "build-command");
179
+ process.exit(1);
180
+ }
121
181
  await cleanDist();
122
182
  await compileTypescript();
123
183
  await copyFiles();
124
184
  break;
125
185
  case "prod": {
186
+ if (!outDir) {
187
+ (0, cli_ui_1.printError)("Cannot run in prod mode. Please provide an outDir in tsconfig.build.json", "prod-command");
188
+ process.exit(1);
189
+ }
126
190
  let config = [];
127
191
  if (opinionated) {
128
192
  config = [
129
193
  "-r",
130
194
  "dotenv/config",
131
195
  "-r",
132
- "./dist/register-path.js",
133
- "./dist/src/main.js",
196
+ `./${outDir}/register-path.js`,
197
+ `./${outDir}/src/main.js`,
134
198
  ];
135
199
  }
136
200
  else {
137
- config = ["-r", "dotenv/config", "./dist/main.js"];
201
+ config = ["-r", "dotenv/config", `./${outDir}/main.js`];
138
202
  }
139
203
  clearScreen();
140
204
  execCmd("node", config);
@@ -1,2 +1 @@
1
- declare const infoForm: () => void;
2
- export { infoForm };
1
+ export declare const infoForm: () => void;
package/bin/info/form.js CHANGED
@@ -9,6 +9,7 @@ const path_1 = __importDefault(require("path"));
9
9
  const fs_1 = __importDefault(require("fs"));
10
10
  const os_1 = __importDefault(require("os"));
11
11
  const cli_ui_1 = require("../utils/cli-ui");
12
+ const axios_1 = __importDefault(require("axios"));
12
13
  function getInfosFromPackage() {
13
14
  try {
14
15
  // Get the absolute path of the input directory parameter
@@ -32,5 +33,16 @@ const infoForm = () => {
32
33
  console.log(chalk_1.default.green("System information:"));
33
34
  console.log(chalk_1.default.white(`\tOS Version: ${os_1.default.version()}`));
34
35
  console.log(chalk_1.default.white(`\tNodeJS version: ${process.version}`));
36
+ currentCLIVersion();
35
37
  };
36
38
  exports.infoForm = infoForm;
39
+ async function currentCLIVersion() {
40
+ try {
41
+ const response = await axios_1.default.get("https://api.github.com/repos/expressots/expressots-cli/releases");
42
+ const latestRelease = `v${response.data[0].tag_name}`;
43
+ (0, cli_ui_1.printSuccess)("CLI version:", latestRelease);
44
+ }
45
+ catch (error) {
46
+ (0, cli_ui_1.printError)("Error:", error.message);
47
+ }
48
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressots/cli",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "Expressots CLI - modern, fast, lightweight nodejs web framework (@cli)",
5
5
  "author": "Richard Zampieri",
6
6
  "license": "MIT",
@@ -36,7 +36,7 @@
36
36
  "start": "node ./bin/cli.js",
37
37
  "start:dev": "tsnd ./src/cli.ts",
38
38
  "build": "npm run clean && tsc -p tsconfig.json && yarn cp:templates && chmod +x ./bin/cli.js",
39
- "cp:templates": "cp -r ./src/generate/templates ./bin/generate/templates && cp -r ./src/providers/prisma/templates ./bin/providers/prisma/templates",
39
+ "cp:templates": "cp -r ./src/generate/templates ./bin/generate/templates",
40
40
  "clean": "rimraf ./bin",
41
41
  "prepublish": "npm run build && npm pack",
42
42
  "publish": "npm publish --tag latest",
@@ -50,6 +50,7 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "@expressots/boost-ts": "1.3.0",
53
+ "axios": "^1.7.3",
53
54
  "chalk-animation": "2.0.3",
54
55
  "cli-progress": "3.12.0",
55
56
  "cli-table3": "0.6.5",
@@ -1,2 +0,0 @@
1
- declare const prismaProvider: (version: string, providerVersion: string) => Promise<void>;
2
- export { prismaProvider };
@@ -1,279 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.prismaProvider = void 0;
7
- const chalk_1 = __importDefault(require("chalk"));
8
- const inquirer_1 = __importDefault(require("inquirer"));
9
- const node_child_process_1 = require("node:child_process");
10
- const node_fs_1 = __importDefault(require("node:fs"));
11
- const cli_ui_1 = require("../../utils/cli-ui");
12
- const node_path_1 = __importDefault(require("node:path"));
13
- const node_process_1 = require("node:process");
14
- const compiler_1 = __importDefault(require("../../utils/compiler"));
15
- const find_folder_1 = require("../../utils/find-folder");
16
- const prismaProvider = async (version, providerVersion) => {
17
- const choices = [
18
- { name: "CockroachDB", value: "cockroachdb" },
19
- { name: "Microsoft SQL Server", value: "sqlserver" },
20
- { name: "MongoDB", value: "mongodb" },
21
- { name: "MySQL", value: "mysql" },
22
- { name: "PostgreSQL", value: "postgresql" },
23
- { name: "SQLite", value: "sqlite" },
24
- ];
25
- const drivers = {
26
- PostgreSQL: "pg",
27
- MySQL: "mysql2",
28
- SQLite: "sqlite3",
29
- "Microsoft SQL Server": "mssql",
30
- MongoDB: "mongodb",
31
- CockroachDB: "pg",
32
- };
33
- const answerPt1 = await inquirer_1.default.prompt([
34
- {
35
- type: "input",
36
- name: "prismaClientVersion",
37
- message: "Type the prisma client version (default=latest):",
38
- default: "latest",
39
- transformer: (input) => {
40
- return chalk_1.default.yellow(chalk_1.default.bold(input));
41
- },
42
- },
43
- {
44
- type: "input",
45
- name: "schemaName",
46
- message: "Type the schema name (default=schema):",
47
- default: "schema",
48
- transformer: (input) => {
49
- return chalk_1.default.yellow(chalk_1.default.bold(input));
50
- },
51
- },
52
- {
53
- type: "input",
54
- name: "schemaPath",
55
- message: "Where do you want to save your prisma schema (default=./):",
56
- default: ".",
57
- transformer: (input) => {
58
- return chalk_1.default.yellow(chalk_1.default.bold(input));
59
- },
60
- },
61
- {
62
- type: "list",
63
- name: "databaseName",
64
- message: "Select your database:",
65
- choices: choices.map((choice) => choice.name),
66
- },
67
- ]);
68
- const answerPt2 = await inquirer_1.default.prompt([
69
- {
70
- type: "confirm",
71
- name: "installDriver",
72
- message: `Do you want to install the latest recommended database driver for ${answerPt1.databaseName}?`,
73
- default: true,
74
- },
75
- {
76
- type: "confirm",
77
- name: "baseRepository",
78
- message: "Do you want to add BaseRepository Pattern in this project?\nthis will replace the existing BaseRepository and BaseRespositoryInterface if it exists.",
79
- default: true,
80
- },
81
- {
82
- type: "confirm",
83
- name: "confirm",
84
- message: "Do you want to add prisma provider in this project?",
85
- default: true,
86
- },
87
- ]);
88
- const answer = { ...answerPt1, ...answerPt2 };
89
- if (answer.confirm) {
90
- // Find which package manager the user has used to install the desired prisma version
91
- const packageManager = node_fs_1.default.existsSync("package-lock.json" || "yarn.lock" || "pnpm-lock.yaml")
92
- ? "npm"
93
- : node_fs_1.default.existsSync("yarn.lock")
94
- ? "yarn"
95
- : node_fs_1.default.existsSync("pnpm-lock.yaml")
96
- ? "pnpm"
97
- : null;
98
- if (packageManager) {
99
- // Install prisma in the project
100
- console.log(`Installing prisma with ${packageManager}...`);
101
- await execProcess({
102
- commandArg: packageManager,
103
- args: ["add", `prisma@${providerVersion}`, "-D"],
104
- directory: process.cwd(),
105
- });
106
- // Install Prisma Client
107
- console.log(`Installing Prisma Client with ${packageManager}...`);
108
- await execProcess({
109
- commandArg: packageManager,
110
- args: ["add", `@prisma/client@${answer.prismaClientVersion}`],
111
- directory: process.cwd(),
112
- });
113
- if (answer.installDriver) {
114
- // Install database driver
115
- console.log(`Installing the latest recommended database driver for ${answer.databaseName}: ${drivers[answer.databaseName]} ...`);
116
- await execProcess({
117
- commandArg: packageManager,
118
- args: ["add", drivers[answer.databaseName]],
119
- directory: process.cwd(),
120
- });
121
- }
122
- // Install @expressots/prisma in the project
123
- console.log(`Installing @expressots/prisma with ${packageManager}...`);
124
- await execProcess({
125
- commandArg: packageManager,
126
- args: ["add", `@expressots/prisma@${version}`],
127
- directory: process.cwd(),
128
- });
129
- }
130
- else {
131
- (0, cli_ui_1.printError)(`Could not find a package manager installed in this project.\nPlease install prisma and @expressots/prisma manually.`, "prisma");
132
- process.exit(1);
133
- }
134
- // Map choices to find the corresponding value
135
- answer.databaseName = choices.find((choice) => choice.name === answer.databaseName)?.value;
136
- // Init prisma
137
- console.log(`Initializing prisma...`);
138
- const prismaFolder = (0, find_folder_1.hasFolder)(process.cwd(), ["node_modules", ".git"]);
139
- if (prismaFolder.found) {
140
- const prismaEnquirer = await inquirer_1.default.prompt([
141
- {
142
- type: "confirm",
143
- name: "confirm",
144
- message: "Prisma is already initialized. Do you want to override it?",
145
- default: true,
146
- },
147
- ]);
148
- if (prismaEnquirer?.confirm === false) {
149
- console.log(chalk_1.default.red("Prisma init aborted!"));
150
- return;
151
- }
152
- node_fs_1.default.rmSync(prismaFolder.path, {
153
- recursive: true,
154
- force: true,
155
- });
156
- }
157
- await execProcess({
158
- commandArg: "npx",
159
- args: [
160
- "prisma",
161
- "init",
162
- "--datasource-provider",
163
- answer.databaseName,
164
- ],
165
- directory: process.cwd(),
166
- });
167
- const oldFileName = node_path_1.default.join(process.cwd(), "/prisma/schema.prisma");
168
- const newFileName = node_path_1.default.join(process.cwd(), `/prisma/${answer.schemaName}.prisma`);
169
- node_fs_1.default.renameSync(oldFileName, newFileName);
170
- // Move the folder to the destination
171
- const schemaPath = node_path_1.default.join(process.cwd(), `${answer.schemaPath}/prisma/${answer.schemaName}.prisma`);
172
- if (!node_fs_1.default.existsSync(schemaPath)) {
173
- node_fs_1.default.mkdirSync(node_path_1.default.join(process.cwd(), `${answer.schemaPath}/prisma`), { recursive: true });
174
- }
175
- node_fs_1.default.renameSync(newFileName, schemaPath);
176
- // Remove the source folder
177
- if (newFileName !== schemaPath) {
178
- node_fs_1.default.rmSync(node_path_1.default.join(process.cwd(), "/prisma"), { recursive: true });
179
- }
180
- // Add prisma to package.json
181
- prismaPackage(answer);
182
- if (answer.baseRepository) {
183
- const { opinionated, sourceRoot } = await compiler_1.default.loadConfig();
184
- let folderMatch = "";
185
- if (opinionated) {
186
- folderMatch = "repositories";
187
- }
188
- else {
189
- folderMatch = "";
190
- }
191
- const repositoryDir = `${sourceRoot}/${folderMatch}`;
192
- console.log(`Generating BaseRepository Pattern...`);
193
- const baseRepositoryInterfaceTplPath = node_path_1.default.join(__dirname, "./templates/base-repository.interface.tpl");
194
- const baseRepositoryTplPath = node_path_1.default.join(__dirname, "./templates/base-repository.tpl");
195
- const baseRepositoryInterfaceTemplate = node_fs_1.default.readFileSync(baseRepositoryInterfaceTplPath, "utf8");
196
- const baseRepositoryTemplate = node_fs_1.default.readFileSync(baseRepositoryTplPath, "utf8");
197
- node_fs_1.default.writeFileSync(node_path_1.default.join(repositoryDir, "base-repository.interface.ts"), baseRepositoryInterfaceTemplate);
198
- node_fs_1.default.writeFileSync(node_path_1.default.join(repositoryDir, "base-repository.ts"), baseRepositoryTemplate);
199
- }
200
- // Install @expressots/prisma in the project
201
- console.log(`Mapping configurations to expressots.config...`);
202
- await addProviderConfigInExpressotsConfig(answer.schemaName, `${answer.schemaPath}/prisma`);
203
- console.log("Now configure your database connection in the project.");
204
- console.log(chalk_1.default.green("\n👍 Prisma provider added successfully!"));
205
- }
206
- else {
207
- console.log(chalk_1.default.red("Prisma provider not added!"));
208
- }
209
- };
210
- exports.prismaProvider = prismaProvider;
211
- async function execProcess({ commandArg, args, directory, }) {
212
- return new Promise((resolve, reject) => {
213
- const isWindows = process.platform === "win32";
214
- const command = isWindows ? `${commandArg}.cmd` : commandArg;
215
- const installProcess = (0, node_child_process_1.spawn)(command, args, {
216
- cwd: directory,
217
- });
218
- console.log(chalk_1.default.bold.blue(`Executing: ${command} ${args.join(" ")}`));
219
- console.log(chalk_1.default.yellow("---------------------------------------"));
220
- installProcess.stdout.on("data", (data) => {
221
- console.log(chalk_1.default.green(data.toString().trim())); // Display regular messages in green
222
- });
223
- installProcess.stderr.on("data", (data) => {
224
- console.error(chalk_1.default.red(data.toString().trim())); // Display error messages in red
225
- });
226
- installProcess.on("close", (code) => {
227
- if (code === 0) {
228
- console.log(chalk_1.default.bold.green("---------------------------------------"));
229
- console.log(chalk_1.default.bold.green("Installation Done!"));
230
- resolve("Installation Done!");
231
- }
232
- else {
233
- console.error(chalk_1.default.bold.red("---------------------------------------"));
234
- console.error(chalk_1.default.bold.red(`Command ${command} ${args.join(" ")} exited with code ${code}`));
235
- reject(new Error(`Command ${command} ${args.join(" ")} exited with code ${code}`));
236
- (0, node_process_1.exit)(1);
237
- }
238
- });
239
- });
240
- }
241
- function prismaPackage(answer) {
242
- // Get the absolute path of the input directory parameter
243
- const absDirPath = node_path_1.default.resolve(process.cwd());
244
- // Load the package.json file
245
- const packageJsonPath = node_path_1.default.join(absDirPath, "package.json");
246
- const fileContents = node_fs_1.default.readFileSync(packageJsonPath, "utf-8");
247
- const packageJson = JSON.parse(fileContents);
248
- // Add the Prisma configuration to the package.json
249
- packageJson.prisma = {
250
- schema: `${answer.schemaPath}/prisma/${answer.schemaName}.prisma`,
251
- };
252
- // Add the Prisma script to the package.json
253
- packageJson.scripts = {
254
- ...packageJson.scripts,
255
- prisma: "npx @expressots/prisma codegen",
256
- };
257
- // Save the package.json file
258
- node_fs_1.default.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
259
- }
260
- async function addProviderConfigInExpressotsConfig(schemaName, schemaPath) {
261
- const absDirPath = node_path_1.default.resolve(process.cwd());
262
- const expressotsConfigPath = node_path_1.default.join(absDirPath, "expressots.config.ts");
263
- let fileContents = node_fs_1.default.readFileSync(expressotsConfigPath, "utf-8");
264
- const config = await compiler_1.default.loadConfig();
265
- const providersObject = `opinionated: ${config.opinionated},\n\tproviders: {
266
- prisma: {
267
- schemaName: "${schemaName}",
268
- schemaPath: "${schemaPath}",
269
- entitiesPath: "entities",
270
- entityNamePattern: "entity",
271
- },
272
- },`;
273
- if (config.providers) {
274
- // delete the providers object until the last closing curly brace
275
- fileContents = fileContents.replace(/\n([\s]*?)providers: {([\s\S]*?)};/, "\n};");
276
- }
277
- const newFileContents = fileContents.replace(/opinionated: (.*)/, providersObject);
278
- node_fs_1.default.writeFileSync(expressotsConfigPath, newFileContents);
279
- }
@@ -1,57 +0,0 @@
1
- import { Prisma, PrismaClient } from "@prisma/client";
2
- import {
3
- CreateInput,
4
- ModelsOf,
5
- DeleteWhere,
6
- Select,
7
- PrismaAction,
8
- } from "@expressots/prisma";
9
-
10
- interface IBaseRepository<ModelName extends ModelsOf<PrismaClient>> {
11
- aggregate: (args: PrismaAction<ModelName, "aggregate">) => Promise<any>;
12
- count: (args: PrismaAction<ModelName, "count">) => Promise<number>;
13
- create: (
14
- data:
15
- | CreateInput<ModelName>["data"]
16
- | {
17
- data: CreateInput<ModelName>["data"];
18
- select?: Select<ModelName, "create">["select"];
19
- },
20
- ) => Promise<ModelName | never>;
21
- delete: (
22
- where: DeleteWhere<ModelName>["where"],
23
- response?: Select<ModelName, "delete">["select"],
24
- ) => Promise<ModelName | never>;
25
- deleteMany: (
26
- args?: PrismaAction<ModelName, "deleteMany">,
27
- ) => Promise<Prisma.BatchPayload>;
28
- findFirst: (
29
- args: PrismaAction<ModelName, "findFirst">,
30
- ) => Promise<ModelName | null>;
31
- findFirstOrThrow: (
32
- args?: PrismaAction<ModelName, "findFirstOrThrow">,
33
- ) => Promise<ModelName | never>;
34
- findMany: (
35
- args: PrismaAction<ModelName, "findMany">,
36
- ) => Promise<ModelName[]>;
37
- findUnique: (
38
- args: PrismaAction<ModelName, "findUnique">,
39
- ) => Promise<ModelName | null>;
40
- findUniqueOrThrow: (
41
- args?: PrismaAction<ModelName, "findFirstOrThrow">,
42
- ) => Promise<ModelName | never>;
43
- groupBy: (
44
- args: PrismaAction<ModelName, "groupBy">,
45
- ) => Promise<ModelName | never>;
46
- update: (
47
- args: PrismaAction<ModelName, "update">,
48
- ) => Promise<ModelName | never>;
49
- updateMany: (
50
- args: PrismaAction<ModelName, "updateMany">,
51
- ) => Promise<Prisma.BatchPayload>;
52
- upsert: (
53
- args: PrismaAction<ModelName, "upsert">,
54
- ) => Promise<ModelName | never>;
55
- }
56
-
57
- export { IBaseRepository };
@@ -1,146 +0,0 @@
1
- import { PrismaClient, Prisma } from "@prisma/client";
2
- import {
3
- CreateInput,
4
- ModelsOf,
5
- DeleteWhere,
6
- Select,
7
- PrismaAction,
8
- } from "@expressots/prisma";
9
- import { provide } from "inversify-binding-decorators";
10
- import { IBaseRepository } from "./base-repository.interface";
11
-
12
- @provide(BaseRepository)
13
- class BaseRepository<ModelName extends ModelsOf<PrismaClient>>
14
- implements IBaseRepository<ModelName>
15
- {
16
- protected prismaModel: any;
17
- protected prismaClient: PrismaClient;
18
- constructor(modelName: keyof PrismaClient) {
19
- this.prismaClient = new PrismaClient();
20
- this.prismaModel = this.prismaClient[modelName];
21
- }
22
-
23
- async aggregate(args: PrismaAction<ModelName, "aggregate">): Promise<any> {
24
- return await this.prismaModel.aggregate(args);
25
- }
26
-
27
- async count(args: PrismaAction<ModelName, "count">): Promise<number> {
28
- return await this.prismaModel.count(args);
29
- }
30
-
31
- async create(
32
- data:
33
- | CreateInput<ModelName>["data"]
34
- | {
35
- data: CreateInput<ModelName>["data"];
36
- select?: Select<ModelName, "create">["select"];
37
- },
38
- ): Promise<ModelName | never> {
39
- if (!data) {
40
- throw new Error("Data cannot be null or undefined");
41
- }
42
-
43
- if (typeof data === "object" && "data" in data) {
44
- return await this.prismaModel.create(data);
45
- }
46
-
47
- return await this.prismaModel.create({ data });
48
- }
49
-
50
- async delete(
51
- where: DeleteWhere<ModelName>["where"],
52
- select?: Select<ModelName, "delete">["select"],
53
- ): Promise<ModelName | never> {
54
- if (!where) {
55
- throw new Error("Data cannot be null or undefined");
56
- }
57
-
58
- const obj = await this.prismaModel.delete({ where });
59
-
60
- if (select) {
61
- const entries = Object.entries(select);
62
-
63
- const hasTrueField = entries.some(([, value]) => value);
64
-
65
- if (hasTrueField) {
66
- const result: any = {};
67
- for (const [key, value] of entries) {
68
- if (value) {
69
- result[key] = obj[key as keyof typeof obj];
70
- }
71
- }
72
- return result as ModelName;
73
- } else {
74
- for (const [key, value] of entries) {
75
- if (!value) {
76
- delete obj[key as keyof typeof obj];
77
- }
78
- }
79
- }
80
- }
81
-
82
- return obj;
83
- }
84
-
85
- async deleteMany(
86
- args?: PrismaAction<ModelName, "deleteMany">,
87
- ): Promise<Prisma.BatchPayload> {
88
- return await this.prismaModel.deleteMany(args);
89
- }
90
-
91
- async findFirst(
92
- args?: PrismaAction<ModelName, "findFirst">,
93
- ): Promise<ModelName | null> {
94
- return await this.prismaModel.findFirst(args);
95
- }
96
-
97
- async findFirstOrThrow(
98
- args?: PrismaAction<ModelName, "findFirstOrThrow">,
99
- ): Promise<ModelName | never> {
100
- return await this.prismaModel.findFirstOrThrow(args);
101
- }
102
-
103
- async findMany(
104
- args: PrismaAction<ModelName, "findMany">,
105
- ): Promise<ModelName[]> {
106
- return await this.prismaModel.findMany(args);
107
- }
108
-
109
- async findUnique(
110
- args: PrismaAction<ModelName, "findUnique">,
111
- ): Promise<ModelName | null> {
112
- return this.prismaModel.findUnique(args);
113
- }
114
-
115
- async findUniqueOrThrow(
116
- args?: PrismaAction<ModelName, "findUniqueOrThrow">,
117
- ): Promise<ModelName | never> {
118
- return await this.prismaModel.findUniqueOrThrow(args);
119
- }
120
-
121
- async groupBy(
122
- args: PrismaAction<ModelName, "groupBy">,
123
- ): Promise<ModelName | never> {
124
- return await this.prismaModel.groupBy(args);
125
- }
126
-
127
- async update(
128
- args: PrismaAction<ModelName, "update">,
129
- ): Promise<ModelName | never> {
130
- return await this.prismaModel.update(args);
131
- }
132
-
133
- async updateMany(
134
- args: PrismaAction<ModelName, "updateMany">,
135
- ): Promise<Prisma.BatchPayload> {
136
- return await this.prismaModel.updateMany(args);
137
- }
138
-
139
- async upsert(
140
- args: PrismaAction<ModelName, "upsert">,
141
- ): Promise<ModelName | never> {
142
- return await this.prismaModel.upsert(args);
143
- }
144
- }
145
-
146
- export { BaseRepository };