npm package: @opens/accesshub-backend
Description: Simple SDK for resource verification with cache and fallback
Author: engenharia@opens.com.br
Latest version: 0.0.2

# AccessHub Backend SDK

A lightweight TypeScript SDK for company resource verification with memory caching and local fallback capabilities.

![version](https://img.shields.io/npm/v/@opens/accesshub-backend)
![license](https://img.shields.io/npm/l/@opens/accesshub-backend)
![build](https://img.shields.io/github/actions/workflow/status/opens/accesshub-backend/ci.yml?branch=main)
![typescript](https://img.shields.io/badge/TypeScript-5.2-blue)

## Features

- 🚀 Fast in-memory caching with TTL support
- 💾 Persistent file-based fallback storage
- 🔌 Pluggable cache providers (Redis, MongoDB, SQLite, etc.)
- 🔄 Automatic fallback to local storage when API is unavailable
- 🔒 Bearer token authentication support
- 📦 Zero runtime dependencies beyond Axios and Keyv

## Installation

```bash
npm install @opens/accesshub-backend
```

## Quick Start

```typescript
import { ResourceClient } from '@opens/accesshub-backend';

// Create client with minimal configuration
const client = new ResourceClient({
  accessHubURL: 'https://api.example.com',
  serviceToken: 'your-service-token',
});

// Get all company resources with automatic caching and fallback
const response = await client.getCompanyResources('company-id');
console.log(response.resources);

// Check if data came from cache or fallback storage
console.log(response._metadata.fromCache); // true/false
console.log(response._metadata.fromFallback); // true/false

// Get a specific resource by name
const resource = await client.getResource('company-id', 'resource1');
```

## Configuration

```typescript
import { ResourceClient } from '@opens/accesshub-backend';

const client = new ResourceClient({
  // Required: Base URL for the AccessHub API
  accessHubURL: 'https://api.example.com',

  // Optional: Authentication token for API requests
  serviceToken: 'your-service-token',

  // Optional: Cache TTL in milliseconds (default: 600000 = 10 minutes)
  cacheTTL: 300000,

  // Optional: Path for storing fallback JSON data
  dumpPath: './resource-data.json',

  // Optional: Custom cache implementation
  cache: customCacheImplementation,
});
```

## Caching Options

The SDK supports various caching backends through Keyv adapters:

### Default In-Memory Cache

```typescript
// Uses built-in in-memory cache (default)
const client = new ResourceClient({
  accessHubURL: 'https://api.example.com',
});
```

### Redis Cache

```typescript
import { ResourceClient, KeyvCacheProvider } from '@opens/accesshub-backend';
// First: npm install @keyv/redis

const client = new ResourceClient({
  accessHubURL: 'https://api.example.com',
  cache: new KeyvCacheProvider({
    store: 'redis://localhost:6379',
    namespace: 'accesshub',
    ttl: 3600000, // 1 hour
  }),
});
```

### Database Caching

```typescript
import { ResourceClient, KeyvCacheProvider } from '@opens/accesshub-backend';

// MongoDB (requires @keyv/mongo)
const mongoCache = new KeyvCacheProvider({
  store: 'mongodb://user:pass@localhost:27017/database',
  namespace: 'resources',
});

// SQLite (requires @keyv/sqlite)
const sqliteCache = new KeyvCacheProvider({
  store: 'sqlite://path/to/database.sqlite',
});

const client = new ResourceClient({
  accessHubURL: 'https://api.example.com',
  cache: mongoCache,
});
```

## Keyv Configuration Options

```typescript
import { KeyvCacheProvider } from '@opens/accesshub-backend';

const cache = new KeyvCacheProvider({
  // Connection string or store instance
  store: 'redis://localhost:6379',

  // Namespace to prevent key collisions (default: 'accesshub')
  namespace: 'my-app',

  // Default TTL in milliseconds
  ttl: 3600000, // 1 hour
});
```

Supported Keyv adapters (install separately):

- `@keyv/redis` - Redis adapter
- `@keyv/mongo` - MongoDB adapter
- `@keyv/sqlite` - SQLite adapter
- `@keyv/postgres` - PostgreSQL adapter
- `@keyv/mysql` - MySQL adapter

## Custom Cache Implementation

You can create your own cache provider by implementing the `CacheProvider` interface:

```typescript
import { ResourceClient, CacheProvider, ResourceResponse } from '@opens/accesshub-backend';

class CustomCache implements CacheProvider {
  async get(companyId: string): Promise<ResourceResponse | null> {
    // Retrieve data from your custom storage
    return null;
  }

  async set(companyId: string, data: ResourceResponse, ttl: number): Promise<void> {
    // Store data in your custom storage with TTL
  }

  async delete(companyId: string): Promise<void> {
    // Delete data for specific company
  }

  async clear(): Promise<void> {
    // Clear all cached data
  }
}

// Use your custom cache
const client = new ResourceClient({
  accessHubURL: 'https://api.example.com',
  cache: new CustomCache(),
});
```

## Fallback Storage

The SDK automatically stores resource data to a local JSON file for offline access when the API is unavailable:

```typescript
// Customize the fallback storage location
const client = new ResourceClient({
  accessHubURL: 'https://api.example.com',
  dumpPath: './custom/path/resources.json',
});
```

## Response Types

```typescript
// Full response structure
interface ResourceResponse {
  // Map of resource name to resource object
  resources: Record<string, Resource>;

  // Metadata about the response
  _metadata: {
    fromCache: boolean; // From cache?
    fromFallback: boolean; // From fallback storage?
    lastUpdated: string; // ISO timestamp
  };
}

// Individual resource structure
interface Resource {
  id: string;
  sequenceId: number;
  name: string;
  description: string;
  createdAt: string;
  updatedAt: string;
}
```