HTTP
StrategyAwareHttpClient
Client HTTP basato su Axios che integra IAuthStrategy moderna mantenendo backward compatibility con IAuthHandler legacy.
Quando usarlo
StrategyAwareHttpClient è un wrapper su AxiosInstance che integra nativamente una IAuthStrategy (approccio moderno) e, in alternativa, un IAuthHandler legacy come fallback.
Usalo quando:
- vuoi comporre Axios + auth strategy moderna senza usare
FetchHttpClient; - stai migrando da
IAuthHandleraIAuthStrategye vuoi entrambi i modelli supportati nello stesso client; - hai bisogno di un client Axios-based dove la strategia di auth è iniettabile e sostituibile a runtime.
Per setup nuovi: usa direttamente
FetchHttpClient con setAuthStrategy(). StrategyAwareHttpClient è pensato per progetti già su Axios.Costruttore
class StrategyAwareHttpClient implements IHttpClient {
constructor(axiosInstance?: AxiosInstance, authStrategy?: IAuthStrategy)
}
| Parametro | Tipo | Default | Descrizione |
|---|---|---|---|
axiosInstance | AxiosInstance | axios.create() | Istanza Axios sottostante. |
authStrategy | IAuthStrategy | null | Strategia di autenticazione (JWT, Cookie, None, custom). Può essere impostata anche dopo via setAuthStrategy(). |
Esempio: composizione strategy + axios
import axios from 'axios'
import { StrategyAwareHttpClient, AuthStrategyFactory } from '@pzeta/postgrest'
const axiosInstance = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
})
const jwtStrategy = AuthStrategyFactory.createJwtStrategy()
const client = new StrategyAwareHttpClient(axiosInstance, jwtStrategy)
// Le richieste applicano automaticamente la strategy
const { data } = await client.get<User[]>('/users')
Esempio: switch di strategia a runtime
const client = new StrategyAwareHttpClient(axiosInstance)
// Inizialmente: endpoint pubblici
client.setAuthStrategy(AuthStrategyFactory.create(AuthStrategyType.NONE))
await client.get('/public/products')
// Dopo login: passa a JWT
client.setAuthStrategy(AuthStrategyFactory.createJwtStrategy())
await client.get('/users/me')
API
| Metodo | Signature | Descrizione |
|---|---|---|
request | <T>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> | Richiesta generica. Applica applyAuthentication e gestisce retry su 401. |
get / post / put / patch / delete | come IHttpClient | Identica shape Axios. |
setAuthStrategy | (strategy: IAuthStrategy): void | Imposta la strategia di auth moderna. Prevale su IAuthHandler se entrambi presenti. |
setAuthHandler | (handler: IAuthHandler): void | Handler legacy. @deprecated — usa setAuthStrategy. |
setMaxRetries | (maxRetries: number): void | Retry su 401. Default 1. |
getAxiosInstance | (): AxiosInstance | Istanza Axios sottostante. |
Priorità di autenticazione
applyAuthentication(config) segue questa priorità:
- Se è impostata una
IAuthStrategy→ chiamastrategy.applyAuth(config)e usa il risultato. - Altrimenti, se è impostato un
IAuthHandlerlegacy → leggegetToken()e aggiungeAuthorization: Bearer <token>conwithCredentials: false. - Altrimenti la config viene inviata invariata.
Gestione 401
In caso di 401:
- se
authStrategy.supportsRefresh()ètrue, il client non ritenta direttamente: il refresh va gestito dal layer superiore (es. servizio di auth che chiamasaveCredentials()sulla strategia); - altrimenti, se è presente un
IAuthHandler, viene chiamatohandler.handleAuthError(error). Se ritornatrue, la richiesta viene ripetuta conapplyAuthentication()riapplicato.
Questa divisione di responsabilità è voluta: con
IAuthStrategy, il refresh è centralizzato in un servizio dedicato e non duplicato nel client HTTP.Setup composito tipico
import axios from 'axios'
import { StrategyAwareHttpClient, AuthStrategyFactory } from '@pzeta/postgrest'
// 1. Istanza Axios con interceptors comuni
const axiosInstance = axios.create({ baseURL: '/api', timeout: 10000 })
axiosInstance.interceptors.request.use((config) => {
config.headers['X-Correlation-Id'] = crypto.randomUUID()
return config
})
// 2. Strategia auth (JWT con sessionStorage)
const strategy = AuthStrategyFactory.createJwtStrategy()
// 3. Client composito
const httpClient = new StrategyAwareHttpClient(axiosInstance, strategy)
// 4. Iniettabile in repository / service
// const repo = new EnhancedPostgRESTRepository(httpClient, ...)
Per integrazione con cache, vedi CachedHttpClient (decoratore che aggiunge cache attorno a un IHttpClient).
Tipi correlati
IHttpClient— interfaccia implementataIAuthStrategy— strategia modernaIAuthHandler— handler legacy (fallback)AxiosHttpClient— versione senza supporto strategy modernaFetchHttpClient— equivalente Fetch-based consetAuthStrategy()
HttpClientFactory
Factory centrale per creare client HTTP preconfigurati. Espone createFetchClient, createAxiosClient, createJwtClient, createCookieClient, createPublicClient, getDefaultHttpClient e createHttpClient.
Repositories
Repository Pattern type-safe per PostgREST — classi CRUD generiche, wrapper semplificati, factory con preset e utility runtime per errori, path e type guards.