npm package: @gzl10/nexus-client
Description: HTTP client for Nexus Backend with auth, correlation-id, and Socket.IO support
Author: Gonzalo Díez
Latest version: 0.21.0

# @gzl10/nexus-client

[![npm version](https://img.shields.io/npm/v/@gzl10/nexus-client.svg)](https://www.npmjs.com/package/@gzl10/nexus-client)
[![npm downloads](https://img.shields.io/npm/dm/@gzl10/nexus-client.svg)](https://www.npmjs.com/package/@gzl10/nexus-client)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

> **Warning**: This project is currently in testing/experimental phase. Use at your own risk.

HTTP client for Nexus Backend with authentication, correlation-id tracking, and Socket.IO support. Built on Axios with automatic token refresh.

**Repository**: [https://gitlab.gzl10.com/oss/nexus](https://gitlab.gzl10.com/oss/nexus)

## Installation

```bash
pnpm add @gzl10/nexus-client
```

## Usage

### Singleton Pattern (Recommended)

```typescript
import { configureClient, getClient } from '@gzl10/nexus-client'

// Configure once at app startup
await configureClient({
  baseURL: 'http://localhost:3000/api/v1',
  onUnauthorized: () => window.location.href = '/login'
})

// Use anywhere in your app
const client = getClient()

// Authentication
await client.auth.login('user@example.com', 'password')
const { user } = await client.auth.me()
await client.auth.logout()

// Users
const users = await client.users.findAll()
const user = await client.users.findById('uuid')

// Roles
const roles = await client.users.roles.findAll()

// Storage
const file = await client.storage.upload(fileInput)
const url = client.storage.getUrl(file.id)

// System
const modules = await client.system.getModules()
const plugins = await client.system.getPlugins()

// Custom HTTP requests
const data = await client.http.get('/custom-endpoint')
await client.http.post('/custom-endpoint', { foo: 'bar' })

// Socket.IO (real-time)
client.socket.on('notification', (payload) => console.log(payload))
```

### Factory Pattern (Advanced)

For multiple instances or testing:

```typescript
import { createNexusClient } from '@gzl10/nexus-client'

const client = await createNexusClient({
  baseURL: 'http://localhost:3000/api/v1'
})
```

## Features

| Feature | Description |
| ------- | ----------- |
| Auto Token Refresh | Automatic 401 retry with token refresh |
| Correlation ID | Request tracing with X-Correlation-ID |
| Device Fingerprint | Browser fingerprinting for device tracking |
| Type-safe | Full TypeScript support |
| Socket.IO | Real-time event subscriptions |
| CASL Integration | Client-side ability checking |

## API Reference

### Auth API

| Method | Description |
| ------ | ----------- |
| `login(email, password, options?)` | Login with credentials |
| `register(input)` | Register new user |
| `logout()` | Logout current device |
| `logoutAll()` | Logout all devices |
| `me()` | Get current user |
| `refresh()` | Refresh access token |
| `forgotPassword(email)` | Request password reset OTP |
| `resetPassword(email, otp, newPassword)` | Reset password with OTP |

### OTP Challenge Handling

When login fails due to OTP requirement (after multiple failed attempts), the error response includes `otpSent: true`:

```typescript
try {
  await client.auth.login(email, password)
} catch (error) {
  if (error.response?.status === 403 && error.response?.data?.otpSent) {
    // Show OTP input, then retry with OTP
    await client.auth.login(email, password, { otp: '123456' })
  }
}
```

### Users API

| Method | Description |
| ------ | ----------- |
| `findAll(query?)` | List users with pagination |
| `findOne(id)` | Get user by ID |
| `create(input)` | Create user |
| `update(id, input)` | Update user |
| `delete(id)` | Delete user |
| `roles.*` | Roles sub-API |

### Storage API

| Method | Description |
| ------ | ----------- |
| `upload(file, options?)` | Upload file |
| `delete(path)` | Delete file |
| `getUrl(path)` | Get file URL |

## Configuration

| Option | Description | Default |
| ------ | ----------- | ------- |
| `baseURL` | API base URL | Required |
| `storage` | Token storage | `localStorage` |
| `onUnauthorized` | 401 callback | - |

## Development

```bash
pnpm build      # Build library
pnpm dev        # Build with watch
pnpm typecheck  # Type check
pnpm lint       # Linting
pnpm test       # Run tests
```

## Support

<a href="https://www.buymeacoffee.com/gzl10g" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>

## License

MIT