README
The Purpose of this Template is to use postgres with express
- init the project
npm init -y
- install typescript
npm i -D typescript
- add tsconfig.json file
tsc --init
"rootDir": "./src",
"outDir": "./dist",
- install cors and dotenv
npm i express cors dotenv
- install dependency
npm i -D ts-node-dev @types/express @types/cors @types/dotenv
- install compression
npm install compression
- install dependency
npm i --save-dev @types/compression
- install eslint
npm install --save-dev eslint @eslint/js typescript typescript-eslint
- add eslint.config.mjs in root
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
/** @type {import('@typescript-eslint/utils').TSESLint.FlatConfig.ConfigFile} */
export default [
eslint.configs.recommended,
tseslint.configs.stylistic,
tseslint.configs.strict,
{
rules: {
"no-console": "warn"
}
}
];
- install prisma related stuffs
npm install prisma typescript tsx @types/node --save-dev
npx prisma init
npm install @prisma/client
- src -> config -> db.ts (this is the prisma client configuration)
import { PrismaClient } from "@prisma/client";
export const prisma = new PrismaClient();
- src -> server.ts
import http, { Server } from "http";
import app from "./app";
import dotenv from "dotenv";
import { prisma } from "./config/db";
dotenv.config();
let server: Server | null = null;
async function connectToDB() {
try {
await prisma.$connect();
console.log("Database Is Connected");
} catch (error) {
console.log("Database Db Connection Failed");
process.exit(1);
}
}
async function startServer() {
try {
await connectToDB();
server = http.createServer(app);
server.listen(process.env.PORT, () => {
console.log(`🚀 Server is running on port ${process.env.PORT}`);
});
handleProcessEvents();
} catch (error) {
console.error("❌ Error during server startup:", error);
process.exit(1);
}
}
/**
* Gracefully shutdown the server and close database connections.
* @param {string} signal - The termination signal received.
*/
async function gracefulShutdown(signal: string) {
console.warn(`🔄 Received ${signal}, shutting down gracefully...`);
if (server) {
server.close(async () => {
console.log("✅ HTTP server closed.");
try {
console.log("Server shutdown complete.");
} catch (error) {
console.error("❌ Error during shutdown:", error);
}
process.exit(0);
});
} else {
process.exit(0);
}
}
/**
* Handle system signals and unexpected errors.
*/
function handleProcessEvents() {
process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
process.on("SIGINT", () => gracefulShutdown("SIGINT"));
process.on("uncaughtException", (error) => {
console.error("💥 Uncaught Exception:", error);
gracefulShutdown("uncaughtException");
});
process.on("unhandledRejection", (reason) => {
console.error("💥 Unhandled Rejection:", reason);
gracefulShutdown("unhandledRejection");
});
}
// Start the application
startServer();
- src -> app.ts
import express, { Request, Response } from "express"
import compression from "compression";
import cors from "cors";
const app = express()
app.use(cors()); // Enables Cross-Origin Resource Sharing
app.use(compression()); // Compresses response bodies for faster delivery
app.use(express.json()); // Parse incoming JSON requests
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
);
app.get("/", (req: Request, res: Response) => {
res.status(200).json({
message: "Welcome To The App"
})
})
app.use((req: Request, res:Response) => {
res.status(404).json({
success: false,
message: "Route Not Found",
});
});
export default app
- schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
role Role @default(USER)
phone String
picture String?
status UserStatus @default(ACTIVE)
isVerified Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
enum Role {
SUPER_ADMIN
ADMIN
USER
}
enum UserStatus {
ACTIVE
INACTIVE
BLOCKED
}
- add the script
"scripts": {
"dev": "ts-node-dev --respawn --transpile-only ./src/server.ts",
"lint": "npx eslint ./src",
"test": "echo \"Error: no test specified\" && exit 1"
},
- run migrate
npx prisma migrate dev
- run the project
npm run dev