Skip to content
mashood-memonPublic

About

trying to learn backend by building a project

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

🚀 TaskFlow Backend

A production-grade task management system built with Node.js, TypeScript, PostgreSQL (Neon DB), and Redis.

Node.js TypeScript Prisma PostgreSQL License


📋 Table of Contents


🎯 Project Overview

TaskFlow is an enterprise-grade task management platform designed for teams and organizations. It supports:

  • ✅ Multi-tenant workspaces - Team collaboration with role-based access
  • ✅ Project & task management - Hierarchical organization with task dependencies
  • ✅ Real-time updates - WebSocket-based live collaboration (Coming Soon)
  • ✅ File attachments - S3-based document storage (Coming Soon)
  • ✅ Activity feeds - Comprehensive audit logs and notifications
  • ✅ Advanced search - Full-text search and filtering (Coming Soon)
  • ✅ Background jobs - Asynchronous email notifications and processing (Coming Soon)
  • ✅ Analytics dashboard - Project insights and team productivity metrics (Coming Soon)

🛠️ Tech Stack

Backend Core

  • Runtime: Node.js 20+ with TypeScript
  • Framework: Express.js with ES Modules
  • Database: PostgreSQL (Neon DB - Serverless)
  • ORM: Prisma 6.19
  • Caching: Redis (Coming Soon)
  • Authentication: JWT with refresh tokens (Coming Soon)

DevOps & Tools

  • Testing: Jest + Supertest
  • Code Quality: ESLint + Prettier
  • Version Control: Git
  • Package Manager: npm
  • Environment: Docker Compose (Coming Soon)

Planned Additions

  • Socket.io for real-time features
  • BullMQ for background job processing
  • AWS S3 for file storage
  • Winston for structured logging
  • Swagger for API documentation

📁 Project Structure

taskflow/
├── prisma/
│   ├── schema.prisma              # Database schema definition
│   └── migrations/                # Database migration history
│       └── 20251125163954_init/   # Initial migration
├── src/
│   ├── config/
│   │   └── database.ts            # Prisma client instance
│   ├── controllers/               # Request handlers (Coming Soon)
│   ├── middleware/                # Express middleware (Coming Soon)
│   ├── routes/                    # API route definitions (Coming Soon)
│   ├── services/                  # Business logic (Coming Soon)
│   ├── types/                     # TypeScript type definitions (Coming Soon)
│   ├── utils/                     # Helper functions (Coming Soon)
│   ├── __tests__/                 # Test files
│   │   └── server.test.ts         # Server integration tests
│   └── server.ts                  # Express app & server entry point
├── .env                           # Environment variables (gitignored)
├── .prettierrc                    # Code formatting rules
├── eslint.config.js               # Linting configuration
├── jest.config.js                 # Testing configuration
├── tsconfig.json                  # TypeScript compiler options
├── package.json                   # Dependencies & scripts
└── README.md                      # Project documentation (you are here!)

🚀 Setup & Installation

Prerequisites

Step 1: Clone the Repository

git clone <your-repo-url>
cd taskflow

Step 2: Install Dependencies

npm install

Step 3: Configure Environment Variables

Create a .env file in the root directory:

# Database (Neon DB)
DATABASE_URL="postgresql://username:password@host.neon.tech/dbname?sslmode=require"

# Server
PORT=3000
NODE_ENV=development

# JWT Secrets (Change these in production!)
JWT_SECRET="your-super-secret-jwt-key-change-this"
JWT_REFRESH_SECRET="your-super-secret-refresh-key-change-this"

# Redis (Coming Soon)
REDIS_URL="redis://localhost:6379"

# AWS S3 (Coming Soon)
AWS_REGION="us-east-1"
AWS_ACCESS_KEY_ID="your-aws-key"
AWS_SECRET_ACCESS_KEY="your-aws-secret"
AWS_S3_BUCKET="taskflow-attachments"

Step 4: Setup Database

# Generate Prisma Client
npx prisma generate

# Run migrations to create database tables
npx prisma migrate dev --name init

# (Optional) Open Prisma Studio to view your database
npx prisma studio

Step 5: Run Development Server

# Start development server with hot-reload
npm run dev

# Server will be available at http://localhost:3000

Step 6: Verify Installation

# Test health endpoint
curl http://localhost:3000/health

# Expected response:
# {"status":"healthy"}

🗄️ Database Schema

Current Schema (Week 1 - Day 4)

Our database is designed for multi-tenancy with the following models:

User

  • id (CUID) - Primary key
  • email (String, unique) - User email address
  • name (String) - Full name
  • passwordHash (String) - Hashed password
  • avatar (String, optional) - Profile picture URL
  • isActive (Boolean) - Account status
  • createdAt, updatedAt - Timestamps

Workspace (Multi-tenant teams)

  • id (CUID) - Primary key
  • name (String) - Workspace name
  • slug (String, unique) - URL-friendly identifier
  • description (String, optional) - Workspace description
  • logo (String, optional) - Workspace logo URL
  • settings (JSON) - Workspace preferences
  • createdById (Foreign key) - Workspace creator
  • createdAt, updatedAt - Timestamps

WorkspaceMember (Team membership)

  • id (CUID) - Primary key
  • role (Enum: OWNER, ADMIN, MEMBER, GUEST) - Access level
  • workspaceId (Foreign key) - Associated workspace
  • userId (Foreign key) - Team member
  • joinedAt - Membership timestamp

Project

  • id (CUID) - Primary key
  • name (String) - Project name
  • description (String, optional) - Project details
  • status (Enum: ACTIVE, ARCHIVED, COMPLETED) - Project state
  • startDate, dueDate (DateTime, optional) - Timeline
  • color (String, optional) - UI color tag
  • workspaceId (Foreign key) - Parent workspace
  • createdById (Foreign key) - Project creator
  • createdAt, updatedAt - Timestamps

Task

  • id (CUID) - Primary key
  • title (String) - Task title
  • description (String, optional) - Task details
  • status (Enum: TODO, IN_PROGRESS, IN_REVIEW, DONE, CANCELLED)
  • priority (Enum: LOW, MEDIUM, HIGH, URGENT)
  • dueDate (DateTime, optional) - Deadline
  • estimatedHours, actualHours (Float, optional) - Time tracking
  • tags (String[]) - Task labels
  • position (Int) - Display order
  • projectId (Foreign key) - Parent project
  • createdById (Foreign key) - Task creator
  • assigneeId (Foreign key, optional) - Assigned user
  • parentTaskId (Foreign key, optional) - Subtask relationship
  • createdAt, updatedAt - Timestamps

Comment

  • id (CUID) - Primary key
  • content (String) - Comment text
  • taskId (Foreign key) - Associated task
  • userId (Foreign key) - Comment author
  • createdAt, updatedAt - Timestamps

Attachment

  • id (CUID) - Primary key
  • filename (String) - Original filename
  • fileUrl (String) - S3 storage URL
  • fileSize (Int) - File size in bytes
  • mimeType (String) - File type
  • taskId (Foreign key) - Associated task
  • uploadedById (Foreign key) - Uploader
  • uploadedAt - Upload timestamp

Notification

  • id (CUID) - Primary key
  • type (Enum: TASK_ASSIGNED, TASK_UPDATED, etc.)
  • title (String) - Notification title
  • message (String) - Notification content
  • isRead (Boolean) - Read status
  • data (JSON, optional) - Additional metadata
  • userId (Foreign key) - Recipient
  • createdAt - Timestamp

ActivityLog (Audit trail)

  • id (CUID) - Primary key
  • action (Enum: CREATED, UPDATED, DELETED, etc.)
  • entityType (String) - Model name (e.g., "Task")
  • entityId (String) - Record ID
  • changes (JSON, optional) - Change details
  • ipAddress, userAgent (String, optional) - Request metadata
  • userId (Foreign key) - User who performed action
  • taskId (Foreign key, optional) - Related task
  • createdAt - Timestamp

Database Relationships

User ──┬─── creates ──> Workspace
       ├─── member of ──> WorkspaceMember
       ├─── creates ──> Project
       ├─── creates ──> Task
       ├─── assigned to ──> Task
       └─── writes ──> Comment, ActivityLog

Workspace ──┬─── has ──> WorkspaceMember
            └─── contains ──> Project

Project ──── contains ──> Task

Task ──┬─── has ──> Comment
       ├─── has ──> Attachment
       ├─── has ──> ActivityLog
       └─── parent of ──> Task (subtasks)

Indexes

We've added strategic indexes for query performance:

@@index([email])              # User lookup
@@index([slug])               # Workspace lookup
@@index([workspaceId, userId]) # Team member queries
@@index([status])             # Task filtering
@@index([priority])           # Task sorting
@@index([projectId])          # Project tasks
@@index([assigneeId])         # User tasks

📊 Development Progress

✅ Week 1: Project Setup & Database Design

Day 1-2: Project Initialization ✅ COMPLETED

  • Initialized Node.js project with TypeScript
  • Configured tsconfig.json for ES2022 modules
  • Set up project folder structure
  • Installed core dependencies (Express, Prisma, TypeScript)
  • Configured package.json scripts
  • Set up .prettierrc for code formatting
  • Configured eslint.config.js for code quality
  • Created .env for environment variables

Day 3-4: Database Schema Design ✅ COMPLETED

  • Designed multi-tenant database architecture
  • Created Prisma schema with 9 models
  • Defined relationships and foreign keys
  • Set up enums for type safety (Role, TaskStatus, Priority, etc.)
  • Added database indexes for performance
  • Generated initial migration
  • Applied migration to Neon DB
  • Created Prisma client singleton (src/config/database.ts)
  • Verified schema with Prisma Studio

Day 5: Docker Setup ⏳ PENDING

  • Create Dockerfile for containerization
  • Create docker-compose.yml for local development
  • Configure PostgreSQL service
  • Configure Redis service
  • Test local container deployment

Day 6-7: Authentication System ⏳ NEXT UP

  • Install authentication dependencies (bcryptjs, jsonwebtoken, zod)
  • Create authentication middleware
  • Implement user registration endpoint
  • Implement login endpoint
  • Implement JWT token generation
  • Implement token refresh logic
  • Create "Get Current User" endpoint
  • Add request validation with Zod
  • Test authentication flow

🔜 Week 2: Core API - Workspaces & Projects (Coming Soon)

🔜 Week 3: Redis Caching & Performance (Coming Soon)

🔜 Week 4: Background Jobs with BullMQ (Coming Soon)

🔜 Week 5: Real-Time Features (Socket.io) (Coming Soon)


📜 Scripts

Development

npm run dev          # Start development server with hot-reload
npm run build        # Compile TypeScript to JavaScript
npm start            # Run production build

Database

npx prisma generate           # Generate Prisma Client
npx prisma migrate dev        # Create and apply migration
npx prisma migrate deploy     # Apply migrations (production)
npx prisma studio             # Open database GUI
npx prisma db seed            # Run seed scripts (coming soon)

Testing

npm test                      # Run all tests once
npm run test:watch            # Run tests in watch mode
npm test -- --coverage        # Run tests with coverage report
npm test -- auth.test.ts      # Run specific test file

Code Quality

npm run lint                  # Check for linting errors
npm run format                # Format code with Prettier

🔐 Environment Variables

Variable Description Example Required
DATABASE_URL Neon PostgreSQL connection string postgresql://user:pass@host/db ✅ Yes
PORT Server port 3000 ❌ No (default: 3000)
NODE_ENV Environment mode development / production ✅ Yes
JWT_SECRET JWT signing key your-secret-key ✅ Yes (Week 1, Day 6)
JWT_REFRESH_SECRET Refresh token signing key your-refresh-secret ✅ Yes (Week 1, Day 6)
REDIS_URL Redis connection string redis://localhost:6379 ✅ Yes (Week 3)
AWS_REGION AWS S3 region us-east-1 ✅ Yes (Week 6)
AWS_ACCESS_KEY_ID AWS access key AKIA... ✅ Yes (Week 6)
AWS_SECRET_ACCESS_KEY AWS secret key secret... ✅ Yes (Week 6)
AWS_S3_BUCKET S3 bucket name taskflow-attachments ✅ Yes (Week 6)

🧪 Testing

Current Test Coverage

 PASS  src/__tests__/server.test.ts
  Server
    GET /
      ✓ should return API info (177ms)
    GET /health
      ✓ should return health status (7ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total

Test Structure

// Example test case
import { describe, it, expect } from '@jest/globals';
import request from 'supertest';
import { app } from '../server';

describe('Server', () => {
  it('should return API info', async () => {
    const res = await request(app).get('/');
    
    expect(res.status).toBe(200);
    expect(res.body).toHaveProperty('message', 'TaskFlow API Server');
  });
});

Running Tests

# Run all tests
npm test

# Watch mode (re-runs on file changes)
npm run test:watch

# Generate coverage report
npm test -- --coverage

📚 API Documentation

Base URL

http://localhost:3000/api

Current Endpoints

Health Check

GET /health

Response:

{
  "status": "healthy"
}

API Info

GET /

Response:

{
  "message": "TaskFlow API Server",
  "status": "ok",
  "timestamp": "2025-11-25T10:30:00.000Z"
}

🔜 Coming Soon: Authentication Endpoints

  • POST /api/auth/register - Create new user account
  • POST /api/auth/login - Authenticate user
  • GET /api/auth/me - Get current user profile
  • POST /api/auth/refresh - Refresh access token
  • POST /api/auth/logout - Logout user

🤝 Contributing

This is a learning project following the Backend Mastery Roadmap.

Development Workflow

  1. Create a feature branch

    git checkout -b feature/your-feature-name
  2. Make your changes

    # Write code
    npm run format    # Format code
    npm run lint      # Check linting
    npm test          # Run tests
  3. Commit your changes

    git add .
    git commit -m "feat: add your feature description"
  4. Push to repository

    git push origin feature/your-feature-name

Commit Message Convention

We follow Conventional Commits:

feat: Add user authentication
fix: Fix database connection pool leak
docs: Update API documentation
test: Add tests for workspace controller
refactor: Improve error handling middleware
chore: Update dependencies

📝 License

MIT License - See LICENSE file for details


🙏 Acknowledgments


📞 Support

For questions or issues:


Built with ❤️ while learning backend development

Last updated: November 25, 2025

About

trying to learn backend by building a project

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages