Getting Started

Architettura

Modello Clean Architecture + DDD a tre layer (domain, application, infrastructure). Dependency Rule, Strategy Pattern per auth e cache, Repository Pattern, Factory Pattern, Facade Pattern.

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) — tipi UserCredentials, RegisterUser, AuthResponse, ForgotPassword, ResetPassword, type guard isAuthResponse / isCustomResponse
  • Value ObjectsFilterCriteria<T>, CacheMetadata, CachedResponse, PaginationOptions, SortOptions, operatori PostgREST tipizzati
  • Interfacce — contratti astratti che l'application e l'infrastructure implementano:
    • ICrudRepository<T, K> — repository CRUD generico
    • IHttpClient — client HTTP astratto (implementato da Fetch e Axios)
    • IAuthService — operazioni autenticazione
    • IAuthStrategy — strategia auth pluggable (JWT / Cookie / ApiKey / None)
    • ICacheStrategy — strategia cache pluggable (IndexedDB / LocalStorage / ...)
    • ICacheService — servizio cache con TTL e background refresh
    • ILogger — 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: newinit() → uso → destroy().
  • services/BasePostgrestService — Classe astratta da estendere per ogni entità di dominio. Wrappa EnhancedPostgRESTRepository con API CRUD omogenea, error messages user-facing in italiano e utility callRpc() per stored procedure PostgREST.

Infrastructure layer (src/infrastructure/)

Implementazioni concrete delle interfacce del dominio.

Sotto-cartellaContenuto
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

DO
  • infrastructure può importare da application e da domain
  • application può importare solo da domain
  • domain non importa nulla (né da application, né da infrastructure, né da pacchetti esterni runtime)
DON'T
  • 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