Skip to content

Toviarock1/worknest-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

34 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WorkNest Backend

A comprehensive backend API for WorkNest - a collaborative project management application with real-time features.

πŸš€ Features

Core Functionality

  • πŸ” Authentication System - Secure user registration and login with JWT tokens
  • πŸ“ Project Management - Create, update, and manage collaborative projects
  • βœ… Task Management - Create, assign, track, and manage tasks within projects
  • πŸ’¬ Real-time Messaging - Instant chat functionality within project rooms
  • πŸ“Ž File Management - Upload and share files using Cloudinary integration
  • πŸ‘€ User Management - User profiles, updates, and search functionality

Technical Features

  • πŸ”„ Real-time Updates - Socket.io integration for live notifications
  • πŸ›‘οΈ Security - JWT authentication, rate limiting, helmet security headers
  • βœ… Input Validation - Zod schema validation for all inputs
  • πŸ“ Logging - Winston logger for error and activity tracking
  • ⚑ API Rate Limiting - Protection against brute-force attacks
  • ☁️ Cloud Storage - Cloudinary integration for file uploads
  • 🐳 Docker Support - PostgreSQL database in containerized environment

πŸ—οΈ Tech Stack

Category Technology
Runtime Node.js
Language TypeScript
Framework Express.js
Database PostgreSQL
ORM Prisma
Real-time Socket.io
Authentication JWT (jsonwebtoken)
Validation Zod
File Storage Cloudinary
Logging Winston
Rate Limiting express-rate-limit
Security Helmet, CORS, Compression
Development nodemon, tsx, ts-node

πŸ“ Project Structure

WorkNest-Backend/
β”œβ”€β”€ prisma/
β”‚   β”œβ”€β”€ schema.prisma          # Database schema
β”‚   └── migrations/            # Database migrations
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app.ts                 # Express app configuration
β”‚   β”œβ”€β”€ index.ts               # Application entry point
β”‚   β”œβ”€β”€ routes.ts              # API routes aggregation
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”œβ”€β”€ cloudinary.ts      # Cloudinary configuration
β”‚   β”‚   β”œβ”€β”€ db.ts              # Prisma database client
β”‚   β”‚   β”œβ”€β”€ env.ts             # Environment variables validation
β”‚   β”‚   └── socket.ts          # Socket.io setup
β”‚   β”œβ”€β”€ constants/
β”‚   β”‚   └── statusCodes.ts     # HTTP status codes
β”‚   β”œβ”€β”€ middlewares/
β”‚   β”‚   β”œβ”€β”€ auth.middleware.ts # JWT authentication
β”‚   β”‚   β”œβ”€β”€ error.middleware.ts# Global error handling
β”‚   β”‚   β”œβ”€β”€ rateLimit.middleware.ts # API rate limiting
β”‚   β”‚   └── validation.middleware.ts # Zod schema validation
β”‚   β”œβ”€β”€ modules/
β”‚   β”‚   β”œβ”€β”€ auth/              # Authentication module
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.controller.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.routes.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.schema.ts
β”‚   β”‚   β”‚   └── auth.service.ts
β”‚   β”‚   β”œβ”€β”€ file/              # File management module
β”‚   β”‚   β”œβ”€β”€ messages/          # Messaging module
β”‚   β”‚   β”œβ”€β”€ projects/          # Project management module
β”‚   β”‚   β”œβ”€β”€ tasks/             # Task management module
β”‚   β”‚   └── user/              # User management module
β”‚   β”œβ”€β”€ startup/
β”‚   β”‚   └── prod.ts            # Production middleware setup
β”‚   └── utils/
β”‚       β”œβ”€β”€ AppError.ts        # Custom error class
β”‚       β”œβ”€β”€ catchAsync.ts      # Async error wrapper
β”‚       β”œβ”€β”€ permissions.ts     # Authorization utilities
β”‚       └── responseObject.ts  # API response formatter
β”œβ”€β”€ docker-compose.yml         # Docker configuration
β”œβ”€β”€ nodemon.json               # Nodemon configuration
β”œβ”€β”€ package.json               # Dependencies and scripts
└── tsconfig.json              # TypeScript configuration

πŸ“¦ API Endpoints

Authentication (/api/v1/auth)

Method Endpoint Description
POST /auth/register Register a new user
POST /auth/login Login and get JWT token

Users (/api/v1/user)

Method Endpoint Description
GET /user/me Get current user profile
PATCH /user/me Update user details
GET /user/search?q=email Search users by email

Projects (/api/v1/project)

Method Endpoint Description
POST /project Create a new project
GET /project Get all user's projects
GET /project/:id/members Get project members
POST /project/add-member Add member to project
POST /project/remove-member Remove member from project
PATCH /project/:id Update project details
DELETE /project/:id Delete project

Tasks (/api/v1/tasks)

Method Endpoint Description
POST /tasks Create a new task
GET /tasks/:id Get tasks for a project
PATCH /tasks/:taskId Update task status
PATCH /tasks/:taskId/assign Assign task to user
DELETE /tasks/:taskId Delete task

Messages (/api/v1/message)

Method Endpoint Description
POST /message Send a message
GET /message/:projectId Get chat history

Files (/api/v1/file)

Method Endpoint Description
POST /file/upload Upload a file
GET /file/:projectId Get project files
DELETE /file/:fileId Delete a file

πŸ”Œ Socket.io Events

Authentication

Socket.io connections require JWT authentication. Pass the JWT token in the handshake query or headers:

const socket = io("http://localhost:5050", {
  query: { token: "your-jwt-token" },
});

Or in headers:

const socket = io("http://localhost:5050", {
  extraHeaders: { token: "your-jwt-token" },
});

Client β†’ Server

Event Payload Description
join_project projectId Join a project room

Server β†’ Client

Event Payload Description
invited_to_project { projectId } User added to project
new_message Message New message sent
task_created Task New task created
task_updated Task Task status updated
task_assigned Task Task assigned to user
new_file File New file uploaded

πŸ—„οΈ Database Schema

Models

User

  • id - UUID primary key
  • name - Optional display name
  • email - Unique email address
  • password - Hashed password
  • Relations: projects, projectMembers, tasks, messages, files

Project

  • id - UUID primary key
  • name - Project name
  • ownerId - Owner user ID
  • description - Optional description
  • Relations: owner, members, tasks, messages, files

ProjectMember

  • id - UUID primary key
  • userId - User ID
  • projectId - Project ID
  • role - "owner" or "member"
  • Unique: [userId, projectId]

Task

  • id - UUID primary key
  • title - Task title
  • description - Optional description
  • status - "todo", "in_progress", or "done"
  • projectId - Project ID
  • assignedToId - Optional assignee ID

Message

  • id - UUID primary key
  • content - Message text
  • projectId - Project ID
  • senderId - Sender user ID

File

  • id - UUID primary key
  • name - File name
  • url - Cloudinary URL
  • size - File size in bytes
  • projectId - Project ID
  • uploaderId - Uploader user ID

πŸš€ Getting Started

Prerequisites

  • Node.js (v18+)
  • PostgreSQL (or use Docker)
  • Cloudinary account

Installation

  1. Clone the repository

    cd WorkNest-Backend
  2. Install dependencies

    npm install
  3. Set up environment variables

    cp .env.example .env  # If you have an example file

    Or create .env with the following:

    NODE_ENV=development
    PORT=5050
    DATABASE_URL=postgresql://postgres@localhost:5433/worknest
    JWT_SECRET=your-super-secret-key-at-least-32-characters
    JWT_EXPIRES_IN=7d
    CLOUDINARY_CLOUD_NAME=your-cloud-name
    CLOUDINARY_API_KEY=your-api-key
    CLOUDINARY_API_SECRET=your-api-secret
  4. Set up the database

    # Using Docker (recommended)
    npm run dock:start
    
    # Or use your local PostgreSQL
  5. Run database migrations

    npm run db:setup
  6. Start the development server

    # Development mode (with hot reload)
    npm run dev
    
    # Or build and run production server
    npm run build
    npm start

    The server will be running at http://localhost:5050

Available Scripts

Script Description
npm run dev Start development server with tsx
npm run build Build for production
npm run start Start production server
npm run db:migrate Run Prisma migrations
npm run db:push Push schema to database
npm run db:generate Generate Prisma client
npm run db:setup Run migrations and generate client
npm run db:view Open Prisma Studio
npm run dock:start Start Docker containers
npm run dock:stop Stop Docker containers

πŸ” Security Features

  • JWT Authentication - Secure token-based auth
  • Password Hashing - bcrypt with salt rounds
  • Rate Limiting - 100 requests/15min for API, 5 attempts/hour for auth
  • Helmet - Security headers (CSP, HSTS, etc.)
  • CORS - Cross-origin resource sharing control
  • Input Validation - Zod schemas for all inputs
  • Error Handling - Global error middleware with logging

πŸ“ API Response Format

All API responses follow this structure:

{
  message: string; // Human-readable message
  status: number; // HTTP status code
  success: boolean; // Indicates success/failure
  data: object; // Response data
}

Example success response:

{
  "message": "Project created successfully",
  "status": 201,
  "success": true,
  "data": {
    "id": "uuid",
    "name": "My Project",
    "ownerId": "uuid"
  }
}

Example error response:

{
  "message": "Validation Error",
  "status": 400,
  "success": false,
  "data": [
    {
      "path": "email",
      "message": "Invalid email format"
    }
  ]
}

πŸ§ͺ Error Handling

The application uses a centralized error handling middleware that:

  • Catches all errors globally
  • Logs errors with Winston (error.log for 5xx, combined.log for all)
  • Returns appropriate HTTP status codes
  • Includes stack traces only in development mode

Custom Error Classes

// Custom operational error
throw new AppError("User not found", 404);

🐳 Docker Support

Start PostgreSQL with Docker:

# Start the container
npm run dock:start

# Stop the container
npm run dock:stop

Docker configuration in docker-compose.yml:

  • PostgreSQL 17 Alpine
  • Port 5433 mapped to host
  • Persistent volume for data

πŸ“„ License

ISC License

πŸ‘¨β€πŸ’» Author

Developed with ❀️ by Simon Adama for collaborative project management

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors