npm package: @nishanthmariyada/kaaty-api-client
Description: Type-safe HTTP client for KAATY backend API with automatic auth token management
Author: KAATY Team
Latest version: 1.0.6

# @kaaty/api-client

Type-safe HTTP client for KAATY backend API with automatic auth token management.

## Installation

```bash
npm install @kaaty/api-client @kaaty/shared
# or
yarn add @kaaty/api-client @kaaty/shared
# or
pnpm add @kaaty/api-client @kaaty/shared
```

## Quick Start

```typescript
import { KaatyAPI } from '@kaaty/api-client';

const api = new KaatyAPI({
  baseUrl: 'https://your-project.supabase.co',
  getAuthToken: async () => {
    // Return user's JWT token
    const session = await getSession(); // Your auth implementation
    return session?.access_token || null;
  },
  onError: (error) => {
    console.error('[API Error]', error.message);
  }
});

// Use the API
const cart = await api.cart.get(userId);
const menu = await api.menu.getByCollege(collegeId, categoryId);
const order = await api.orders.create(orderData);
```

## Features

- **Type-Safe**: Full TypeScript support with shared type definitions
- **Auto-Retry**: Automatic retry logic with exponential backoff
- **Error Parsing**: Structured error handling with detailed messages
- **Auth Management**: Automatic JWT token injection
- **Zero Config**: Works out-of-the-box with sensible defaults

## API Reference

### Cart Operations

```typescript
// Get user's cart
const cart = await api.cart.get(userId);

// Add item to cart
await api.cart.add(userId, {
  menu_item_id: 'item-123',
  quantity: 2,
  special_instructions: 'Extra spicy'
});

// Update cart item
await api.cart.update(userId, cartItemId, { quantity: 3 });

// Remove item
await api.cart.remove(userId, cartItemId);

// Clear entire cart
await api.cart.clear(userId);
```

### Favorites Management

```typescript
// Get user's favorites
const favorites = await api.favorites.get(userId);

// Add to favorites
await api.favorites.add(userId, menuItemId);

// Remove from favorites
await api.favorites.remove(userId, menuItemId);

// Check if item is favorited
const isFavorite = await api.favorites.check(userId, menuItemId);
```

### Menu Data

```typescript
// Get menu items by college and category
const items = await api.menu.getByCollege(collegeId, categoryId);

// Get single menu item
const item = await api.menu.getItem(itemId);

// Get all categories
const categories = await api.menu.getCategories(collegeId);
```

### Orders

```typescript
// Create new order
const order = await api.orders.create({
  user_id: userId,
  college_id: collegeId,
  items: [
    { menu_item_id: 'item-1', quantity: 2, price: 150 }
  ],
  delivery_location: 'Room 301',
  total_amount: 300
});

// Get order details
const order = await api.orders.get(orderId);

// Get user's orders
const orders = await api.orders.getUserOrders(userId);
```

### Payment

```typescript
// Initialize payment
const payment = await api.payment.initialize({
  order_id: orderId,
  amount: 300,
  user_id: userId
});

// Verify payment
const result = await api.payment.verify(paymentId, transactionId);
```

### Inventory (Staff Only)

```typescript
// Get inventory status
const status = await api.inventory.getStatus(menuItemId);

// Update stock
await api.inventory.updateStock(menuItemId, newQuantity);

// Reserve items
await api.inventory.reserve(orderId, items);
```

### Authentication

```typescript
// Send OTP
await api.auth.sendOTP(email);

// Verify OTP
const session = await api.auth.verifyOTP(email, otp);

// Delete account
await api.auth.deleteAccount(userId);
```

## Configuration

### Constructor Options

```typescript
interface KaatyAPIConfig {
  baseUrl: string;              // Supabase project URL
  getAuthToken: () => Promise<string | null>;  // Token provider
  timeout?: number;              // Request timeout (default: 30000ms)
  maxRetries?: number;           // Max retry attempts (default: 3)
  onError?: (error: KaatyError) => void;  // Error handler
}
```

### Error Handling

The client throws structured errors:

```typescript
try {
  const cart = await api.cart.get(userId);
} catch (error) {
  if (error instanceof KaatyError) {
    console.error('Error code:', error.code);
    console.error('Message:', error.message);
    console.error('Status:', error.statusCode);
    console.error('Details:', error.details);
  }
}
```

### Retry Logic

Failed requests are automatically retried with exponential backoff:

- Initial delay: 1 second
- Max delay: 10 seconds
- Max retries: 3 (configurable)
- Retries only on network errors and 5xx responses

## Advanced Usage

### Custom Error Handler

```typescript
const api = new KaatyAPI({
  baseUrl: process.env.SUPABASE_URL,
  getAuthToken: async () => getToken(),
  onError: (error) => {
    // Send to error tracking service
    Sentry.captureException(error);
    
    // Show user-friendly message
    if (error.code === 'NETWORK_ERROR') {
      showToast('Network error. Please check your connection.');
    }
  }
});
```

### Custom Timeout

```typescript
const api = new KaatyAPI({
  baseUrl: process.env.SUPABASE_URL,
  getAuthToken: async () => getToken(),
  timeout: 15000,  // 15 seconds
  maxRetries: 5
});
```

### React Integration

```typescript
import { createContext, useContext } from 'react';
import { KaatyAPI } from '@kaaty/api-client';

const APIContext = createContext<KaatyAPI | null>(null);

export function APIProvider({ children }) {
  const api = new KaatyAPI({
    baseUrl: process.env.EXPO_PUBLIC_SUPABASE_URL,
    getAuthToken: async () => {
      const session = await supabase.auth.getSession();
      return session.data.session?.access_token || null;
    }
  });

  return <APIContext.Provider value={api}>{children}</APIContext.Provider>;
}

export function useAPI() {
  const api = useContext(APIContext);
  if (!api) throw new Error('useAPI must be used within APIProvider');
  return api;
}

// Usage in components
function CartScreen() {
  const api = useAPI();
  const [cart, setCart] = useState([]);

  useEffect(() => {
    api.cart.get(userId).then(setCart);
  }, []);
}
```

## TypeScript Support

Full type definitions are included. All request/response types are imported from @kaaty/shared:

```typescript
import type { Order, CartItem, MenuItem } from '@kaaty/shared';

// Types are automatically inferred
const cart: CartItem[] = await api.cart.get(userId);
const order: Order = await api.orders.create(data);
```

## Why This Package?

- **Separation of Concerns**: Backend logic stays in Edge Functions, not in frontend
- **Type Safety**: Shared types prevent frontend/backend drift
- **Error Handling**: Consistent error parsing across all endpoints
- **Security**: No direct database access from frontend
- **Maintainability**: Single place to update API logic

## Development

```bash
# Build the package
npm run build

# Watch mode
npm run dev

# Clean build artifacts
npm run clean
```

## Dependencies

- @kaaty/shared - Shared types and validation schemas

## License

MIT

## Repository

https://github.com/your-org/kaaty-api-client

## Issues

https://github.com/your-org/kaaty-api-client/issues

## Related Packages

- [@kaaty/shared](https://npmjs.com/package/@kaaty/shared) - Shared types and constants