Architettura
Modello a layer
@pzeta/postgrest segue Clean Architecture con regola di dipendenza unidirezionale: le dipendenze puntano sempre verso l'interno (dal layer infrastruttura verso il dominio). Il domain è puro: zero dipendenze esterne, solo TypeScript.
┌──────────────────────────────────────────────────────────────────────┐
│ INFRASTRUCTURE LAYER │
│ │
│ ┌─ http/ ──────────┐ ┌─ repositories/ ──────┐ ┌─ auth/ ────────┐ │
│ │ FetchHttpClient │ │ PostgRESTRepository │ │ AuthService │ │
│ │ AxiosHttpClient │ │ EnhancedRepository │ │ JwtStrategy │ │
│ │ HttpFactory │ │ RepositoryFactory │ │ CookieStrategy │ │
│ │ FetchAdapter │ │ RepositoryUtils │ │ ApiKeyStrategy │ │
│ │ CorsAdapter │ │ │ │ NoAuthStrategy │ │
│ └──────────────────┘ └──────────────────────┘ └────────────────┘ │
│ │
│ ┌─ cache/ ─────────┐ ┌─ logging/ ───────────┐ ┌─ utils/ ───────┐ │
│ │ CacheService │ │ ConsoleLogger │ │ FilterUtils │ │
│ │ IndexedDBStore │ │ NullLogger │ │ TypeGuards │ │
│ │ 5 strategies │ │ │ │ │ │
│ └──────────────────┘ └──────────────────────┘ └────────────────┘ │
└──────────────────────────────────────────────────────────────────────┘
│
│ implementa interfacce
▼
┌──────────────────────────────────────────────────────────────────────┐
│ APPLICATION LAYER │
│ │
│ ┌─ facades/ ───────────────────┐ ┌─ services/ ──────────────────┐ │
│ │ PostgRESTClient │ │ BasePostgrestService │ │
│ │ - init() / destroy() │ │ - getAll / getById │ │
│ │ - repository<T,K>() │ │ - create / update / delete │ │
│ │ - login / logout / register │ │ - callRpc<R>() │ │
│ │ - clearCache() │ │ (classe astratta da estendere)│ │
│ └──────────────────────────────┘ └──────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────────┘
│
│ usa solo astrazioni domain
▼
┌──────────────────────────────────────────────────────────────────────┐
│ DOMAIN LAYER │
│ (zero dipendenze) │
│ │
│ ┌─ entities/ ──────────┐ ┌─ value-objects/ ──────────────────┐ │
│ │ AuthEntity │ │ FilterCriteria · FilterOperator │ │
│ │ - UserCredentials │ │ CacheMetadata · CacheItem │ │
│ │ - AuthResponse │ │ PaginationOptions · SortOptions │ │
│ └──────────────────────┘ └───────────────────────────────────┘ │
│ │
│ ┌─ interfaces/ ────────────────────────────────────────────────┐ │
│ │ ICrudRepository · IHttpClient · IAuthService · IAuthHandler │ │
│ │ ICacheService · ICacheStrategy · IAuthStrategy · ILogger │ │
│ └──────────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────────┘
I tre layer
Domain layer (src/domain/)
Il cuore della libreria, completamente isolato. Contiene:
- Entità (
AuthEntity.ts) — tipiUserCredentials,RegisterUser,AuthResponse,ForgotPassword,ResetPassword, type guardisAuthResponse/isCustomResponse - Value Objects —
FilterCriteria<T>,CacheMetadata,CachedResponse,PaginationOptions,SortOptions, operatori PostgREST tipizzati - Interfacce — contratti astratti che l'application e l'infrastructure implementano:
ICrudRepository<T, K>— repository CRUD genericoIHttpClient— client HTTP astratto (implementato da Fetch e Axios)IAuthService— operazioni autenticazioneIAuthStrategy— strategia auth pluggable (JWT / Cookie / ApiKey / None)ICacheStrategy— strategia cache pluggable (IndexedDB / LocalStorage / ...)ICacheService— servizio cache con TTL e background refreshILogger— logging configurabile
Application layer (src/application/)
Orchestrazione dei use case usando solo le astrazioni del dominio.
facades/PostgRESTClient— Facade Pattern. Punto di ingresso principale. Nasconde la complessità di setup di HTTP client, auth e cache. Espone API ad alto livello per CRUD, login, logout, register, refresh, gestione cache. Lifecycle:new→init()→ uso →destroy().services/BasePostgrestService— Classe astratta da estendere per ogni entità di dominio. WrappaEnhancedPostgRESTRepositorycon API CRUD omogenea, error messages user-facing in italiano e utilitycallRpc()per stored procedure PostgREST.
Infrastructure layer (src/infrastructure/)
Implementazioni concrete delle interfacce del dominio.
| Sotto-cartella | Contenuto |
|---|---|
http/ | FetchHttpClient (default), AxiosHttpClient (peer opzionale), HttpClientFactory, FetchAdapter, CorsAdapter, StrategyAwareHttpClient |
repositories/ | PostgRESTRepository (CRUD completo + RPC), EnhancedPostgRESTRepository (wrapper con path/keyName fissi), RepositoryFactory (preset JWT/Cookie/Cached), RepositoryUtils, RestError, CrudRepositoryBase, BaseEnhancedRepository |
auth/ | AuthService, AuthServiceFactory, strategie JwtAuthStrategy / CookieAuthStrategy / ApiKeyAuthStrategy / NoAuthStrategy, AuthStrategyFactory |
cache/ | CacheService (singleton con background refresh), IndexedDBStore, strategie IndexedDBCacheStrategy / LocalStorageCacheStrategy / SessionStorageCacheStrategy / MemoryCacheStrategy / NoCacheStrategy, WebStorageCacheStrategy base, CacheStrategyFactory con auto-fallback |
logging/ | ConsoleLogger, NullLogger |
utils/ | FilterUtils (conversione FilterCriteria → query string PostgREST), TypeGuards |
Design pattern
Facade Pattern — PostgRESTClient
Riduce a una classe l'intero setup di HTTP client + strategia auth + cache service + repository factory. Le opzioni hanno default sensati: per partire serve solo apiUrl.
Strategy Pattern — auth e cache
Sia autenticazione che cache usano lo stesso pattern: una interfaccia astratta (IAuthStrategy / ICacheStrategy) e implementazioni intercambiabili (JwtAuthStrategy, CookieAuthStrategy, ... / IndexedDBCacheStrategy, MemoryCacheStrategy, ...). Si può iniettare anche una strategia custom:
const client = new PostgRESTClient({
apiUrl: '...',
customAuthStrategy: new MyCustomAuthStrategy(),
customCacheStrategy: new MemoryCacheStrategy(),
})
Repository Pattern — PostgRESTRepository
Astrazione data-access tipizzata. EnhancedPostgRESTRepository<T, K> lega path PostgREST + chiave primaria a un tipo TypeScript, esponendo read, readAll, readPaginated, create, update, delete, RPC, prefetch.
Factory Pattern — *Factory
Creazione standardizzata di componenti complessi: HttpClientFactory.createFetchClient() / createAxiosClient(), AuthStrategyFactory.create(AuthStrategyType.JWT), CacheStrategyFactory.createWithFallback() (auto-fallback IndexedDB → SessionStorage → LocalStorage → Memory), RepositoryFactory.create(...).
Singleton — CacheService
CacheService.getInstance(httpClient, strategy) garantisce un'unica istanza condivisa tra tutti i repository del client (evita duplicazione di cache e timer). Il facade PostgRESTClient gestisce il suo lifecycle e chiama destroy() correttamente.
Dependency Rule
infrastructurepuò importare daapplicatione dadomainapplicationpuò importare solo dadomaindomainnon importa nulla (né da application, né da infrastructure, né da pacchetti esterni runtime)
- Importare classi concrete dell'infrastruttura nel domain
- Aggiungere logica business nei repository o nel client HTTP
- Bypassare le strategie iniettando token o cache key direttamente
Getting Started
Guida introduttiva a @pzeta/postgrest. Installazione, architettura DDD, quick start con PostgRESTClient e service pattern con BasePostgrestService.
Installazione
Installazione di @pzeta/postgrest, peer dependencies opzionali (axios, vue, @pzeta/mfe-contracts), subpath exports core e /mfe, verifica con esempio minimo.