Eve library

Aphrodite Domain - Code Quality Report

Guide

Revision 1

On this page

Technical debt assessment and code quality analysis of the Eve codebase for migration to the Aphrodite domain within the Oshun monorepo.

Analysis Date: January 2026 Scope: Eve Platform TypeScript/JavaScript codebase Methodology: Static analysis, pattern detection, code metrics


Executive Summary#

Codebase Statistics:

Metric Value
Total TypeScript files ~1,270
Non-test source files ~451 (apps)
Test files ~20 (4.4% test file ratio)
Largest files Up to 795 lines
Code organization 12 packages, monorepo

Overall Risk Assessment: MEDIUM-HIGH

  • Type safety issues present but not critical
  • Test coverage gaps in production services
  • Some files exceed maintainability thresholds
  • Good architectural patterns with isolated concerns

Table of Contents#

  1. TypeScript Type Quality
  2. Code Duplication
  3. Code Smells
  4. Naming Conventions
  5. Error Handling
  6. Async/Await Issues
  7. Import/Export Issues
  8. Testing Gaps
  9. Technical Debt Summary
  10. Remediation Plan

1. TypeScript Type Quality#

Issue 1.1: Widespread Use of any Type#

Attribute Details
Severity MEDIUM
Effort 2-3 days
Files Affected 22+ files

Statistics:

  • 37 instances of as any casts
  • 102 instances of : any type annotations

Critical Files:

File Lines Issue
services/shared/src/database/prisma-helpers.ts 540 Cast in cursor handling
services/shared/src/database/prisma-client.ts 148, 156, 160 Prisma events typed as any
services/shared/src/api/metrics.controller.ts Multiple 9 instances of error: any
services/shared/src/middleware/caching.ts - etagGenerator typed as any
services/shared/src/caching/cache-invalidation.ts 172, 213, 264, 387 JSON responses as any

Example - Bad:

typescript
// prisma-helpers.ts:540
? (items[items.length - 1] as any).id  // Why cast to any?

// metrics.controller.ts:62+
} catch (error: any) {
  res.status(error.statusCode || 500).json(...)
}

Example - Better:

typescript
type APIError = Error & { statusCode?: number };

} catch (error: unknown) {
  const apiError = error as APIError | Error;
  const statusCode = 'statusCode' in apiError ? apiError.statusCode : 500;
}

Impact:

  • Loss of compile-time type safety
  • Difficult refactoring (renaming breaks at runtime)
  • IDE autocomplete ineffective
  • Hard to catch API contract violations

Suggested Fixes:

  1. Create proper error types for catch blocks
  2. Type Prisma event callbacks properly
  3. Define interfaces for JSON responses
  4. Use unknown instead of any where appropriate

Issue 1.2: Implicit Any - Untyped Function Parameters#

Attribute Details
Severity LOW-MEDIUM
Effort 1-2 days
Location apps/user-service/src/subscription/subscriptions.ts:20-40

Example - Bad:

typescript
interface SubscriptionDeps {
  tierRepo: {
    findById: (tierId: string) => Promise<any>; // Any type for tier
    findActiveByCreator: (creatorId: string) => Promise<any[]>;
  };
  subscriptionRepo: {
    create: (input: any) => Promise<Subscription>; // Any input
  };
}

Example - Better:

typescript
interface Tier {
  id: string;
  creatorId: string;
  name: string;
  price: number;
}

interface CreateSubscriptionInput {
  subscriberId: string;
  tierId: string;
}

interface SubscriptionDeps {
  tierRepo: {
    findById: (tierId: string) => Promise<Tier | null>;
    findActiveByCreator: (creatorId: string) => Promise<Tier[]>;
  };
  subscriptionRepo: {
    create: (input: CreateSubscriptionInput) => Promise<Subscription>;
  };
}

Issue 1.3: Missing Type Definitions for Express Extensions#

Attribute Details
Severity MEDIUM
Effort 1 day
Files apps/user-service/src/subscription/api/router.ts:16, services/shared/src/middleware/profiling.middleware.ts:259,282

Example - Bad:

typescript
function getUserId(req: Request): string {
  return (req as any).user?.id || ''; // User is typed as any
}

(req as any).profilingMetadata = { ... }; // Lost type info

Example - Better:

typescript
declare global {
  namespace Express {
    interface Request {
      user?: {
        id: string;
        email?: string;
        role?: string;
      };
      profilingMetadata?: {
        requestId: string;
        startTime: number;
        startMemory?: NodeJS.MemoryUsage;
      };
    }
  }
}

// Now use without casting
function getUserId(req: Request): string {
  return req.user?.id || ''; // Properly typed
}

2. Code Duplication#

Issue 2.1: Repeated Error Handling Patterns#

Attribute Details
Severity MEDIUM
Effort 2-3 days
Files apps/user-service/src/subscription/api/router.ts, apps/user-service/src/subscription-billing-worker.ts:86-94

Pattern repeated 20+ times:

typescript
router.post('/endpoint', async (req: Request, res: Response) => {
  try {
    const data = SomeSchema.parse(req.body);
    const result = await service.doSomething(data);
    res.status(201).json({ data: result });
  } catch (error: any) {
    if (error instanceof z.ZodError) {
      return res.status(400).json({
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Invalid input',
          details: error.flatten().fieldErrors,
        },
      });
    }
    res.status(error.statusCode || 500).json({
      error: {
        code: error.name || 'INTERNAL_ERROR',
        message: error.message,
      },
    });
  }
});

Suggested Fix - Create middleware:

typescript
function handleRouteError(res: Response, error: unknown): void {
  if (error instanceof z.ZodError) {
    return res.status(400).json({
      error: {
        code: 'VALIDATION_ERROR',
        message: 'Invalid input',
        details: error.flatten().fieldErrors,
      },
    });
  }
  // ... other error types
}

function asyncHandler(fn: RequestHandler) {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch((error) =>
      handleRouteError(res, error)
    );
  };
}

Issue 2.2: Duplicated Event Subscription Patterns#

Attribute Details
Severity LOW
Effort 1 day
Location services/shared/src/caching/cache-invalidation.ts:625-678

Pattern repeated 8 times:

typescript
eventBus.on('user.updated', async (event: any) => {
  await this.invalidate({
    strategy: InvalidationStrategy.TAG,
    tags: [`user:${event.id}`],
  });
});

eventBus.on('user.deleted', async (event: any) => {
  await this.invalidate({
    strategy: InvalidationStrategy.TAG,
    tags: [`user:${event.id}`],
  });
});

Suggested Fix - Configuration-driven:

typescript
private setupEventListeners() {
  const eventTypeToTags = {
    'user.updated': (event: any) => [`user:${event.id}`],
    'user.deleted': (event: any) => [`user:${event.id}`],
    'stream.created': (event: any) => [`stream:${event.id}`, 'streams'],
    'stream.updated': (event: any) => [`stream:${event.id}`],
  };

  for (const [eventType, getTags] of Object.entries(eventTypeToTags)) {
    eventBus.on(eventType, async (event: any) => {
      await this.invalidate({
        strategy: InvalidationStrategy.TAG,
        tags: getTags(event),
      });
    });
  }
}

3. Code Smells#

Issue 3.1: Functions Exceeding Size Limits#

Attribute Details
Severity MEDIUM
Effort 2-3 days per file
Guideline Functions should be < 30 lines (max 50)

Oversized Functions:

File Location Lines Issue
services/shared/src/database/mongodb-helpers.ts Various 795 total Multiple 100+ line functions
services/shared/src/database/prisma-helpers.ts Various 677 total Multiple field selection functions
services/shared/src/middleware/compression.ts Various 489 total Large compression logic
services/shared/src/caching/cache-invalidation.ts 147-250 103 lines Cloudflare purge implementation
apps/user-service/src/fanclub-service.ts 21-413 393 lines Single factory function
apps/user-service/src/subscription/api/router.ts 19-365 346 lines Router setup function

Example - fanclub-service.ts (393 lines in ONE function):

typescript
export async function createFanClubService(
  postRepo,
  likeRepo,
  commentRepo,
  subscriptionService,
  eventBus
): Promise<IFanClubService> {
  async function getFanClubPage(...) { ... }  // 45 lines
  async function createPost(...) { ... }      // 25 lines
  async function updatePost(...) { ... }      // 30 lines
  // ... 20 more nested functions
  return { getFanClubPage, createPost, updatePost, ... };
}

Suggested Fix - Use class:

typescript
export class FanClubService implements IFanClubService {
  constructor(
    private postRepo: IFanClubPostRepository,
    private likeRepo: IPostLikeRepository,
    private commentRepo: IPostCommentRepository,
    private subscriptionService: ISubscriptionService,
    private eventBus: EventEmitter
  ) {}

  async getFanClubPage(
    creatorId: string,
    viewerId?: string
  ): Promise<FanClubPageInfo> {
    // 45 lines - single method
  }

  async createPost(
    creatorId: string,
    input: CreatePostInput
  ): Promise<FanClubPost> {
    // 25 lines - single method
  }
}

Issue 3.2: Files Exceeding Size Limits#

Attribute Details
Severity MEDIUM
Effort 2-3 days
Guideline Max 500 lines per source file

Oversized Files:

File Lines Recommendation
services/shared/src/database/mongodb-helpers.ts 795 Split into: projections, query-helpers, aggregation-helpers
services/shared/src/database/prisma-helpers.ts 677 Split into: selections, user-queries, stream-queries, utils
services/shared/src/middleware/compression.ts 489 At threshold - monitor
services/shared/src/caching/cache-invalidation.ts 714 Split into: cdn-providers, invalidation-strategy, event-listeners
services/shared/src/services/performance-monitor.service.ts 646 Split into: metrics-store, monitor-service, alert-system

Issue 3.3: Deeply Nested Code (>4 levels)#

Attribute Details
Severity MEDIUM
Effort MEDIUM
Location apps/user-service/src/subscription-billing-worker.ts:86-94

Example - 5 levels of nesting:

typescript
for (const subscription of dueSubscriptions) {
  // 1
  try {
    // 2
    await this.processSingleSubscription(sub.id); // 3
  } catch (error) {
    // 2
    appLogger.error(...); // 3
  }
}

Better - Early returns:

typescript
async function processSubscriptions(subscriptions: Subscription[]) {
  const results = await Promise.allSettled(
    subscriptions.map((sub) => this.processSingleSubscription(sub.id))
  );

  results.forEach((result, index) => {
    if (result.status === 'rejected') {
      appLogger.error(`Failed to process ${subscriptions[index].id}`);
    }
  });
}

Issue 3.4: Magic Numbers and Strings#

Attribute Details
Severity LOW-MEDIUM
Effort 1-2 days

Instances Found:

Location Value Purpose
performance-monitor.service.ts:91 2000 2s threshold for p95 response time
performance-monitor.service.ts:96 10000 max memory bytes
performance-monitor.service.ts:114 60000 check interval (1 minute)
mongodb-client.ts:67-70 Various timeout values (90s, 15s, 10s)
profiling.middleware.ts:83 1000 1 second slow threshold
profiling.middleware.ts:98 10000 max metrics stored
compression.ts:222 1024 1KB compression threshold

Suggested Fix - Constants file:

typescript
export const PERFORMANCE_THRESHOLDS = {
  P95_RESPONSE_TIME_MS: 2000,
  MAX_MEMORY_BYTES: 10000,
  CHECK_INTERVAL_MS: 60 * 1000,
  SLOW_REQUEST_THRESHOLD_MS: 1000,
} as const;

export const MONGODB_TIMEOUTS = {
  MAX_IDLE_TIME_MS: 90 * 1000,
  WAIT_QUEUE_TIMEOUT_MS: 15 * 1000,
  CONNECT_TIMEOUT_MS: 10 * 1000,
  SOCKET_TIMEOUT_MS: 60 * 1000,
} as const;

export const COMPRESSION = {
  THRESHOLD_BYTES: 1024,
  MIN_RESPONSE_SIZE: 1024,
} as const;

4. Naming Conventions#

Issue 4.1: Inconsistent Naming Patterns#

Attribute Details
Severity LOW
Effort 1 day

Observations:

  • Good: Mostly consistent camelCase for functions/variables, PascalCase for types
  • Issues:
    • Mix of repo and repository terminology
    • Inconsistent suffix patterns: Service, Helper, Manager used without clear distinction
    • TypeScript .js extensions in imports inconsistently used

Example:

typescript
// Inconsistent terminology
const tierRepo = ...;         // "repo"
const subscriptionRepo = ...;  // "repo"
const CDNProvider = ...;       // All caps

// Should be consistent
const tierRepository = ...;
const subscriptionRepository = ...;
const CdnProvider = ...;

5. Error Handling#

Issue 5.1: Error Type Coercion in Catch Blocks#

Attribute Details
Severity MEDIUM
Effort 1-2 days
Files 9+ files use catch (error: any)

Example - Bad:

typescript
} catch (error: any) {
  res.status(error.statusCode || 500).json({
    error: {
      code: error.name || 'INTERNAL_ERROR',
      message: error.message,
    },
  });
}

Issues:

  • Unknown errors might not have .statusCode, .name, .message
  • No type safety for error structure
  • Runtime errors possible if error shape changes

Suggested Fix - Typed error hierarchy:

typescript
class AppError extends Error {
  constructor(
    message: string,
    public code: string,
    public statusCode: number = 500
  ) {
    super(message);
  }
}

class ValidationError extends AppError {
  constructor(public details: Record<string, string[]>) {
    super('Validation failed', 'VALIDATION_ERROR', 400);
  }
}

// Proper catch handling
} catch (error: unknown) {
  if (error instanceof ValidationError) {
    return res.status(400).json({
      error: {
        code: 'VALIDATION_ERROR',
        message: error.message,
        details: error.details,
      },
    });
  }

  if (error instanceof AppError) {
    return res.status(error.statusCode).json({
      error: {
        code: error.code,
        message: error.message,
      },
    });
  }

  // Unknown error - safe fallback
  appLogger.error('Unexpected error:', error);
  return res.status(500).json({
    error: {
      code: 'INTERNAL_ERROR',
      message: 'An unexpected error occurred',
    },
  });
}

Issue 5.2: Missing Error Logging in Catch Blocks#

Attribute Details
Severity MEDIUM
Effort 1-2 days
Files services/shared/src/caching/cache-invalidation.ts:188+, apps/user-service/src/subscription-billing-worker.ts

Example - Bad:

typescript
try {
  // do something
} catch (error) {
  // No logging, error is lost
  return { success: false };
}

Example - Better:

typescript
try {
  // do something
} catch (error) {
  appLogger.error(
    'Operation failed:',
    error instanceof Error ? error.message : String(error)
  );
  throw error; // or handle appropriately
}

6. Async/Await Issues#

Issue 6.1: Promise.all Without Error Handling#

Attribute Details
Severity LOW-MEDIUM
Effort < 1 day
Files apps/user-service/src/health.ts:20, apps/moderation-service/src/ai-moderation/pipelines.ts:48, apps/recommendation-service/src/recommendation/algorithms.ts:70

Example - Potential Issue:

typescript
// If one promise fails, all fail
const [dbOk, redisOk] = await Promise.all([
  deps.checkDatabase(),
  deps.checkRedis(),
]);

Better Approach:

typescript
const [dbResult, redisResult] = await Promise.allSettled([
  deps.checkDatabase(),
  deps.checkRedis(),
]);

const dbOk = dbResult.status === 'fulfilled' ? dbResult.value : false;
const redisOk = redisResult.status === 'fulfilled' ? redisResult.value : false;

Issue 6.2: Positive Async Patterns Observed#

  • Consistent use of async/await over .then() chains
  • Promise error handling generally properly implemented
  • Few unhandled promise rejections detected

7. Import/Export Issues#

Issue 7.1: TypeScript File Extensions in Imports#

Attribute Details
Severity LOW
Effort < 1 day
Location apps/user-service/src/subscription/subscriptions.ts:1

Example:

typescript
// Inconsistent - TypeScript shouldn't need .js extension
import { calculatePeriodEnd, isSubscriptionActive } from './utils.js';

// Should be
import { calculatePeriodEnd, isSubscriptionActive } from './utils';

Issue 7.2: Index Files - Good Practice#

Finding: 63 index.ts files found - good modular organization


Issue 7.3: Circular Dependencies#

Status: No circular dependencies detected Note: Monorepo structure with clear service boundaries reduces risk


8. Testing Gaps#

Issue 8.1: Insufficient Test Coverage#

Attribute Details
Severity HIGH
Effort 5+ days per service

Coverage Statistics:

Category Count Coverage
Non-test source files 451 100%
Test files 20 4.4% ratio
Apps with tests 2 of 14 14%
Services with tests 1 of 8+ 12%

Files Without Tests:

Service Status
apps/user-service/ No unit/integration tests
apps/chat-service/ No tests for main service
apps/content-service/ No tests
apps/recommendation-service/ No tests
apps/moderation-service/ No tests

Tested Components:

  • services/shared/src/__tests__/ - 2 test files
  • tests/ - Integration/e2e tests (14 files, ~9,000 lines)

Required Test Files:

text
apps/
├── user-service/src/
│   ├── fanclub-service.ts             NO TEST
│   ├── subscription/subscriptions.ts  NO TEST
│   ├── subscription-billing-worker.ts NO TEST
│   └── login.ts                       NO TEST
├── chat-service/src/
│   ├── dm-service.ts                  NO TEST
│   ├── moderation-service.ts          NO TEST
│   └── socket.ts                      NO TEST
└── ...

Issue 8.2: Test Organization#

Finding: Test files in /eve/tests/ are integration/e2e, not unit tests

Best Practice Structure:

text
apps/user-service/src/
├── fanclub-service.ts
├── fanclub-service.test.ts           <- Co-locate tests
├── subscription/
│   ├── subscriptions.ts
│   └── subscriptions.test.ts         <- Co-locate tests
└── __tests__/                        <- Or group if many
    ├── fanclub-service.test.ts
    └── subscriptions.test.ts

9. Technical Debt Summary#

By Priority#

Priority Category Issues Effort
CRITICAL Testing Missing unit tests for 5+ services 15-20 days
HIGH Type Safety 139+ any instances 5-7 days
HIGH Code Duplication Repeated patterns 5-8 days
HIGH File Size 5 files over 500 lines 5-7 days
MEDIUM Error Handling Inconsistent patterns 3-5 days
LOW Naming Inconsistent conventions 1 day
LOW Constants Magic numbers 1-2 days

Total Estimated Effort#

Category Effort
Type Safety Improvements 5-7 days
Unit Test Coverage 15-20 days
Code Duplication Cleanup 5-8 days
Large Function Refactoring 5-7 days
Error Handling Standardization 3-5 days
Documentation & Cleanup 3-5 days
Total 36-52 days

10. Remediation Plan#

Phase 1: Critical (Sprint 1)#

Task Effort Priority
Add unit tests for user-service 5 days P0
Add unit tests for chat-service 3 days P0
Fix error handling types in metrics controller 1 day P0

Phase 2: High Priority (Sprint 2)#

Task Effort Priority
Extract large functions in fanclub-service 2 days P1
Break up database helpers files 3 days P1
Standardize error handling pattern 2 days P1

Phase 3: Medium Priority (Sprint 3)#

Task Effort Priority
Replace any types with proper types 5 days P2
Add Express Request/Response type augmentation 1 day P2
Extract cache invalidation event handlers 1 day P2

Phase 4: Ongoing (Backlog)#

Task Effort Priority
Remove TypeScript .js extensions 0.5 days P3
Extract magic numbers to constants 1 day P3
Add JSDoc to complex functions 2 days P3
Refactor deeply nested code 1 day P3

Recommendations#

  1. Enable strict TypeScript settings - noImplicitAny, exactOptionalPropertyTypes
  2. Implement pre-commit hooks - Lint, type check, test requirements
  3. Establish testing standard - Minimum 80% coverage on new code
  4. Use code metrics tooling - SonarQube/CodeClimate to track issues
  5. Refactor incrementally - Don't do all at once
  6. Create reusable patterns - Error handler middleware, logging utilities
  7. Document API contracts - Use OpenAPI/Swagger for type safety

Appendix: Files Requiring Attention#

File Issues Priority
services/shared/src/database/mongodb-helpers.ts 795 lines, split needed HIGH
services/shared/src/database/prisma-helpers.ts 677 lines, any types HIGH
services/shared/src/caching/cache-invalidation.ts 714 lines, duplication HIGH
services/shared/src/api/metrics.controller.ts 9 error: any instances MEDIUM
apps/user-service/src/fanclub-service.ts 393 line function MEDIUM
apps/user-service/src/subscription/api/router.ts Duplicate error handling MEDIUM
services/shared/src/middleware/compression.ts At size threshold LOW
apps/user-service/src/subscription/subscriptions.ts .js imports, any types LOW