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
| Campo | Tipo | Required | Default | Descrizione |
|---|---|---|---|---|
apiUrl | string | ✓ | — | URL base dell'endpoint PostgREST |
schema | string | — | 'public' | Schema PostgreSQL (header Accept-Profile/Content-Profile) |
httpClientType | HttpClientType | — | FETCH | FETCH (nativo, zero deps) o AXIOS (peer dep) |
authType | AuthStrategyType | — | JWT | JWT, COOKIE, API_KEY, NONE |
cacheType | CacheStrategyType | — | INDEXEDDB | INDEXEDDB, LOCALSTORAGE, SESSIONSTORAGE, MEMORY, NONE |
cacheTTL | number | — | 3600000 | TTL cache in millisecondi (1h default) |
timeout | number | — | 10000 | Timeout richiesta HTTP in millisecondi |
customAuthStrategy | IAuthStrategy | — | — | Override completo della strategia auth |
customCacheStrategy | ICacheStrategy | — | — | Override completo della strategia cache |
API
Lifecycle
| Metodo | Firma | Descrizione |
|---|---|---|
init() | () => Promise<void> | Inizializza HTTP client, auth, cache, AuthService. Idempotente |
destroy() | () => void | Libera 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
| Metodo | Firma | Descrizione |
|---|---|---|
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 | () => boolean | Presenza credenziali valide (no chiamate al server) |
getToken | () => string | null | Access token JWT corrente |
Cache
| Metodo | Firma | Descrizione |
|---|---|---|
clearCache | () => void | Invalida tutta la cache |
cleanExpiredCache | () => Promise<void> | Pulisce solo elementi scaduti |
Getters avanzati
| Metodo | Ritorna | Uso |
|---|---|---|
getHttpClient() | IHttpClient | Richieste custom non-CRUD (es. RPC) |
getAuthService() | IAuthService | Operazioni auth avanzate |
getCacheService() | ICacheService | Invalidazione 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
| Errore | Causa | Soluzione |
|---|---|---|
PostgRESTClient non inizializzato | Chiamata a metodo pubblico prima di init() | await client.init() prima di tutto |
| Token non aggiunto alle richieste | authType errato vs server (es. JWT quando server usa cookie) | Verifica authType o usa customAuthStrategy |
| Cache mai popolata | IndexedDB non disponibile e fallback non scattato | Verifica con client.getCacheService().getStats() |
Tipi correlati
BasePostgrestService— classe base service di dominio costruita sopra il clientAuthEntity— tipi delle richieste/risposte di autenticazioneFilterCriteria— criteri perrepository.readAll()IAuthStrategy— interfaccia per strategie auth customICacheStrategy— interfaccia per strategie cache custom
BasePostgrestService
Classe base astratta per service applicativi PostgREST. Wrapper di alto livello su EnhancedPostgRESTRepository con API CRUD omogenea, error messages italiani e helper RPC.
Domain
Layer di dominio di @pzeta/postgrest — entità, value objects e interfacce con zero dipendenze runtime. Cuore puro della Clean Architecture.