npm package: @rodggall/multi-api
Description: A TypeScript API handler library compatible with Vue and React
Latest version: 0.0.1

# multi-api

A TypeScript API handler library with Axios instances, compatible with Vue and React.

## Installation

```bash
npm install multi-api
```

## Features

- 🚀 Factory pattern for creating multiple API instances
- 🎯 Per-instance configuration (baseURL, headers, interceptors)
- 💾 Simple caching with staleTime and cacheTime
- ⚛️ React hooks (useQuery, useMutation)
- 💚 Vue composables (useQuery, useMutation)
- 🔥 TypeScript support out of the box

## Usage

### Basic Usage

```typescript
import { createApi } from 'multi-api';

// Create API instance with configuration
const api = createApi('myApi', {
  baseURL: 'https://api.example.com',
  headers: {
    'Content-Type': 'application/json',
  },
  interceptors: {
    request: {
      onFulfilled: (config) => {
        console.log('Request:', config);
        return config;
      },
    },
    response: {
      onFulfilled: (response) => {
        console.log('Response:', response);
        return response;
      },
      onRejected: (error) => {
        console.error('Error:', error);
        return Promise.reject(error);
      },
    },
  },
});

// Make requests
const response = await api.get('/users');
console.log(response.data);

const user = await api.post('/users', { name: 'John', email: 'john@example.com' });
console.log(user.data);
```

### React Integration

```tsx
import { createApi, useQuery, useMutation } from 'multi-api';

// Create API instance
const api = createApi('usersApi', {
  baseURL: 'https://api.example.com',
});

function UsersList() {
  const { data, isLoading, error } = useQuery(
    api,
    { url: '/users', method: 'GET' },
    {
      staleTime: 5 * 60 * 1000, // 5 minutes
      cacheTime: 10 * 60 * 1000, // 10 minutes
      refetchOnWindowFocus: true,
    }
  );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <ul>
      {data?.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

function CreateUser() {
  const { mutate, isLoading, error } = useMutation(
    api,
    {
      url: '/users',
      method: 'POST',
      data: { name: 'John', email: 'john@example.com' },
    },
    {
      onSuccess: (data) => {
        console.log('User created:', data);
      },
      onError: (error) => {
        console.error('Error creating user:', error);
      },
    }
  );

  return (
    <button onClick={() => mutate()} disabled={isLoading}>
      Create User
    </button>
  );
}
```

### Vue Integration

```vue
<script setup lang="ts">
import { createApi, useQuery, useMutation } from 'multi-api';

// Create API instance
const api = createApi('usersApi', {
  baseURL: 'https://api.example.com',
});

// Query users
const { data, isLoading, error } = useQuery(
  api,
  { url: '/users', method: 'GET' },
  {
    staleTime: 5 * 60 * 1000,
    cacheTime: 10 * 60 * 1000,
  }
);

// Create user mutation
const { mutate: createUser, isLoading: isCreating } = useMutation(
  api,
  {
    url: '/users',
    method: 'POST',
  }
);

const handleCreateUser = () => {
  createUser({ name: 'John', email: 'john@example.com' });
};
</script>

<template>
  <div v-if="isLoading">Loading...</div>
  <div v-else-if="error">Error: {{ error.message }}</div>
  <ul v-else>
    <li v-for="user in data" :key="user.id">{{ user.name }}</li>
  </ul>
  
  <button @click="handleCreateUser" :disabled="isCreating">
    Create User
  </button>
</template>
```

### Shared API Instances

```typescript
import { createApi, getApi } from 'multi-api';

// Create shared instances
createApi('usersApi', { baseURL: 'https://api.example.com/users' });
createApi('postsApi', { baseURL: 'https://api.example.com/posts' });

// Retrieve instances anywhere in your app
const usersApi = getApi('usersApi');
const postsApi = getApi('postsApi');

// Use them
const users = await usersApi?.get('/');
const posts = await postsApi?.get('/');
```

### Cache Management

```typescript
import { queryCache } from 'multi-api';

// Clear all cache
queryCache.clear();

// Clear specific cache entry
queryCache.delete('/users');

// Check if data is stale
const isStale = queryCache.isStale('/users');
```

## API Reference

### createApi(name, config)

Creates a new API instance with the specified configuration.

- `name` (string): Unique name for the API instance
- `config` (ApiConfig): Configuration object
  - `baseURL` (string): Base URL for all requests
  - `timeout` (number): Request timeout in milliseconds
  - `headers` (object): Default headers for all requests
  - `interceptors` (object): Axios interceptors

Returns: `ApiInstance`

### useQuery(apiInstance, config, options)

React hook for fetching data with caching.

- `apiInstance` (ApiInstance): API instance to use
- `config` (Partial<RequestConfig>): Request configuration
- `options` (UseQueryOptions): Query options
  - `enabled` (boolean): Whether the query is enabled
  - `refetchOnWindowFocus` (boolean): Refetch on window focus
  - `refetchInterval` (number): Auto-refetch interval in milliseconds
  - `staleTime` (number): Time in milliseconds before data is stale
  - `cacheTime` (number): Time in milliseconds before cache is garbage collected
  - `onSuccess` (function): Callback on successful fetch
  - `onError` (function): Callback on error

Returns: `QueryState`

### useMutation(apiInstance, config, options)

React hook for performing mutations (POST, PUT, PATCH, DELETE).

- `apiInstance` (ApiInstance): API instance to use
- `config` (RequestConfig): Request configuration
- `options` (UseMutationOptions): Mutation options
  - `onSuccess` (function): Callback on successful mutation
  - `onError` (function): Callback on error
  - `onSettled` (function): Callback after mutation completes

Returns: `MutationState`

### ApiInstance

- `get<T>(url, config?)`: GET request
- `post<T, D>(url, data?, config?)`: POST request
- `put<T, D>(url, data?, config?)`: PUT request
- `patch<T, D>(url, data?, config?)`: PATCH request
- `delete<T>(url, config?)`: DELETE request
- `request<T>(config)`: Generic request

## Development

```bash
npm install
npm run dev    # Watch mode
npm run build  # Build the library
npm run test   # Run tests
npm run lint   # Lint code
npm run typecheck  # Type check
```

## License

MIT