5. Social Commerce Service‐ MongoDB Edition‐ Step‐by‐Step Guide - Wiz-DevTech/prettygirllz GitHub Wiki

Step-by-Step Guide: Implementing the Social Commerce Service with MongoDB

1. Environment Setup

Prerequisites Installation

# Install Java 17+
sudo apt install openjdk-17-jdk  # Linux
brew install openjdk@17          # macOS

# Install MongoDB 6.0+
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 656408E390CFB1F5
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -sc)/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt update && sudo apt install -y mongodb-org

# Install Maven
sudo apt install maven

Verify Installations

java -version       # Should show Java 17+
mongod --version   # Should show MongoDB 6.x
mvn -v             # Should show Maven 3.9+

2. Project Initialization

Create Maven Project Structure

mvn archetype:generate -DgroupId=com.socialcommerce -DartifactId=social-commerce-service -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
cd social-commerce-service

Add Spring Boot Parent POM

<!-- pom.xml -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.5</version>
</parent>

3. MongoDB Configuration

Add Dependencies

<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
</dependencies>

Configure MongoDB Connection

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

4. Implement Product Chat

Create Chat Message Document

// src/main/java/com/socialcommerce/chat/model/ChatMessage.java
@Document(collection = "chat_messages")
@Data
public class ChatMessage {
    @Id
    private String id;
    private String productId;
    private String senderId;
    private String content;
    private Instant timestamp = Instant.now();
}

Set Up WebSocket

// src/main/java/com/socialcommerce/chat/config/WebSocketConfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/live-chat").withSockJS();
    }
    
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

5. Implement Community Feed

Create Feed Item Document

// src/main/java/com/socialcommerce/feed/model/FeedItem.java
@Document(collection = "feed_items")
@Data
@CompoundIndex(def = "{'userId': 1, 'score': -1}")
public class FeedItem {
    @Id
    private String id;
    private String userId;
    private String contentUrl;
    private double score;
}

Generate Recommendations

// src/main/java/com/socialcommerce/feed/service/FeedService.java
@Service
@RequiredArgsConstructor
public class FeedService {
    private final MongoTemplate mongoTemplate;
    
    public List<FeedItem> getFeedForUser(String userId) {
        Query query = Query.query(Criteria.where("userId").is(userId))
            .with(Sort.by(Sort.Direction.DESC, "score"))
            .limit(20);
        return mongoTemplate.find(query, FeedItem.class);
    }
}

6. Content Moderation Setup

Moderation Decision Document

// src/main/java/com/socialcommerce/moderation/model/ModerationDecision.java
@Document(collection = "moderation_decisions")
@Data
public class ModerationDecision {
    @Id
    private String id;
    private String contentId;
    private ModerationStatus status;
    private String reason;
}

AI Moderation Service

@Service
public class AIModerationService {
    public ModerationDecision moderateContent(String content) {
        // Implement your AI logic here
        return new ModerationDecision(content, 
            containsBadWords(content) ? REJECTED : APPROVED);
    }
}

7. Testing

Unit Tests

// src/test/java/com/socialcommerce/chat/ChatServiceTest.java
@SpringBootTest
class ChatServiceTest {
    @Autowired
    private ChatRepository chatRepo;
    
    @Test
    void testSaveMessage() {
        ChatMessage msg = new ChatMessage("prod1", "user1", "Hello!");
        chatRepo.save(msg);
        assertNotNull(msg.getId());
    }
}

Integration Test with Test Containers

// src/test/java/com/socialcommerce/feed/FeedIT.java
@Testcontainers
@SpringBootTest
class FeedIT {
    @Container
    static MongoDBContainer mongo = new MongoDBContainer("mongo:6.0");
    
    @DynamicPropertySource
    static void setProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.data.mongodb.uri", mongo::getReplicaSetUrl);
    }
    
    @Test
    void testFeedGeneration() {
        // Test with real MongoDB
    }
}

8. Deployment

Build and Run

mvn clean package
java -jar target/social-commerce-service-0.0.1-SNAPSHOT.jar

Docker Deployment

# Dockerfile
FROM eclipse-temurin:17-jdk
COPY target/social-commerce-service-*.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
docker build -t social-commerce-service .
docker run -p 8080:8080 -e SPRING_DATA_MONGODB_URI=mongodb://host.docker.internal:27017 social-commerce-service

9. Monitoring (Optional)

Add Actuator

<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

View Metrics

curl http://localhost:8080/actuator/metrics

Troubleshooting

Issue Solution
MongoDB connection failed Verify mongod is running and URI is correct
WebSocket not connecting Check browser console for SockJS errors
Slow feed queries Add proper MongoDB indexes

▶️ Next Steps:

  1. Implement user authentication
  2. Add rate limiting for chat
  3. Set up MongoDB sharding for scalability

Need help? Contact [email protected]

⚠️ **GitHub.com Fallback** ⚠️