Skip to content

Commit

Permalink
Merge pull request #10 from adripo/patch-1
Browse files Browse the repository at this point in the history
Add a Postgres template
  • Loading branch information
Abhinav-ark authored Oct 20, 2024
2 parents 5d12814 + 6432229 commit 07e912a
Show file tree
Hide file tree
Showing 7 changed files with 222 additions and 74 deletions.
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,17 @@ qse -v
qse --version
```

## List

List all available commands and options.

```bash
qse list
```

## Init

Initialize a basic Express.js server.
Initialize a new Express.js server.

```bash
qse init
Expand Down
38 changes: 37 additions & 1 deletion bin/configs.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,22 @@ export const metadata = {

export const commands = {
version: {
versionFlags: "-v, --version",
command: "-v, --version",
description: "Prints current qse version",
},
init: {
command: "init",
description: "Initialize a new Express server.",
options: [
{
flags: "-t, --template <template>",
description: "Specify template to use",
},
],
},
list: {
command: "list",
description: "List all available commands and options.",
},
clear: {
command: "clear",
Expand All @@ -30,4 +41,29 @@ export const templates = {
},
],
},
express_pg_sequelize: {
name: "express_pg_sequelize",
dependencies: [
{
name: "express",
version: "^4.17.1",
},
{
name: "pg",
version: "^8.6.0",
},
{
name: "pg-hstore",
version: "^2.3.4",
},
{
name: "sequelize",
version: "^6.6.5",
},
{
name: "dotenv",
version: "^16.4.1",
},
],
},
};
181 changes: 109 additions & 72 deletions bin/index.js
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -13,88 +13,41 @@ import { metadata, commands, templates } from "./configs.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const template = templates.basic;

program
.version(metadata.version, commands.version.versionFlags)
.version(metadata.version, commands.version.command)
.description(metadata.description);

program
.command(commands.init.command)
.description(commands.init.description)
.action(() => {
.option(commands.init.options[0].flags, commands.init.options[0].description)
.action((options) => {
toolIntro();
initCommand(options);
});

console.log("Starting server initialization...");

const targetDir = process.cwd();
const parentDir = path.dirname(__dirname);
const templatePath = path.join(parentDir, "templates", template.name);
const destinationPath = path.join(targetDir);
const npmInit = chalk.yellow.bold("npm init");

const initSpinner = createSpinner(`Running ${npmInit}...`).start();
try {
// execSync('npm init -y', { stdio: 'inherit', cwd: targetDir });
execSync("npm init -y", { stdio: "ignore", cwd: targetDir });
initSpinner.success({ text: `${npmInit} completed successfully.` });
} catch (err) {
initSpinner.error({ text: `Error running ${npmInit}:\n` });
console.error(err.message);
return;
}

//console.log(`Copying server template from ${templatePath} to ${destinationPath}`);

const copySpinner = createSpinner("Creating server files...").start();
try {
fs.copySync(templatePath, destinationPath);
copySpinner.success({ text: "Created server files successfully." });
} catch (err) {
copySpinner.error({ text: "Error creating server files.\n" });
console.error(err.message);
}

const addDependencies = createSpinner(
"Adding dependency packages..."
).start();
try {
// Update package.json to add express as a dependency.
const packageJsonPath = path.join(targetDir, "package.json");
const packageJsonContent = fs.readFileSync(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonContent);
packageJson.dependencies = packageJson.dependencies || {};
// packageJson.dependencies.express = "^4.17.1";
template.dependencies.forEach((dependency) => {
packageJson.dependencies[`${dependency.name}`] = dependency.version;
});
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));

addDependencies.success({
text: "Added dependency packages successfully.",
});
} catch (err) {
addDependencies.error("Error adding dependency packages.\n");
console.error(err.message);
}

const installDependencies = createSpinner(
"Installing dependency packages..."
).start();
try {
//execSync('npm i', { stdio: 'inherit', cwd: targetDir });
execSync("npm i", { stdio: "ignore", cwd: targetDir });
program
.command(commands.list.command)
.description(commands.list.description)
.action(() => {
console.log("Available Commands:");
Object.keys(commands).forEach((cmd) => {
const commandInfo = commands[cmd];
if (commandInfo.command) {
console.log(`- ${commandInfo.command}${commandInfo.description ? ": " + commandInfo.description : ""}`);
}

installDependencies.success({
text: "Installed dependencies successfully.",
});
if (commandInfo.options) {
commandInfo.options.forEach((option) => {
console.log(` (Options: ${option.flags}${option.description ? " - " + option.description : ""})`);
});
}
});

console.log(chalk.green.bold("\nSetup complete! To run your server:"));
console.log(chalk.yellow("Run:"), chalk.white.bold("npm start"));
} catch (err) {
installDependencies.error({ text: "Error installing dependencies.\n" });
console.error(err);
}
console.log("\nAvailable Templates:");
Object.keys(templates).forEach((template) => {
console.log(`- ${templates[template].name}`);
});
});

program
Expand Down Expand Up @@ -124,6 +77,90 @@ program
}
});

function initCommand(options) {
const selectedTemplate = options.template || "basic"; // Default to 'basic' if no template is specified

if (!templates[selectedTemplate]) {
console.error(chalk.bgRed.white(`Template ${selectedTemplate} does not exist. To see available templates use "qse list".`));
return;
}

console.log("Starting server initialization...");

const targetDir = process.cwd();
const parentDir = path.dirname(__dirname);
const templatePath = path.join(parentDir, "templates", templates[selectedTemplate].name);
const destinationPath = path.join(targetDir);
const npmInit = chalk.yellow.bold("npm init");

// Initialize package.json
const initSpinner = createSpinner(`Running ${npmInit}...`).start();
try {
execSync("npm init -y", { stdio: "ignore", cwd: targetDir });

initSpinner.success({ text: `${npmInit} completed successfully.` });
} catch (err) {
initSpinner.error({ text: `Error running ${npmInit}:\n` });
console.error(err.message);
return;
}

const copySpinner = createSpinner("Creating server files...").start();
try {
fs.copySync(templatePath, destinationPath);

copySpinner.success({ text: "Created server files successfully." });
} catch (err) {
copySpinner.error({ text: "Error creating server files.\n" });
console.error(err.message);
}

const addTypeDeclaration = createSpinner("Adding type declaration...").start();
try {
const packageJsonPath = path.join(targetDir, "package.json");
const packageJsonContent = fs.readFileSync(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonContent);
packageJson.type = "module";
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));

addTypeDeclaration.success({ text: "Added type declaration successfully." });
} catch (err) {
addTypeDeclaration.error({ text: "Error adding type declaration.\n" });
console.error(err.message);
}

const addDependencies = createSpinner("Adding dependency packages...").start();
try {
const packageJsonPath = path.join(targetDir, "package.json");
const packageJsonContent = fs.readFileSync(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonContent);
packageJson.dependencies = packageJson.dependencies || {};

templates[selectedTemplate].dependencies.forEach((dependency) => {
packageJson.dependencies[`${dependency.name}`] = dependency.version;
});
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));

addDependencies.success({ text: "Added dependency packages successfully." });
} catch (err) {
addDependencies.error("Error adding dependency packages.\n");
console.error(err.message);
}

const installDependencies = createSpinner("Installing dependency packages...").start();
try {
execSync("npm i", { stdio: "ignore", cwd: targetDir });

installDependencies.success({ text: "Installed dependencies successfully." });
} catch (err) {
installDependencies.error({ text: "Error installing dependencies.\n" });
console.error(err);
}

console.log(chalk.green.bold("\nSetup complete! To run your server:"));
console.log(chalk.yellow("Run:"), chalk.white.bold("npm start"));
};

const toolIntro = () => {
console.log(
figlet.textSync(metadata.name, {
Expand Down
3 changes: 3 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions templates/express_pg_sequelize/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Sequelize } from 'sequelize';

// Initialize Sequelize
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'localhost',
dialect: 'postgres',
});

// Export the Sequelize instance
export default sequelize;
38 changes: 38 additions & 0 deletions templates/express_pg_sequelize/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import express from 'express';
import db from './db.js';
import dotenv from 'dotenv'

dotenv.config()

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

// Test PostgreSQL connection
db.authenticate()
.then(() => {
console.log('Database connection established successfully.');
})
.catch((err) => {
console.error('Unable to connect to the database:', err);
});

app.get('/', (req, res) => {
return res.send('Hello, Express with PostgreSQL!');
});

// Dummy route to test DB query
app.get('/db-test', async (req, res) => {
try {
const [results, metadata] = await db.query('SELECT NOW()');
return res.status(200).json({ message: 'DB query successful!', data: results });
} catch (error) {
return res.status(500).json({ message: 'Error querying the database', error });
}
});

// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
16 changes: 16 additions & 0 deletions templates/express_pg_sequelize/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "express_pg",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.17.1",
"pg": "^8.6.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.6.5",
"dotenv": "^16.4.1"
}
}

0 comments on commit 07e912a

Please sign in to comment.