Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"snyk.advanced.autoSelectOrganization": true
}
127 changes: 127 additions & 0 deletions src/templates/js/postgresql/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache


# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*


## OS X
.DS_Store
Empty file.
10 changes: 10 additions & 0 deletions src/templates/js/postgresql/default.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
PORT=8000
JWT_SECRET=your_jwt_secret_here
JWT_EXPIRES_IN=1d


DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD= 12345
DB_NAME=
29 changes: 29 additions & 0 deletions src/templates/js/postgresql/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "js-postgresql-api",
"version": "1.0.0",
"description": "Modern Express API with PostgreSQL, ES Modules, and async CRUD",
"type": "module",
"main": "./src/app.js",
"scripts": {
"dev": "nodemon app.js",
"start": "node app.js",
"lint": "eslint .",
"format": "prettier --write ."
},
"dependencies": {
"bcryptjs": "^3.0.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"http-errors": "^2.0.0",
"jsonwebtoken": "^9.0.3",
"pg": "^8.20.0",
"morgan": "^1.10.0"
},
"devDependencies": {
"eslint": "^9.0.0",
"eslint-plugin-import": "^2.29.1",
"nodemon": "^3.1.14",
"prettier": "^3.2.5"
}
}
42 changes: 42 additions & 0 deletions src/templates/js/postgresql/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import express from "express";
import morgan from "morgan";
import createError from "http-errors";
import cors from "cors";
import dotenv from "dotenv";
import apiRoutes from "./routes/user.route.js";
import authRoutes from "./routes/auth.route.js";
import { connectDB } from "./configs/db.js";

dotenv.config();
connectDB();

const app = express();

// Middlewares
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan("dev"));

// Routes
app.get("/", (req, res) => res.json({ message: "API is running 🚀" }));
app.use("/api", apiRoutes); // user routes
app.use("/api/auth", authRoutes); // login route

// 404 handler
app.use((req, res, next) => {
next(createError.NotFound());
});

// Global error handler
app.use((err, req, res) => {
res.status(err.status || 500).json({
success: false,
message: err.message || "Internal Server Error",
});
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>
console.log(`🚀 Server running @ http://localhost:${PORT}`)
);
30 changes: 30 additions & 0 deletions src/templates/js/postgresql/src/configs/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// src/config/db.js
import pkg from "pg";
import 'dotenv/config';


const { Pool } = pkg;

const pool = new Pool({
user: String(process.env.DB_USER),
host: String(process.env.DB_HOST),
database: String(process.env.DB_NAME),
password: String(process.env.DB_PASSWORD),
port: Number(process.env.DB_PORT),
});

export const connectDB = async () => {
try {
const client = await pool.connect();
//remove this in production
console.log("🚀 Connected to PostgreSQL database");

client.release();
} catch (err) {
//remove this in production
console.error("DB connection error:", err);
process.exit(1);
}
};

export default pool;
72 changes: 72 additions & 0 deletions src/templates/js/postgresql/src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import asyncHandler from "../utils/asyncHandler.js";
import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs";
import { successResponse, errorResponse } from "../utils/response.js";
import{ findByEmail } from "../repositories/user.repository.js";

// Login endpoint
export const login = asyncHandler(async (req, res) => {
try {
const { email, password } = req.body;

// Find user
// const user = await User.findOne({ email });
const user = await findByEmail(email);
if (!user) {
return res.status(401).json(errorResponse(null, "Invalid credentials"));
}

// Check password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json(errorResponse(null, "Invalid credentials"));
}

// Generate token
const token = jwt.sign(
{ id: user._id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRES_IN || "1d" }
);

res.json(successResponse({ token }, "Login successful"));
} catch (error) {
res.status(500).json(errorResponse(error, "Login failed"));
}
});

export const signup = asyncHandler(async (req, res) => {
try {
const { name, email, password, age } = req.body;

// Check if user already exists
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json(errorResponse(null, "User already exists"));
}

// Hash password
const hashedPassword = await bcrypt.hash(password, 10);

// Create user
const newUser = await User.create({
name,
email,
password: hashedPassword,
age: age || 0,
});

// Generate token
const token = jwt.sign(
{ id: newUser._id, email: newUser.email },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRES_IN || "1d" }
);

res
.status(201)
.json(successResponse({ token, user: newUser }, "Signup successful"));
} catch (error) {
res.status(500).json(errorResponse(error, "Login failed"));
}
});
27 changes: 27 additions & 0 deletions src/templates/js/postgresql/src/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as userService from "../services/user.service.js";
import asyncHandler from "../utils/asyncHandler.js";

export const getUsers = asyncHandler(async (req, res) => {
const result = await userService.getUsers();
res.status(result.status).json(result);
});

export const getUser = asyncHandler(async (req, res) => {
const result = await userService.getUser(req.params.id);
res.status(result.status).json(result);
});

export const createUser = asyncHandler(async (req, res) => {
const result = await userService.createNewUser(req.body);
res.status(result.status).json(result);
});

export const updateUser = asyncHandler(async (req, res) => {
const result = await userService.updateExistingUser(req.params.id, req.body);
res.status(result.status).json(result);
});

export const deleteUser = asyncHandler(async (req, res) => {
const result = await userService.deleteExistingUser(req.params.id);
res.status(result.status).json(result);
});
Loading