@expressots/cli 1.9.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");
@@ -12,23 +14,48 @@ const cli_1 = require("./help/cli");
12
14
  const info_1 = require("./info");
13
15
  const new_1 = require("./new");
14
16
  const providers_1 = require("./providers");
15
- console.log(`\n[🐎 Expressots]\n`);
17
+ const cli_2 = require("./providers/create/cli");
18
+ const cli_ui_1 = require("./utils/cli-ui");
19
+ process_1.stdout.write(`\n${[chalk_1.default.bold.green("🐎 Expressots")]}\n\n`);
16
20
  (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
17
21
  .scriptName("expressots")
18
- .command(project_commands_1.runCommandModule)
19
22
  .command((0, new_1.createProject)())
20
- .command((0, providers_1.generateProviders)())
23
+ .command(project_commands_1.devCommand)
24
+ .command(project_commands_1.buildCommand)
25
+ .command(project_commands_1.prodCommand)
26
+ .command((0, cli_2.createExternalProviderCMD)())
27
+ .command((0, providers_1.addProviderCMD)())
21
28
  .command((0, generate_1.generateProject)())
22
29
  .command((0, info_1.infoProject)())
23
30
  .command((0, cli_1.helpCommand)())
24
- .example("$0 new expressots-demo", "Create interactively")
25
- .example("$0 new expressots-demo -d ./", "Create interactively with path")
26
- .example("$0 new expressots-demo -p yarn -t opinionated", "Create silently")
27
- .example("$0 new expressots-demo -p yarn -t opinionated -d ./", "Create silently with path")
28
- .example("$0 generate service user-create", "Scaffold a service")
29
- .example("$0 info", "Show CLI details")
30
31
  .demandCommand(1, "You need at least one command before moving on")
31
- .epilog("For more information: \n" +
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
+ })
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")
34
61
  .help("help", "Show command help")
@@ -1,8 +1,26 @@
1
1
  import { CommandModule } from "yargs";
2
- export declare const runCommandModule: CommandModule<{}, {
3
- command: string;
4
- }>;
5
- declare const runCommand: ({ command }: {
2
+ /**
3
+ * Dev command module
4
+ * @type {CommandModule<object, object>}
5
+ * @returns The command module
6
+ */
7
+ export declare const devCommand: CommandModule<object, object>;
8
+ /**
9
+ * Build command module
10
+ * @type {CommandModule<object, object>}
11
+ * @returns The command module
12
+ */
13
+ export declare const buildCommand: CommandModule<object, object>;
14
+ /**
15
+ * Prod command module
16
+ * @type {CommandModule<object, object>}
17
+ * @returns The command module
18
+ */
19
+ export declare const prodCommand: CommandModule<object, object>;
20
+ /**
21
+ * Helper function to run a command
22
+ * @param command The command to run
23
+ */
24
+ export declare const runCommand: ({ command, }: {
6
25
  command: string;
7
26
  }) => Promise<void>;
8
- export { runCommand };
@@ -1,13 +1,44 @@
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
  };
5
28
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.runCommand = exports.runCommandModule = void 0;
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"));
34
+ const cli_ui_1 = require("../utils/cli-ui");
10
35
  const compiler_1 = __importDefault(require("../utils/compiler"));
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;
11
42
  /**
12
43
  * Load the configuration from the compiler
13
44
  * @param compiler The compiler to load the configuration from
@@ -15,6 +46,7 @@ const compiler_1 = __importDefault(require("../utils/compiler"));
15
46
  */
16
47
  const opinionatedConfig = [
17
48
  "--transpile-only",
49
+ "--clear",
18
50
  "-r",
19
51
  "dotenv/config",
20
52
  "-r",
@@ -23,10 +55,47 @@ const opinionatedConfig = [
23
55
  ];
24
56
  const nonOpinionatedConfig = [
25
57
  "--transpile-only",
58
+ "--clear",
26
59
  "-r",
27
60
  "dotenv/config",
28
61
  "./src/main.ts",
29
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
+ };
30
99
  /**
31
100
  * Helper function to execute a command
32
101
  * @param command The command to execute
@@ -51,15 +120,23 @@ function execCmd(command, args, cwd = process.cwd()) {
51
120
  });
52
121
  });
53
122
  }
54
- // Helper to delete the dist directory
123
+ /**
124
+ * Helper function to clean the dist directory
125
+ */
55
126
  const cleanDist = async () => {
56
- await fs_1.promises.rm("./dist", { recursive: true, force: true });
127
+ await fs_1.promises.rm(outDir, { recursive: true, force: true });
128
+ (0, cli_ui_1.printSuccess)(`Clean ${outDir} directory`, "clean-dist");
57
129
  };
58
- // Helper to compile TypeScript
130
+ /**
131
+ * Helper function to compile TypeScript
132
+ */
59
133
  const compileTypescript = async () => {
60
134
  await execCmd("npx", ["tsc", "-p", "tsconfig.build.json"]);
135
+ (0, cli_ui_1.printSuccess)("Built successfully", "compile-typescript");
61
136
  };
62
- // Helper to copy files
137
+ /**
138
+ * Helper function to copy files to the dist directory
139
+ */
63
140
  const copyFiles = async () => {
64
141
  const { opinionated } = await compiler_1.default.loadConfig();
65
142
  let filesToCopy = [];
@@ -74,64 +151,66 @@ const copyFiles = async () => {
74
151
  filesToCopy = ["tsconfig.json", "package.json"];
75
152
  }
76
153
  filesToCopy.forEach((file) => {
77
- 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)));
78
155
  });
79
156
  };
80
- // eslint-disable-next-line @typescript-eslint/ban-types
81
- exports.runCommandModule = {
82
- command: "run <command>",
83
- describe: "Runs a specified command (dev, build, prod)",
84
- builder: (yargs) => {
85
- return yargs.positional("command", {
86
- describe: "The command to run",
87
- type: "string",
88
- choices: ["dev", "build", "prod"],
89
- });
90
- },
91
- handler: async (argv) => {
92
- const { command } = argv;
93
- // Now call your original runCommand function with the command
94
- // Ensure runCommand is properly defined to handle these commands
95
- await runCommand({ command });
96
- },
157
+ /**
158
+ * Helper function to clear the screen
159
+ */
160
+ const clearScreen = () => {
161
+ const platform = os_1.default.platform();
162
+ const command = platform === "win32" ? "cls" : "clear";
163
+ (0, child_process_1.spawn)(command, { stdio: "inherit", shell: true });
97
164
  };
98
- const runCommand = async ({ command }) => {
165
+ /**
166
+ * Helper function to run a command
167
+ * @param command The command to run
168
+ */
169
+ const runCommand = async ({ command, }) => {
99
170
  const { opinionated } = await compiler_1.default.loadConfig();
100
171
  try {
101
172
  switch (command) {
102
173
  case "dev":
103
- // Use execSync or spawn to run ts-node-dev programmatically
104
174
  execCmd("tsnd", opinionated ? opinionatedConfig : nonOpinionatedConfig);
105
175
  break;
106
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
+ }
107
181
  await cleanDist();
108
182
  await compileTypescript();
109
183
  await copyFiles();
110
184
  break;
111
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
+ }
112
190
  let config = [];
113
191
  if (opinionated) {
114
192
  config = [
115
193
  "-r",
116
194
  "dotenv/config",
117
195
  "-r",
118
- "./dist/register-path.js",
119
- "./dist/src/main.js",
196
+ `./${outDir}/register-path.js`,
197
+ `./${outDir}/src/main.js`,
120
198
  ];
121
199
  }
122
200
  else {
123
- config = ["-r", "dotenv/config", "./dist/main.js"];
201
+ config = ["-r", "dotenv/config", `./${outDir}/main.js`];
124
202
  }
125
- // Ensure environment variables are set
203
+ clearScreen();
126
204
  execCmd("node", config);
127
205
  break;
128
206
  }
129
207
  default:
130
- console.log(`Unknown command: ${command}`);
208
+ (0, cli_ui_1.printError)(`Unknown command: `, command);
209
+ break;
131
210
  }
132
211
  }
133
212
  catch (error) {
134
- console.error("Error executing command:", error);
213
+ (0, cli_ui_1.printError)("Error executing command:", error.message);
135
214
  }
136
215
  };
137
216
  exports.runCommand = runCommand;
@@ -27,7 +27,7 @@ const coerceSchematicAliases = (arg) => {
27
27
  const generateProject = () => {
28
28
  return {
29
29
  command: "generate [schematic] [path] [method]",
30
- describe: "Scaffold a new resource",
30
+ describe: "Generate ExpressoTS resource.",
31
31
  aliases: ["g"],
32
32
  builder: (yargs) => {
33
33
  yargs.positional("schematic", {
package/bin/help/cli.js CHANGED
@@ -5,7 +5,7 @@ const form_1 = require("./form");
5
5
  const helpCommand = () => {
6
6
  return {
7
7
  command: "resources",
8
- describe: "Resource list",
8
+ describe: "Resource list.",
9
9
  aliases: ["r"],
10
10
  handler: async () => {
11
11
  await (0, form_1.helpForm)();
package/bin/help/form.js CHANGED
@@ -19,7 +19,7 @@ const helpForm = async () => {
19
19
  "service",
20
20
  "g s",
21
21
  "Generate a service [controller, usecase, dto, module]",
22
- ], ["controller", "g c", "Generate a controller"], ["usecase", "g u", "Generate a usecase"], ["dto", "g d", "Generate a dto"], ["entity", "g e", "Generate an entity"], ["provider", "g p", "Generate a provider"], ["provider external", "a provider", "Generate an external provider"], ["module", "g mo", "Generate a module"], ["middleware", "g mi", "Generate a middleware"]);
22
+ ], ["controller", "g c", "Generate a controller"], ["usecase", "g u", "Generate a usecase"], ["dto", "g d", "Generate a dto"], ["entity", "g e", "Generate an entity"], ["provider", "add", "Add provider to the project"], ["provider", "create", "Create a provider"], ["module", "g mo", "Generate a module"], ["middleware", "g mi", "Generate a middleware"]);
23
23
  console.log(chalk_1.default.bold.white("ExpressoTS:", `${chalk_1.default.green("Resources List")}`));
24
24
  console.log(chalk_1.default.whiteBright(table.toString()));
25
25
  console.log(chalk_1.default.bold.white(`📝 More info: ${chalk_1.default.green("https://doc.expresso-ts.com/docs/category/cli")}`));
package/bin/info/cli.js CHANGED
@@ -5,7 +5,7 @@ const form_1 = require("./form");
5
5
  const infoProject = () => {
6
6
  return {
7
7
  command: "info",
8
- describe: "Displays project details",
8
+ describe: "Displays project info.",
9
9
  aliases: ["i"],
10
10
  handler: async () => {
11
11
  await (0, form_1.infoForm)();
@@ -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/bin/new/cli.js CHANGED
@@ -52,7 +52,7 @@ const checkNodeVersion = () => {
52
52
  const createProject = () => {
53
53
  return {
54
54
  command: "new <project-name> [package-manager] [template] [directory]",
55
- describe: "Create a new project",
55
+ describe: "Create ExpressoTS application.",
56
56
  builder: commandOptions,
57
57
  handler: async ({ projectName, packageManager, template, directory, }) => {
58
58
  checkNodeVersion();
package/bin/new/form.js CHANGED
@@ -13,6 +13,7 @@ const node_fs_1 = __importDefault(require("node:fs"));
13
13
  const node_path_1 = __importDefault(require("node:path"));
14
14
  const center_text_1 = require("../utils/center-text");
15
15
  const cli_ui_1 = require("../utils/cli-ui");
16
+ const change_package_info_1 = require("../utils/change-package-info");
16
17
  async function packageManagerInstall({ packageManager, directory, progressBar, }) {
17
18
  return new Promise((resolve, reject) => {
18
19
  const isWindows = process.platform === "win32";
@@ -67,14 +68,6 @@ async function checkIfPackageManagerExists(packageManager) {
67
68
  process.exit(1);
68
69
  }
69
70
  }
70
- function changePackageName({ directory, name, }) {
71
- const absDirPath = node_path_1.default.resolve(directory);
72
- const packageJsonPath = node_path_1.default.join(absDirPath, "package.json");
73
- const fileContents = node_fs_1.default.readFileSync(packageJsonPath, "utf-8");
74
- const packageJson = JSON.parse(fileContents);
75
- packageJson.name = name;
76
- node_fs_1.default.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
77
- }
78
71
  function renameEnvFile(directory) {
79
72
  try {
80
73
  const envExamplePath = node_path_1.default.join(directory, ".env.example");
@@ -189,7 +182,7 @@ const projectForm = async (projectName, args) => {
189
182
  progressBar,
190
183
  });
191
184
  progressBar.update(90);
192
- changePackageName({
185
+ (0, change_package_info_1.changePackageName)({
193
186
  directory: answer.name,
194
187
  name: projectName,
195
188
  });
@@ -0,0 +1,4 @@
1
+ import { CommandModule } from "yargs";
2
+ type CommandModuleArgs = {};
3
+ export declare const addProviderCMD: () => CommandModule<CommandModuleArgs, any>;
4
+ export {};
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addProviderCMD = void 0;
4
+ const form_1 = require("./form");
5
+ const addProviderCMD = () => {
6
+ return {
7
+ command: "add <provider> [version]",
8
+ describe: "Add provider to the project.",
9
+ builder: (yargs) => {
10
+ yargs
11
+ .positional("provider", {
12
+ describe: "The provider to be added to the project",
13
+ type: "string",
14
+ })
15
+ .option("version", {
16
+ describe: "The provider version to be installed",
17
+ type: "string",
18
+ default: "latest",
19
+ alias: "v",
20
+ });
21
+ return yargs;
22
+ },
23
+ handler: async ({ provider, version }) => {
24
+ await (0, form_1.addExternalProvider)(provider, version);
25
+ },
26
+ };
27
+ };
28
+ exports.addProviderCMD = addProviderCMD;
@@ -0,0 +1 @@
1
+ export declare const addExternalProvider: (provider: string, version: string) => Promise<void>;
@@ -0,0 +1,68 @@
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.addExternalProvider = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const node_child_process_1 = require("node:child_process");
9
+ const node_fs_1 = __importDefault(require("node:fs"));
10
+ const node_process_1 = require("node:process");
11
+ const cli_ui_1 = require("../../utils/cli-ui");
12
+ const addExternalProvider = async (provider, version) => {
13
+ await installProvider(provider, version);
14
+ };
15
+ exports.addExternalProvider = addExternalProvider;
16
+ async function installProvider(provider, version) {
17
+ const packageManager = node_fs_1.default.existsSync("package-lock.json" || "yarn.lock" || "pnpm-lock.yaml")
18
+ ? "npm"
19
+ : node_fs_1.default.existsSync("yarn.lock")
20
+ ? "yarn"
21
+ : node_fs_1.default.existsSync("pnpm-lock.yaml")
22
+ ? "pnpm"
23
+ : null;
24
+ if (packageManager) {
25
+ console.log(`Installing ${provider} provider ...`);
26
+ const currentVersion = version === "latest" ? "" : `@${version}`;
27
+ await execProcess({
28
+ commandArg: packageManager,
29
+ args: ["add", `${provider}${currentVersion}`, "--prefer-offline"],
30
+ directory: process.cwd(),
31
+ });
32
+ }
33
+ else {
34
+ (0, cli_ui_1.printError)("No package manager found in the project", "install-provider");
35
+ return;
36
+ }
37
+ }
38
+ async function execProcess({ commandArg, args, directory, }) {
39
+ return new Promise((resolve, reject) => {
40
+ const isWindows = process.platform === "win32";
41
+ const command = isWindows ? `${commandArg}.cmd` : commandArg;
42
+ const installProcess = (0, node_child_process_1.spawn)(command, args, {
43
+ cwd: directory,
44
+ shell: true,
45
+ });
46
+ console.log(chalk_1.default.bold.blue(`Executing: ${commandArg} ${args.join(" ")}`));
47
+ console.log(chalk_1.default.yellow("-------------------------------------------------"));
48
+ installProcess.stdout.on("data", (data) => {
49
+ console.log(chalk_1.default.green(data.toString().trim())); // Display regular messages in green
50
+ });
51
+ installProcess.stderr.on("data", (data) => {
52
+ console.error(chalk_1.default.red(data.toString().trim())); // Display error messages in red
53
+ });
54
+ installProcess.on("close", (code) => {
55
+ if (code === 0) {
56
+ console.log(chalk_1.default.bold.green("-------------------------------------------------"));
57
+ console.log(chalk_1.default.bold.green("Installation Done!\n"));
58
+ resolve("Installation Done!");
59
+ }
60
+ else {
61
+ console.error(chalk_1.default.bold.red("---------------------------------------"));
62
+ console.error(chalk_1.default.bold.red(`Command ${command} ${args.join(" ")} exited with code ${code}`));
63
+ reject(new Error(`Command ${command} ${args.join(" ")} exited with code ${code}`));
64
+ (0, node_process_1.exit)(1);
65
+ }
66
+ });
67
+ });
68
+ }
@@ -0,0 +1,4 @@
1
+ import { CommandModule } from "yargs";
2
+ type CommandModuleArgs = {};
3
+ export declare const createExternalProviderCMD: () => CommandModule<CommandModuleArgs, any>;
4
+ export {};
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createExternalProviderCMD = void 0;
4
+ const form_1 = require("./form");
5
+ const createExternalProviderCMD = () => {
6
+ return {
7
+ command: "create [provider]",
8
+ describe: "Create a provider.",
9
+ builder: (yargs) => {
10
+ yargs.option("provider", {
11
+ describe: "Provider name",
12
+ type: "string",
13
+ });
14
+ return yargs;
15
+ },
16
+ handler: async ({ provider }) => {
17
+ await (0, form_1.createExternalProvider)(provider);
18
+ },
19
+ };
20
+ };
21
+ exports.createExternalProviderCMD = createExternalProviderCMD;
@@ -0,0 +1 @@
1
+ export declare const createExternalProvider: (provider: string) => Promise<void>;
@@ -3,11 +3,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.externalProvider = void 0;
6
+ exports.createExternalProvider = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const degit_1 = __importDefault(require("degit"));
9
9
  const inquirer_1 = __importDefault(require("inquirer"));
10
10
  const center_text_1 = require("../../utils/center-text");
11
+ const change_package_info_1 = require("../../utils/change-package-info");
11
12
  const cli_ui_1 = require("../../utils/cli-ui");
12
13
  async function printInfo(providerName) {
13
14
  console.log("\n");
@@ -20,30 +21,38 @@ async function printInfo(providerName) {
20
21
  console.log(chalk_1.default.bold.white((0, center_text_1.centerText)("💖 Sponsor: https://github.com/sponsors/expressots")));
21
22
  console.log("\n");
22
23
  }
23
- const externalProvider = async () => {
24
+ const createExternalProvider = async (provider) => {
24
25
  return new Promise(async (resolve, reject) => {
25
- const providerInfo = await inquirer_1.default.prompt([
26
- {
27
- type: "input",
28
- name: "providerName",
29
- message: "Type the name of your provider:",
30
- default: "expressots-provider",
31
- transformer: (input) => {
32
- return chalk_1.default.yellow(chalk_1.default.bold(input));
26
+ let providerInfo = {};
27
+ providerInfo.providerName = provider;
28
+ if (!provider) {
29
+ providerInfo = await inquirer_1.default.prompt([
30
+ {
31
+ type: "input",
32
+ name: "providerName",
33
+ message: "Provider name",
34
+ default: "expressots-provider",
35
+ transformer: (input) => {
36
+ return chalk_1.default.yellow(chalk_1.default.bold(input));
37
+ },
33
38
  },
34
- },
35
- ]);
39
+ ]);
40
+ }
36
41
  try {
37
42
  const emitter = (0, degit_1.default)(`expressots/expressots-provider-template`);
38
43
  await emitter.clone(providerInfo.providerName);
44
+ (0, change_package_info_1.changePackageName)({
45
+ directory: providerInfo.providerName,
46
+ name: providerInfo.providerName,
47
+ });
39
48
  await printInfo(providerInfo.providerName);
40
49
  resolve();
41
50
  }
42
51
  catch (err) {
43
52
  console.log("\n");
44
- (0, cli_ui_1.printError)("Project already exists or Folder is not empty", "generate-external-provider");
53
+ (0, cli_ui_1.printError)("Project already exists or Folder is not empty", "");
45
54
  reject(err);
46
55
  }
47
56
  });
48
57
  };
49
- exports.externalProvider = externalProvider;
58
+ exports.createExternalProvider = createExternalProvider;
@@ -1 +1,2 @@
1
- export * from "./cli";
1
+ export * from "./add/cli";
2
+ export * from "./create/cli";
@@ -14,4 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./cli"), exports);
17
+ __exportStar(require("./add/cli"), exports);
18
+ __exportStar(require("./create/cli"), exports);
@@ -0,0 +1,4 @@
1
+ export declare function changePackageName({ directory, name, }: {
2
+ directory: string;
3
+ name: string;
4
+ }): void;
@@ -0,0 +1,17 @@
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.changePackageName = void 0;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ function changePackageName({ directory, name, }) {
10
+ const absDirPath = node_path_1.default.resolve(directory);
11
+ const packageJsonPath = node_path_1.default.join(absDirPath, "package.json");
12
+ const fileContents = node_fs_1.default.readFileSync(packageJsonPath, "utf-8");
13
+ const packageJson = JSON.parse(fileContents);
14
+ packageJson.name = name;
15
+ node_fs_1.default.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
16
+ }
17
+ exports.changePackageName = changePackageName;
@@ -1,4 +1,5 @@
1
1
  export declare function printError(message: string, component: string): void;
2
+ export declare function printSuccess(message: string, component: string): void;
2
3
  export declare function printWarning(message: string, component?: string): void;
3
4
  export declare function printGenerateError(schematic: string, file: string): Promise<void>;
4
5
  export declare function printGenerateSuccess(schematic: string, file: string): Promise<void>;
@@ -3,13 +3,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.printGenerateSuccess = exports.printGenerateError = exports.printWarning = exports.printError = void 0;
6
+ exports.printGenerateSuccess = exports.printGenerateError = exports.printWarning = exports.printSuccess = exports.printError = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const process_1 = require("process");
9
9
  function printError(message, component) {
10
10
  console.error(chalk_1.default.red(`${message}:`, chalk_1.default.bold(chalk_1.default.white(`[${component}] ❌`))));
11
11
  }
12
12
  exports.printError = printError;
13
+ function printSuccess(message, component) {
14
+ process_1.stdout.write(chalk_1.default.green(`${message}:`, chalk_1.default.bold(chalk_1.default.white(`[${component}] ✔️\n`))));
15
+ }
16
+ exports.printSuccess = printSuccess;
13
17
  function printWarning(message, component) {
14
18
  if (component === undefined) {
15
19
  process_1.stdout.write(chalk_1.default.yellow(`${message} ⚠️\n`));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressots/cli",
3
- "version": "1.9.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,11 +50,12 @@
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",
56
57
  "degit": "2.8.4",
57
- "glob": "10.4.1",
58
+ "glob": "10.4.5",
58
59
  "inquirer": "8.2.6",
59
60
  "mustache": "4.2.0",
60
61
  "semver": "7.6.2",
@@ -1,4 +0,0 @@
1
- import { CommandModule } from "yargs";
2
- type CommandModuleArgs = {};
3
- declare const generateProviders: () => CommandModule<CommandModuleArgs, any>;
4
- export { generateProviders };
@@ -1,43 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateProviders = void 0;
4
- const external_provider_1 = require("./external/external.provider");
5
- const prisma_provider_1 = require("./prisma/prisma.provider");
6
- const generateProviders = () => {
7
- return {
8
- command: "add <provider> [library-version] [provider-version]",
9
- describe: "Scaffold a new provider",
10
- aliases: ["a"],
11
- builder: (yargs) => {
12
- yargs
13
- .positional("provider", {
14
- choices: ["prisma", "provider"],
15
- describe: "The provider to add to the project",
16
- type: "string",
17
- alias: "p",
18
- })
19
- .option("library-version", {
20
- describe: "The library version to install",
21
- type: "string",
22
- default: "latest",
23
- alias: "v",
24
- })
25
- .option("provider-version", {
26
- describe: "The version of the provider to install",
27
- type: "string",
28
- default: "latest",
29
- alias: "vp",
30
- });
31
- return yargs;
32
- },
33
- handler: async ({ provider, libraryVersion, providerVersion }) => {
34
- if (provider === "prisma") {
35
- await (0, prisma_provider_1.prismaProvider)(libraryVersion, providerVersion);
36
- }
37
- else if (provider === "provider") {
38
- await (0, external_provider_1.externalProvider)();
39
- }
40
- },
41
- };
42
- };
43
- exports.generateProviders = generateProviders;
@@ -1,2 +0,0 @@
1
- declare const externalProvider: () => Promise<void>;
2
- export { externalProvider };
@@ -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 };