Skip to content

Latest commit

 

History

History
227 lines (173 loc) · 6.49 KB

File metadata and controls

227 lines (173 loc) · 6.49 KB

API Integration Guide

This document explains how the frontend is integrated with the NetWorkr backend API.

Configuration

Environment Variables

Create a .env file in the root directory with the following:

VITE_API_BASE_URL=http://localhost:8017/v1

Note: The backend API uses /v1 not /api/v1. Make sure your base URL doesn't include /api.

Default Configuration

If no environment variable is set, the API defaults to:

  • Development: http://localhost:8017/v1

API Client Architecture

File Structure

src/
├── config/
│   └── api.config.js          # API configuration (base URL, timeouts)
├── utils/
│   ├── apiClient.js           # HTTP client utilities (apiGet, apiPost, etc.)
│   └── auth.js                # Authentication utilities (token management)
└── apis/
    └── api.js                 # API function definitions

HTTP Client (src/utils/apiClient.js)

The API client provides standardized HTTP request methods:

  • apiGet(endpoint, options) - GET requests
  • apiPost(endpoint, body, options) - POST requests
  • apiPatch(endpoint, body, options) - PATCH requests
  • apiDelete(endpoint, options) - DELETE requests
  • apiUpload(endpoint, formData, options) - File uploads (multipart/form-data)

Features:

  • Automatic JWT token injection from localStorage
  • Automatic 401 handling (redirects to login)
  • Standardized error handling
  • Request timeout (30 seconds default)
  • JSON response parsing

Authentication

The API client automatically:

  1. Retrieves the JWT token from localStorage (via getAuthToken())
  2. Adds Authorization: Bearer <token> header to all requests
  3. Handles 401 responses by clearing auth and redirecting to login

API Functions (src/apis/api.js)

All API functions follow this pattern:

export const functionName = async (params) => {
  try {
    const response = await apiGet('/endpoint', options)
    
    if (response.success && response.data) {
      return {
        success: true,
        data: response.data,
        message: response.message
      }
    }
    
    return {
      success: false,
      message: response.message || 'Operation failed'
    }
  } catch (error) {
    return {
      success: false,
      message: error.message || 'Network error'
    }
  }
}

Important Notes

  1. Base URL: The backend uses /v1 not /api/v1. The base URL should be http://localhost:8017/v1.
  2. Error Handling: The API client now properly handles non-JSON responses (like HTML error pages) and provides better error messages.
  3. Response Format: The backend returns { success: true/false, message: "...", data: {...} } format.

Backend API Endpoints

The frontend is configured to work with the following backend endpoints (all under /v1):

Authentication

  • POST /v1/registrations - Register new user
  • POST /v1/verifications - Verify account with OTP
  • POST /v1/verifications/resend - Resend OTP
  • POST /v1/sessions - Login
  • DELETE /v1/sessions - Logout
  • PATCH /v1/sessions/password - Change password
  • POST /v1/password-resets - Request password reset
  • PATCH /v1/password-resets - Complete password reset

Users/Profile

  • GET /v1/users/me - Get current user
  • GET /v1/users/:id - Get user by ID
  • PATCH /v1/users/me - Update current user profile
  • POST /v1/users/me/avatar - Upload avatar
  • POST /v1/users/me/background - Upload background image
  • GET /v1/users/me/completeness - Get profile completeness
  • GET /v1/users - Search users (with query params)
  • POST /v1/users/me/experiences - Add work experience
  • POST /v1/users/me/skills - Add skill

Posts/Social

  • GET /v1/feeds/main - Get personalized feed
  • POST /v1/posts - Create post (supports multipart for media)
  • POST /v1/posts/:id/interactions - Interact with post (like/share)
  • POST /v1/posts/:id/comments - Add comment
  • GET /v1/posts/:id/comments - Get comments

Connections/Network

(Endpoints may vary based on backend implementation)

Jobs

(Endpoints may vary based on backend implementation)

Notifications

(Endpoints may vary based on backend implementation)

Messaging

(Endpoints may vary based on backend implementation)

Companies

(Endpoints may vary based on backend implementation)

Note: Refer to the API documentation at http://localhost:8017/api-docs/ for the complete list of available endpoints and their exact specifications.

Response Format

The backend returns responses in this format:

{
  success: true,  // or false
  data: { ... },  // Response data (optional)
  message: "...", // Human-readable message (optional)
  error: "..."    // Error message (optional, if success is false)
}

Error Handling

All API functions handle errors gracefully:

  1. Network Errors: Returns { success: false, message: 'Network error...' }
  2. HTTP Errors: Parses error message from response
  3. 401 Unauthorized: Automatically clears auth and redirects to login
  4. Timeouts: Returns timeout error message after 30 seconds

Usage Examples

Login

import { login } from '~/apis/api'
import { saveAuth } from '~/utils/auth'

const handleLogin = async (email, password) => {
  const response = await login(email, password)
  if (response.success) {
    saveAuth(response.token, response.user)
    // Redirect to dashboard
  } else {
    // Show error: response.message
  }
}

Create Post

import { createPost } from '~/apis/api'

const handleCreatePost = async (content, mediaFiles) => {
  const response = await createPost({
    content,
    media: mediaFiles, // File objects or URLs
    visibility: 'PUBLIC'
  })
  
  if (response.success) {
    // Post created: response.post
  }
}

Upload Avatar

import { uploadAvatar } from '~/apis/api'

const handleAvatarUpload = async (file) => {
  const response = await uploadAvatar(file)
  if (response.success) {
    // Avatar uploaded: response.avatarUrl
  }
}

Migration Notes

This API integration replaces the previous mock API functions. Key changes:

  1. Removed: Mock data functions (getUsersData, getPostsData, etc.)
  2. Removed: simulateApiDelay function
  3. Removed: localStorage-based mock data storage
  4. Added: Real HTTP requests using fetch API
  5. Added: JWT token authentication
  6. Added: Proper error handling and 401 redirects

All existing API function signatures remain the same for backward compatibility, but they now make real HTTP requests instead of returning mock data.