# idesigner-backend

A Node.js-based backend service for the iDesigner application, built with Express.js, TypeScript, and Prisma ORM. This service provides RESTful APIs for managing users, roles, and other application data. It integrates with PostgreSQL for structured data management and supports DevOps-friendly deployment.

## 🚀 Features

- **TypeScript** - Type-safe development
- **Express.js** - Fast, unopinionated web framework
- **Prisma ORM** - Next-generation ORM for PostgreSQL
- **ESLint** - Code linting and quality checks
- **Husky** - Git hooks for pre-commit checks
- **Scalable Architecture** - Well-structured MVC pattern with services layer
- **Config Driven** - Centralized environment loader for all runtime settings

## 📋 Prerequisites

- Node.js (v18 or higher)
- PostgreSQL (v12 or higher)
- npm or yarn

## 🛠️ Installation

1. **Clone the repository**

   ```bash
   git clone <repository-url>
   cd idesigner-backend
   ```

2. **Install dependencies**

   ```bash
   npm install
   ```

3. **Set up environment variables**

   ```bash
   cp .env.example .env
   ```

   Edit `.env` and update the database connection string:

   ```env
   DATABASE_URL="postgresql://username:password@localhost:5432/idesigner_db?schema={env}"
   ```

4. **Set up the database**

   ```bash
   # Generate Prisma Client
   npm run prisma:generate

   # Run migrations (if needed)
   npm run prisma:migrate
   ```

5. **Start the development server**

   ```bash
   npm run dev
   ```

   The server will start on `http://localhost:3000` (or the port specified in `.env`)

## 🌱 Database Seeding

Run the curated seeders (mirroring the existing Laravel seed flow) against your PostgreSQL database:

```bash
npm run prisma:seed
```

Seeders live in `prisma/seeders` and can be extended per table. The entrypoint `prisma/seed.ts` orchestrates execution order so relational dependencies (e.g., `users` before `user_roles`) are preserved.

## 📁 Project Structure

```
idesigner-backend/
├── .env.example            # Environment variable template
├── .eslintrc.json          # ESLint configuration
├── .gitignore              # Git ignore rules
├── .husky/
│   └── pre-commit          # Lint on commit hook
├── package.json            # Dependencies and npm scripts
├── prisma/
│   ├── schema.prisma       # Prisma schema reflecting PostgreSQL tables
│   ├── seed.ts             # Prisma seeding entrypoint
│   └── seeders/            # Table-specific seeders
│       ├── base.seeder.ts
│       ├── users.seeder.ts
│       └── userRoles.seeder.ts
├── README.md               # Project documentation
├── tsconfig.json           # TypeScript configuration
└── src/
    ├── config/
    │   ├── database.ts     # Prisma client configuration
    │   └── env.ts          # Environment config loader
    ├── controllers/
    │   └── user.controller.ts
    ├── middleware/
    │   ├── bigintSerializer.ts
    │   ├── errorHandler.ts
    │   └── validation.ts
    ├── routes/
    │   ├── index.ts
    │   └── user.routes.ts
    ├── repositories/
    │   ├── base.repository.ts
    │   ├── user.repository.ts
    │   └── userRole.repository.ts
    ├── services/
    │   └── user.service.ts
    ├── types/
    │   └── user.types.ts
    ├── utils/
    │   └── bigint.ts
    └── index.ts            # Express bootstrap
```

## 🔌 API Endpoints

### Users

- `POST /api/v1/users` - Create a new user
- `GET /api/v1/users` - Get all users (with pagination)
- `GET /api/v1/users/:id` - Get user by ID
- `PUT /api/v1/users/:id` - Update user
- `DELETE /api/v1/users/:id` - Soft delete user

### Health Check

- `GET /health` - Server health check

## 📝 Example API Request

### Create User

```bash
curl -X POST http://localhost:3000/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "securepassword123",
    "firstName": "John",
    "lastName": "Doe",
    "status": true,
    "roleIds": [1, 2]
  }'
```

## 🧪 Scripts

- `npm run dev` - Start development server with hot reload
- `npm run build` - Build TypeScript to JavaScript
- `npm start` - Start production server
- `npm run lint` - Run ESLint
- `npm run lint:fix` - Fix ESLint errors automatically
- `npm run prisma:generate` - Generate Prisma Client
- `npm run prisma:migrate` - Run database migrations
- `npm run prisma:studio` - Open Prisma Studio (database GUI)
- `npm run prisma:seed` - Run table-specific Prisma seeders

## 🔒 Git Hooks

Husky is configured to run ESLint on pre-commit. This ensures code quality before commits.

## 🗄️ Database Schema

The application uses PostgreSQL with a `idesigner_local` schema. Main tables:

- `idesigner_local.users` - User information
- `idesigner_local.user_roles` - User role associations

See `prisma/schema.prisma` for the complete schema definition.

## 🛡️ Security

- Helmet.js for security headers
- CORS enabled
- Input validation (can be extended with Joi/Zod)
- Error handling middleware

## 📦 Dependencies

### Production

- `express` - Web framework
- `@prisma/client` - Prisma ORM client
- `dotenv` - Environment variables
- `cors` - CORS middleware
- `helmet` - Security headers
- `morgan` - HTTP request logger

### Development

- `typescript` - TypeScript compiler
- `tsx` - TypeScript execution
- `eslint` - Code linter
- `husky` - Git hooks
- `prisma` - Prisma CLI

## 🚀 Deployment

### Scripts for Deployment (Dev/QA/Production)

Since the application is built from scratch with the database as the base, you **only need** these scripts for deployment:

```bash
# 1. Generate Prisma Client (automatically merges schema.prisma first)
npm run prisma:generate

# 2. Apply database migrations (if any)
npm run migrate:apply

# 3. Build the application
npm run build

# 4. Start the application
npm start
```

**Note:** `prisma:generate` automatically runs `prisma:merge` first, so you don't need to run them separately.

### Development-Only Scripts (NOT needed for deployment)

These scripts are prefixed with `_dev:` and are only used during development:

- `_dev:prisma:introspect` - Sync database schema to Prisma models (not needed when building from scratch)
- `_dev:prisma:find-missing` - Find columns in Prisma but missing in DB (not needed when building from scratch)

**Note:** Since you're building the application from scratch with the database as the base, you don't need introspection or schema sync scripts for deployment. The Prisma models are manually maintained to match your database structure.

### Deployment Checklist

1. ✅ Set environment variables (`.env` file)
2. ✅ Run `npm run build` (automatically generates schema.prisma, Prisma Client, and compiles TypeScript)
3. ✅ Run `npm run migrate:apply` if there are new migrations
4. ✅ Run `npm start` to start the server

**Important:** 
- `schema.prisma` is **auto-generated** from `prisma/models/` files and should **NOT** be committed to git
- The `build` command automatically runs `prisma:generate` which merges all model files and generates Prisma Client
- Each environment (dev/QA/prod) will generate `schema.prisma` fresh from the model files

## 🤝 Contributing

1. Create a feature branch
2. Make your changes
3. Ensure all tests pass and linting is clean
4. Submit a pull request

## 📄 License

Copyright (c) Softnotions Technologies Pvt Ltd
All rights reserved.

This software is proprietary and confidential.
Unauthorized copying, distribution, or modification is prohibited.

