Social Commerce Service ‐ Integration Guide - Wiz-DevTech/prettygirllz GitHub Wiki

Social Commerce Service - Integration Guide

Overview

This document outlines the integration requirements and API design for connecting the Social Commerce Service with frontend applications.

API Design Principles

URL Structure

/api/v1/{resource}
/api/v1/{resource}/{id}
/api/v1/{resource}/{id}/{sub-resource}

HTTP Methods

  • GET - Retrieve resources
  • POST - Create new resources
  • PUT - Update entire resources
  • PATCH - Partial resource updates
  • DELETE - Remove resources

Response Format

All APIs return JSON with consistent structure:

{
  "data": {},
  "meta": {
    "timestamp": "2024-01-01T00:00:00Z",
    "version": "1.0"
  },
  "errors": []
}

Authentication & Authorization

JWT Authentication

  • Type: Bearer Token
  • Header: Authorization: Bearer <token>
  • Expiration: 24 hours (86400 seconds)
  • Refresh: Manual refresh required

Token Endpoint

POST /api/v1/auth/login
Content-Type: application/json

{
  "username": "[email protected]",
  "password": "password"
}

Response:

{
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expiresIn": 86400,
    "tokenType": "Bearer"
  }
}

Protected Endpoints

All endpoints except /auth/* and /public/* require authentication.

Core API Endpoints

Users API

Get User Profile

GET /api/v1/users/profile
Authorization: Bearer <token>

Response:

{
  "data": {
    "id": 1,
    "username": "test_user1",
    "email": "[email protected]",
    "enabled": true,
    "createdAt": "2024-01-01T00:00:00Z",
    "updatedAt": "2024-01-01T00:00:00Z"
  }
}

Chat Messages API

Send Message

POST /api/v1/chat/messages
Authorization: Bearer <token>
Content-Type: application/json

{
  "recipientId": 101,
  "content": "Is this product available in blue?",
  "productId": 1001,
  "messageType": "TEXT"
}

Response:

{
  "data": {
    "id": 1,
    "senderId": 100,
    "recipientId": 101,
    "content": "Is this product available in blue?",
    "productId": 1001,
    "status": "SENT",
    "messageType": "TEXT",
    "createdAt": "2024-01-01T00:00:00Z"
  }
}

Get Conversation

GET /api/v1/chat/conversations/{conversationId}?page=0&size=20
Authorization: Bearer <token>

Response:

{
  "data": {
    "messages": [
      {
        "id": 1,
        "senderId": 100,
        "recipientId": 101,
        "content": "Is this product available in blue?",
        "productId": 1001,
        "status": "DELIVERED",
        "createdAt": "2024-01-01T00:00:00Z"
      }
    ],
    "pagination": {
      "page": 0,
      "size": 20,
      "totalElements": 1,
      "totalPages": 1
    }
  }
}

Feed API

Get Feed Items

GET /api/v1/feed?page=0&size=10&type=RECOMMENDATION
Authorization: Bearer <token>

Response:

{
  "data": {
    "items": [
      {
        "id": 1,
        "userId": 100,
        "content": "Check out this amazing product!",
        "type": "RECOMMENDATION",
        "productId": 1001,
        "likesCount": 25,
        "commentsCount": 5,
        "sharesCount": 2,
        "engagementScore": 8.5,
        "isFeatured": false,
        "visibility": "PUBLIC",
        "createdAt": "2024-01-01T00:00:00Z"
      }
    ],
    "pagination": {
      "page": 0,
      "size": 10,
      "totalElements": 1,
      "totalPages": 1
    }
  }
}

Create Feed Item

POST /api/v1/feed/items
Authorization: Bearer <token>
Content-Type: application/json

{
  "content": "Check out this amazing product!",
  "type": "RECOMMENDATION",
  "productId": 1001,
  "tags": ["trending", "electronics"],
  "visibility": "PUBLIC"
}

Like Feed Item

POST /api/v1/feed/items/{id}/like
Authorization: Bearer <token>

Comment on Feed Item

POST /api/v1/feed/items/{id}/comments
Authorization: Bearer <token>
Content-Type: application/json

{
  "content": "Great recommendation!"
}

Moderation API

Report Content

POST /api/v1/moderation/report
Authorization: Bearer <token>
Content-Type: application/json

{
  "contentId": 1,
  "contentType": "FEED_ITEM",
  "reason": "Inappropriate content"
}

Real-time Communication

WebSocket Endpoints

Chat WebSocket

const socket = new WebSocket('ws://localhost:8080/ws/chat');
socket.onopen = function(event) {
  // Send authentication
  socket.send(JSON.stringify({
    type: 'AUTH',
    token: 'Bearer <jwt-token>'
  }));
};

// Receive messages
socket.onmessage = function(event) {
  const message = JSON.parse(event.data);
  console.log('New message:', message);
};

// Send message
socket.send(JSON.stringify({
  type: 'MESSAGE',
  recipientId: 101,
  content: 'Hello!',
  productId: 1001
}));

Kafka Integration (Optional for Advanced Features)

The service uses Kafka for asynchronous processing:

  • Chat messages: Real-time message delivery
  • Feed updates: Notification processing
  • Moderation events: Content review workflows

Error Handling

Standard Error Response

{
  "errors": [
    {
      "code": "VALIDATION_ERROR",
      "message": "Content is required",
      "field": "content",
      "timestamp": "2024-01-01T00:00:00Z"
    }
  ]
}

HTTP Status Codes

  • 200 - Success
  • 201 - Created
  • 400 - Bad Request
  • 401 - Unauthorized
  • 403 - Forbidden
  • 404 - Not Found
  • 422 - Validation Error
  • 500 - Internal Server Error

Data Models

User Model

{
  "id": "integer",
  "username": "string",
  "email": "string",
  "enabled": "boolean",
  "createdAt": "datetime",
  "updatedAt": "datetime"
}

Chat Message Model

{
  "id": "integer",
  "senderId": "integer",
  "recipientId": "integer",
  "content": "string",
  "productId": "integer (optional)",
  "conversationId": "integer",
  "status": "enum (SENT, DELIVERED, READ)",
  "messageType": "enum (TEXT, IMAGE, PRODUCT_LINK)",
  "attachmentUrl": "string (optional)",
  "createdAt": "datetime",
  "updatedAt": "datetime",
  "readAt": "datetime (optional)"
}

Feed Item Model

{
  "id": "integer",
  "userId": "integer",
  "content": "string",
  "type": "enum (RECOMMENDATION, REVIEW, PRODUCT_REVIEW)",
  "productId": "integer (optional)",
  "imageUrl": "string (optional)",
  "likesCount": "integer",
  "commentsCount": "integer",
  "sharesCount": "integer",
  "engagementScore": "double",
  "isFeatured": "boolean",
  "visibility": "enum (PUBLIC, PRIVATE, FOLLOWERS)",
  "tags": ["string"],
  "createdAt": "datetime",
  "updatedAt": "datetime"
}

File Upload

Upload Endpoint

POST /api/v1/upload
Authorization: Bearer <token>
Content-Type: multipart/form-data

file=<binary-data>

Constraints:

  • Max file size: 10MB
  • Max request size: 10MB
  • Supported formats: jpg, png, gif, mp4 (configurable)

Rate Limiting

Default Limits

  • Authentication attempts: 5 per minute per IP
  • API calls: 100 per minute per user
  • File uploads: 10 per minute per user

CORS Configuration

For frontend integration, configure CORS:

@CrossOrigin(origins = {"http://localhost:3000", "https://your-frontend-domain.com"})

SDK/Client Library

JavaScript Example

class SocialCommerceClient {
  constructor(baseUrl, token) {
    this.baseUrl = baseUrl;
    this.token = token;
  }

  async request(path, options = {}) {
    const url = `${this.baseUrl}${path}`;
    const config = {
      ...options,
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Content-Type': 'application/json',
        ...options.headers
      }
    };
    
    const response = await fetch(url, config);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  }

  async getFeed(page = 0, size = 10) {
    return this.request(`/api/v1/feed?page=${page}&size=${size}`);
  }

  async sendMessage(recipientId, content, productId) {
    return this.request('/api/v1/chat/messages', {
      method: 'POST',
      body: JSON.stringify({ recipientId, content, productId })
    });
  }
}

Performance Considerations

Caching Strategy

  • Application uses Caffeine cache with 10-minute expiration
  • Implement Redis for distributed caching if scaling horizontally
  • Use HTTP caching headers for static content

Pagination

All list endpoints support pagination:

GET /api/v1/feed?page=0&size=20&sort=createdAt,desc

Compression

  • Response compression enabled for responses > 1KB
  • Supported MIME types: JSON, XML, HTML, plain text

Testing

Test Endpoints

In test environment, additional endpoints are available:

GET /api/v1/test/health
POST /api/v1/test/reset-data

Mock Data

Use provided JSON files for testing:

  • chat-messages.json
  • feed-items.json

Security Best Practices

  1. Always validate JWT tokens
  2. Implement rate limiting
  3. Sanitize user inputs
  4. Use HTTPS in production
  5. Implement proper CORS policies
  6. Log security events
  7. Regularly rotate JWT secrets

Integration Checklist

  • Configure authentication endpoint
  • Implement JWT token storage
  • Set up automatic token refresh
  • Configure CORS for your domain
  • Implement error handling for all API calls
  • Set up WebSocket connection for real-time features
  • Configure file upload component
  • Implement pagination for list views
  • Set up proper loading states
  • Add retry logic for failed requests
⚠️ **GitHub.com Fallback** ⚠️