Decapretated ‐ 5. Social Commerce Service (SCS) ‐ MongoDB Edition - Wiz-DevTech/prettygirllz GitHub Wiki

Social Commerce Service (SCS) - MongoDB Edition

A Java/Maven implementation with MongoDB for real-time product chats, community feeds, and AI moderation


🚀 Features

Product Chat - Real-time messaging with WebSockets and MongoDB history
Community Feed - TikTok-style feed with personalized recommendations
Content Moderation - AI + human review workflow with audit trails
MongoDB Optimized - Full leverage of document model for social commerce data


📦 Module Structure

social-commerce-service/
├── product-chat/               # Real-time messaging
│   ├── src/main/java/com/example/chat/
│   │   ├── config/            # WebSocket config
│   │   ├── model/             # MongoDB documents
│   │   ├── repository/        # Spring Data MongoDB
│   │   └── service/           # Chat logic
├── community-feed/            # Content feed engine
│   ├── src/main/java/com/example/feed/
│   │   ├── model/             # Feed documents
│   │   └── service/           # Recommendation logic
├── content-moderation/        # Moderation system
│   ├── src/main/java/com/example/moderation/
│   │   ├── model/             # Moderation records
│   │   └── service/           # AI/human workflow
└── integration-tests/         # Test containers

⚙️ Tech Stack

  • Java 17+ (Spring Boot 3.x)
  • MongoDB 6.0+ (Document model, Change Streams)
  • Spring WebSockets (STOMP protocol)
  • Test Containers (Integration testing)
  • Lombok (Reduced boilerplate)

🔧 Setup

1. Prerequisites

  • MongoDB 6.0+ (Local or Atlas URI)
  • Java 17 JDK
  • Maven 3.9+

2. Configuration

# application.properties
spring.data.mongodb.uri=mongodb://localhost:27017/social_commerce
spring.data.mongodb.auto-index-creation=true

# WebSocket endpoint
app.websocket.endpoint=/live-chat

3. Run the Service

mvn spring-boot:run -pl product-chat  # Start chat service
mvn spring-boot:run -pl community-feed  # Start feed service

🧪 Testing

1. Unit Tests

mvn test  # Runs all unit tests

2. Integration Tests

Test Containers (MongoDB):

@Testcontainers
class ChatRepositoryIT {
    @Container 
    static MongoDBContainer mongo = new MongoDBContainer("mongo:6.0");
    
    @Test
    void whenMessageSaved_thenCanRetrieve() {
        ChatMessage msg = new ChatMessage("prod123", "user1", "Hello!");
        repository.save(msg);
        assertThat(repository.findByProductId("prod123")).hasSize(1);
    }
}

3. API Testing

WebSocket Chat:

# Connect using STOMP client
stomp-cli connect ws://localhost:8080/live-chat
> SEND destination:/chat/prod123 content-type:application/json {"text":"Test message"}

Feed API:

curl -X GET "http://localhost:8080/feed/user123?limit=10"

📊 MongoDB Optimization

Indexes

// Product Chat indexes
@CompoundIndex(name = "product_status_idx", 
               def = "{productId: 1, status: 1, timestamp: -1}")
public class ChatMessage { ... }

// Feed indexes
@CompoundIndex(name = "user_score_idx", 
               def = "{userId: 1, score: -1}")
public class FeedItem { ... }

Change Streams

// Real-time moderation updates
mongoTemplate.changeStream(ModerationDecision.class)
    .listen()
    .doOnNext(event -> {
        if (event.getBody().getStatus() == APPROVED) {
            websocketService.notifyUser(event.getBody().getContentId());
        }
    });

🚨 Error Handling

MongoDB Retry Logic:

@Retryable(value = MongoException.class, maxAttempts = 3)
public void saveMessage(ChatMessage message) {
    mongoTemplate.save(message);
}

Dead Letter Queue:

@KafkaListener(topics = "moderation-dlq")
public void handleFailedContent(ModerationRequest request) {
    log.error("Failed to moderate: {}", request);
    humanReviewQueue.add(request);
}

📈 Monitoring

Key Metrics:

  • chat.messages.sent (Counter)
  • feed.recommendation.latency (Timer)
  • moderation.decision.time (Gauge)

Sample Dashboard:

# Prometheus config
- job_name: 'social-commerce'
  metrics_path: '/actuator/prometheus'

📜 License

Apache 2.0


📮 Support

For issues, contact:


▶️ Quick Start:

git clone https://github.com/your-repo/social-commerce-mongodb.git
cd social-commerce-mongodb
mvn test  # Verify setup
mvn spring-boot:run -pl product-chat