QUICK START BACKEND API

Documentation for Plans

๐Ÿš€ Quick Start: Backend API Integration

Date: October 31, 2025
Purpose: Get started with the new backend API integration in 5 minutes


โšก Quick Setup

1๏ธโƒฃ Start Backend API

# Terminal 1 - Start backend
cd /Users/fguijarro/developer/repos/editor
nx serve backend-api

โœ… Backend running on: http://localhost:3000

2๏ธโƒฃ Start Frontend

# Terminal 2 - Start frontend (already running)
# Your serve process should already be running on port 5200
# If not:
nx serve gograb-space --port 5200

โœ… Frontend running on: http://localhost:5200


๐Ÿงช Test the Integration

Option 1: Browser Console

Open http://localhost:5200 and run in console:

// Test Space API connection
const spaceApi = inject(SpaceApiService);
await spaceApi.checkConnection();  // Should return true

// Get current user's space
spaceApi.getCurrentUserSpace().subscribe(
  space => console.log('โœ… Space loaded:', space),
  error => console.error('โŒ Error:', error)
);

Option 2: Component Code

Create a test component:

import { Component, inject, OnInit } from '@angular/core';
import { SpaceService } from '@libs-foundational/core-angular';

@Component({
  selector: 'app-test',
  template: `
    <div>
      <h2>Space API Test</h2>
      @if (space()) {
        <div>
          <p><strong>Space Name:</strong> {{ space()!.name }}</p>
          <p><strong>Space Slug:</strong> {{ space()!.spaceSlug }}</p>
          <p><strong>Owner ID:</strong> {{ space()!.ownerId }}</p>
        </div>
      } @else {
        <p>Loading...</p>
      }
    </div>
  `
})
export class TestComponent implements OnInit {
  private readonly spaceService = inject(SpaceService);
  readonly space = this.spaceService.currentSpace;

  async ngOnInit() {
    try {
      await this.spaceService.initializeSpace('user_123');
      console.log('โœ… Space initialized');
    } catch (error) {
      console.error('โŒ Failed to initialize:', error);
    }
  }
}

๐Ÿ” Verify Backend API

Test Health Endpoint

curl http://localhost:3000/api/health

Expected response:

{
  "status": "ok",
  "timestamp": "2025-10-31T...",
  "uptime": 123.45
}

Test Authentication

# Login
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "password123"
  }'

Expected response:

{
  "accessToken": "eyJhbGciOiJIUzI1NiIs...",
  "user": {
    "id": "user_123",
    "email": "[email protected]",
    "name": "Test User"
  }
}

Test Space Initialization

# Get your JWT token from login response
TOKEN="your-jwt-token-here"

# Initialize space
curl -X POST http://localhost:3000/api/spaces/initialize \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "spaceSlug": "my-awesome-space"
  }'

Expected response:

{
  "id": "space_user_123",
  "name": "My Awesome Space",
  "spaceSlug": "my-awesome-space",
  "ownerId": "user_123",
  "universeIds": [],
  "settings": {
    "defaultTheme": "dark",
    "aiProvider": "anthropic",
    "storageLocation": "local",
    "autoSave": true,
    "autoBackup": false
  },
  "createdAt": "2025-10-31T...",
  "updatedAt": "2025-10-31T..."
}

๐Ÿ› Troubleshooting

Backend Not Starting?

Check MongoDB connection:

# Verify MONGODB_CONNECTION_STRING in .env
cat apis/backend-api/.env | grep MONGODB

Expected:

MONGODB_CONNECTION_STRING=mongodb+srv://...
MONGODB_DATABASE=gograb-api

Authentication Failing?

Check JWT secret:

# Verify JWT_SECRET in .env
cat apis/backend-api/.env | grep JWT

Expected:

JWT_SECRET=your-secret-key
JWT_EXPIRATION=7d

Frontend Not Connecting to API?

Check environment config:

// apps/gograb-space/src/environments/environment.ts
export const environment = {
  production: false,
  useMockApi: false,  // โœ… Should be false
  backendApiUrl: BACKEND_URLS.railway,  // or BACKEND_URLS.local
  // ...
};

For local backend:

backendApiUrl: BACKEND_URLS.local,  // http://localhost:3000

CORS Errors?

Add your frontend URL to backend CORS:

// apis/backend-api/src/main.ts (already configured)
const defaultOrigins = [
  'http://localhost:5701',  // gograb-space (primary)
  'http://localhost:5200',  // unified-dashboard โœ…
  'http://localhost:4200',  // alternative dev port
  'http://localhost:5300',  // space-admin
];

๐Ÿ“Š What to Expect

โœ… Success Indicators

  1. Backend Console:

    [Nest] INFO  [SpacesService] Initializing space for user: user_123
    [Nest] INFO  [SpacesService] โœ… Space initialized: space_user_123
    
  2. Frontend Console:

    [SpaceService] ๐Ÿš€ Initializing space (API-first mode)
    [SpaceApiService] Getting current user space...
    [SpaceApiService] โœ… Space loaded: My Space
    [SpaceService] โœ… Space initialized from API: space_user_123
    
  3. Browser DevTools โ†’ Network:

    • GET /api/spaces/me โ†’ Status 200
    • POST /api/spaces/initialize โ†’ Status 200
    • Headers: Authorization: Bearer ... โœ…
  4. MongoDB:

    • Database: gograb-api
    • Collection: spaces
    • Document with your space data โœ…

โŒ Common Issues

Issue Cause Solution
401 Unauthorized JWT token missing/invalid Login again via /api/auth/login
404 Not Found Backend not running Start backend: nx serve backend-api
Cannot connect to MongoDB MongoDB credentials wrong Check .env file
CORS error Frontend URL not allowed Add to ALLOWED_ORIGINS in .env
Space already exists Space created previously Use GET /api/spaces/me instead

๐ŸŽฏ Next Steps

Once you confirm everything works:

  1. Test Offline Mode:

    • Stop backend
    • Reload frontend
    • Should load space from local cache โœ…
  2. Test Space Updates:

    await spaceService.updateSpace({
      name: 'My New Space Name',
      settings: { defaultTheme: 'light' }
    });
    
  3. Test Slug Generation:

    • Create space with name "Amazing Platform"
    • Verify slug is "amazing-platform" (not from URL)
  4. Test Multiple Users:

    • Register/login as different users
    • Each should have their own space

๐Ÿ“š Documentation

For more details, see:


๐Ÿšจ Important

Before deploying to production:

  1. โœ… Change JWT secret in .env
  2. โœ… Update MongoDB connection string
  3. โœ… Set proper CORS origins
  4. โœ… Enable HTTPS
  5. โœ… Add rate limiting
  6. โœ… Set up error monitoring

Status: โœ… READY TO TEST

You're all set! Start both servers and test the integration. ๐Ÿš€