PostgREST
Cos'è @pzeta/postgrest
@pzeta/postgrest è la libreria client TypeScript per consumare API PostgREST seguendo i principi di Domain-Driven Design e Clean Architecture. Espone un facade ad alto livello (PostgRESTClient), una classe base service (BasePostgrestService) per il pattern di adozione canonico nei progetti PZeta, e l'intera infrastruttura modulare (HTTP, cache, auth, repository) per casi che richiedono controllo fine.
node>=22.0.0. Tutte le peer dependencies (axios, vue, @pzeta/mfe-contracts) sono opzionali.Funzionalità principali
- Facade
PostgRESTClient— setup in due righe, gestisce HTTP, auth, cache e repository factory - Service Pattern —
BasePostgrestServicecome classe base per service di dominio (CRUD + RPC + error messages italiani) - Repository Pattern —
PostgRESTRepositoryeEnhancedPostgRESTRepositoryCRUD type-safe - 5 Cache Strategies — IndexedDB (default), LocalStorage, SessionStorage, Memory, None con auto-fallback
- 4 Auth Strategies — JWT (sessionStorage), Cookie HTTP-only, ApiKey, None — interfaccia
IAuthStrategyper strategie custom - Filtering type-safe —
FilterCriteria<T>con tutti gli operatori PostgREST (eq,ilike,between,in,fts, ...), sort, paginazione, vertical filtering - Dual HTTP Client —
FetchHttpClient(nativo, zero deps) oAxiosHttpClient(opzionale) - Schema PostgreSQL — header
Accept-Profile/Content-Profileper multi-schema - MFE entry point — subpath
@pzeta/postgrest/mfeconPostgrestMfeService,BaseMfePostgrestServicee composables Vue
Architettura
@pzeta/postgrest
├── domain/ # Zero dipendenze runtime
│ ├── entities/ # AuthEntity
│ ├── value-objects/ # FilterCriteria · CacheMetadata
│ └── interfaces/ # IAuthService · ICrudRepository · IHttpClient · ILogger · ICacheStrategy
├── application/
│ ├── facades/ # PostgRESTClient (entry point principale)
│ └── services/ # BasePostgrestService (classe base service di dominio)
├── infrastructure/
│ ├── http/ # FetchHttpClient · AxiosHttpClient · HttpClientFactory · FetchAdapter · CorsAdapter
│ ├── repositories/ # PostgRESTRepository · EnhancedPostgRESTRepository · RepositoryFactory
│ ├── auth/ # AuthService + strategies/ (JWT · Cookie · ApiKey · None) + factory
│ ├── cache/ # CacheService · IndexedDBStore + 5 strategies + factory
│ ├── logging/ # ConsoleLogger · NullLogger
│ └── utils/ # FilterUtils · TypeGuards
└── mfe/ # Entry separato per microfrontend (subpath /mfe)
├── PostgrestMfeService
├── BaseMfePostgrestService
├── composables/ # usePostgrestPagination · useReferenceData
└── utils/
Le dipendenze puntano sempre verso l'interno: infrastructure → application → domain. Il domain layer non importa nulla dall'esterno.
Sotto-pagine
Auth
Autenticazione multi-strategia per @pzeta/postgrest. Supporta JWT Bearer, Cookie HTTP-only, API Key e NoAuth con interfaccia comune IAuthStrategy.
Cache
Sistema di caching multi-strategia con TTL, background refresh e request deduplication. Strategie IndexedDB, LocalStorage, SessionStorage, Memory e NoCache con auto-fallback.
Domain
Layer di dominio di @pzeta/postgrest — entità, value objects e interfacce con zero dipendenze runtime. Cuore puro della Clean Architecture.
Facade & Services
Punto di ingresso applicativo della libreria — facade PostgRESTClient per setup rapido e BasePostgrestService come classe base per service di dominio CRUD + RPC.
Getting Started
Guida introduttiva a @pzeta/postgrest. Installazione, architettura DDD, quick start con PostgRESTClient e service pattern con BasePostgrestService.
HTTP
Client HTTP duale (Fetch API e Axios), factory di creazione, gestione CORS e wrapper strategy-aware per @pzeta/postgrest.
Logging & Utils
Logger configurabili (ConsoleLogger, NullLogger) per iniettare il logging della libreria e FilterUtils — utility statiche per convertire FilterCriteria type-safe nella sintassi query PostgREST.
MFE Integration
Entry point @pzeta/postgrest/mfe per microfrontend — service e composables Vue 3 basati su MFEHttpClient di @pzeta/mfe-contracts invece di Axios/Fetch diretti.
Repositories
Repository Pattern type-safe per PostgREST — classi CRUD generiche, wrapper semplificati, factory con preset e utility runtime per errori, path e type guards.
Quick start
import { PostgRESTClient } from '@pzeta/postgrest'
interface User {
iduser: number
email: string
nome: string
}
const client = new PostgRESTClient({
apiUrl: 'https://api.example.com',
schema: 'public',
})
await client.init()
await client.login({ email: 'mario@example.com', password: 'pwd' })
const userRepo = client.repository<User, number>('/users', 'iduser')
const utenti = await userRepo.readAll({
nome: { operator: 'ilike', value: '%mario%' },
sort: { field: 'iduser', direction: 'desc' },
pagination: { limit: 20, offset: 0 },
})
client.destroy() // cleanup obbligatorio
Per progetti strutturati il pattern consigliato è estendere BasePostgrestService: vedi Service Pattern.
Quando usare cosa
| Scenario | API consigliata |
|---|---|
| Setup rapido, app standalone | PostgRESTClient (facade) |
| Progetti strutturati con DI / service di dominio | BasePostgrestService (estende il facade) |
| Controllo fine, repository singolo senza facade | EnhancedPostgRESTRepository diretto |
| Configurazione manuale di HTTP/auth/cache | HttpClientFactory + AuthStrategyFactory + CacheStrategyFactory + RepositoryFactory |
Microfrontend con MFEHttpClient da shell host | BaseMfePostgrestService (@pzeta/postgrest/mfe) |
| Chiamate CRUD ad-hoc in un MFE | PostgrestMfeService (@pzeta/postgrest/mfe) |
| Lookup dropdown / select remoti in MFE | useReferenceData (@pzeta/postgrest/mfe) |
Stack tecnico
- TypeScript ~6.0 — strict mode, zero
any - ESM only —
"type": "module", build viatsc - Subpath exports —
.(core) e/mfe(microfrontend) - Zero dipendenze runtime — Fetch API nativa di default
- Peer dependencies opzionali —
axios,vue,@pzeta/mfe-contracts - Vitest v4 per i test (1000+ test nella suite)
- Biome per lint e format