Facade & Services

PostgRESTClient

Facade Pattern di @pzeta/postgrest. Punto di ingresso principale — nasconde la complessità di HTTP client, autenticazione, cache e repository factory.

Cos'è

PostgRESTClient è il Facade della libreria. Una sola istanza orchestra tutti i componenti interni (HTTP client, auth strategy, cache strategy, repository factory) e ne gestisce il ciclo di vita.

import { PostgRESTClient } from '@pzeta/postgrest'

const client = new PostgRESTClient({ apiUrl: 'https://api.example.com' })
await client.init()
// ... usa il client
client.destroy()
init() è obbligatorio: prima della sua risoluzione qualsiasi chiamata pubblica lancia Error: PostgRESTClient non inizializzato. Chiama await client.init() prima di usarlo..

Contratto — PostgRESTClientConfig

interface PostgRESTClientConfig {
  /** URL base dell'API PostgREST (obbligatorio) */
  apiUrl: string

  /** Schema PostgreSQL (default: 'public') */
  schema?: string

  /** Tipo di HTTP client: FETCH o AXIOS (default: FETCH) */
  httpClientType?: HttpClientType

  /** Tipo di autenticazione: JWT, COOKIE, API_KEY o NONE (default: JWT) */
  authType?: AuthStrategyType

  /** Tipo di cache (default: INDEXEDDB con auto-fallback) */
  cacheType?: CacheStrategyType

  /** Cache TTL in millisecondi (default: 3600000 = 1 ora) */
  cacheTTL?: number

  /** Timeout richieste HTTP in millisecondi (default: 10000) */
  timeout?: number

  /** Strategia auth custom (ignora authType se fornito) */
  customAuthStrategy?: IAuthStrategy

  /** Strategia cache custom (ignora cacheType se fornito) */
  customCacheStrategy?: ICacheStrategy
}

Campi

CampoTipoRequiredDefaultDescrizione
apiUrlstringURL base dell'endpoint PostgREST
schemastring'public'Schema PostgreSQL (header Accept-Profile/Content-Profile)
httpClientTypeHttpClientTypeFETCHFETCH (nativo, zero deps) o AXIOS (peer dep)
authTypeAuthStrategyTypeJWTJWT, COOKIE, API_KEY, NONE
cacheTypeCacheStrategyTypeINDEXEDDBINDEXEDDB, LOCALSTORAGE, SESSIONSTORAGE, MEMORY, NONE
cacheTTLnumber3600000TTL cache in millisecondi (1h default)
timeoutnumber10000Timeout richiesta HTTP in millisecondi
customAuthStrategyIAuthStrategyOverride completo della strategia auth
customCacheStrategyICacheStrategyOverride completo della strategia cache

API

Lifecycle

MetodoFirmaDescrizione
init()() => Promise<void>Inizializza HTTP client, auth, cache, AuthService. Idempotente
destroy()() => voidLibera timer interni e pending requests. Reinizializzabile con init()

Repository factory

repository<T extends Record<string, unknown>, K>(
  path: string,
  keyName: keyof T,
  options?: {
    cacheTTL?: number
    useCache?: boolean
    isAuthRequired?: boolean
    schema?: string
  }
): EnhancedPostgRESTRepository<T, K>

Crea un repository type-safe per una specifica tabella/view. Le opzioni sovrascrivono per-repository la configurazione globale del client.

Autenticazione

MetodoFirmaDescrizione
login(credentials: UserCredentials) => Promise<AuthResponse | null>Login con email/password
logout() => Promise<void>Invalida refresh token sul server e pulisce storage locale
register(user: RegisterUser) => Promise<CustomResponse>Registra nuovo utente
activateAccount(token: string) => Promise<CustomResponse>Attiva account tramite token email
forgotPassword(email: ForgotPassword) => Promise<CustomResponse>Avvia flusso recupero password
resetPassword(data: ResetPassword) => Promise<CustomResponse>Imposta nuova password con token
refreshToken() => Promise<AuthResponse | null>Rinnova access token (chiamato auto su 401)
isAuthenticated() => booleanPresenza credenziali valide (no chiamate al server)
getToken() => string | nullAccess token JWT corrente

Cache

MetodoFirmaDescrizione
clearCache() => voidInvalida tutta la cache
cleanExpiredCache() => Promise<void>Pulisce solo elementi scaduti

Getters avanzati

MetodoRitornaUso
getHttpClient()IHttpClientRichieste custom non-CRUD (es. RPC)
getAuthService()IAuthServiceOperazioni auth avanzate
getCacheService()ICacheServiceInvalidazione selettiva, statistiche

Esempio completo

import {
  PostgRESTClient,
  AuthStrategyType,
  CacheStrategyType,
  HttpClientType,
} from '@pzeta/postgrest'

interface User {
  iduser: number
  email: string
  nome: string
}

const client = new PostgRESTClient({
  apiUrl: 'https://api.example.com',
  schema: 'app',
  httpClientType: HttpClientType.FETCH,
  authType: AuthStrategyType.JWT,
  cacheType: CacheStrategyType.INDEXEDDB,
  cacheTTL: 5 * 60 * 1000, // 5 minuti
  timeout: 15000,
})

await client.init()

// Login
const auth = await client.login({
  email: 'mario@example.com',
  password: 'pwd123',
})

if (!auth) {
  console.error('Login fallito')
  return
}

// Repository
const userRepo = client.repository<User, number>('/users', 'iduser')
const users = await userRepo.readAll({
  nome: { operator: 'ilike', value: '%mario%' },
  sort: { field: 'iduser', direction: 'desc' },
  pagination: { limit: 20 },
})

// Repository non cached, no auth (es. endpoint pubblico)
const logRepo = client.repository<Log, string>('/v_logs_pubblici', 'idlog', {
  useCache: false,
  isAuthRequired: false,
})

// Cleanup
client.destroy()

Lifecycle

1. new PostgRESTClient(config)
   └─ Salva config con default

2. await client.init()
   ├─ Crea auth strategy (JWT/Cookie/ApiKey/None o custom)
   ├─ Crea cache strategy (con auto-fallback IndexedDB → LocalStorage → Memory)
   ├─ Crea HTTP client (Fetch o Axios)
   ├─ Inizializza CacheService (singleton) con threshold 75%, maxAge cacheTTL
   ├─ Inizializza AuthService
   └─ Collega HTTP client ↔ AuthService

3. Operazioni: login(), repository(), getHttpClient()...

4. client.destroy()
   ├─ Ferma timer cache
   ├─ Cancella pending requests
   └─ initialized = false (reinizializzabile)
In Vue/React chiama destroy() nel hook onUnmounted/useEffect cleanup. In SPA con router invoca destroy() nel beforeEach quando si esce dall'area autenticata, per prevenire memory leak.

Errori comuni

ErroreCausaSoluzione
PostgRESTClient non inizializzatoChiamata a metodo pubblico prima di init()await client.init() prima di tutto
Token non aggiunto alle richiesteauthType errato vs server (es. JWT quando server usa cookie)Verifica authType o usa customAuthStrategy
Cache mai popolataIndexedDB non disponibile e fallback non scattatoVerifica con client.getCacheService().getStats()

Tipi correlati