useApi, useCancelHandler, usePolling
useApi
Recupera l'istanza di ImportExportApi dal contesto Vue (provided da ImportWizard o ExportDialog tramite IMPORT_EXPORT_API_KEY).
import { useApi } from '@pzeta/vue-importexport'
const api = useApi()
await api.uploadFile(file, 'anagrafica')
Errori
Se chiamato fuori da un componente che ha l'API provided, lancia:
ImportExportApi non disponibile. Assicurarsi che il componente sia
usato dentro ImportWizard o ExportDialog.
Quando usarlo
- All'interno di un sotto-componente del wizard custom (per recuperare l'API condivisa)
- All'interno di un composable custom che opera nel contesto di
ImportWizard/ExportDialog
Per uso standalone (fuori dal wizard) crea direttamente l'istanza:
import { ImportExportApi } from '@pzeta/vue-importexport'
const api = new ImportExportApi(baseUrl)
IMPORT_EXPORT_API_KEY
InjectionKey<ImportExportApi> esposto pubblicamente per provide manuale:
import { provide } from 'vue'
import { ImportExportApi, IMPORT_EXPORT_API_KEY } from '@pzeta/vue-importexport'
const api = new ImportExportApi(baseUrl)
provide(IMPORT_EXPORT_API_KEY, api)
useCancelHandler
Factory che produce un handler di annullamento per operazioni in corso (upload, export). Centralizza la logica:
- Guardia su
loading.value(no-op se non c'è nulla da annullare) - Invocazione di
cancelFn(di solito unAbortController.abort()) - Reset di
loadingafalsee settaggio del messaggio di "operazione annullata" suerrore.value - Log dell'errore via
logErrorcon ilerrorCodeindicato - Hook opzionale
onCancelper cleanup specifico
Firma
function createCancelHandler(options: CancelHandlerOptions): () => void
CancelHandlerOptions
| Campo | Tipo | Descrizione |
|---|---|---|
loading | Ref<boolean> | Riferimento al flag loading |
errore | Ref<string | null> | Riferimento al messaggio errore |
cancelFn | () => void | Funzione di cancel (es. api.cancelUpload()) |
cancelledMessage | string | Messaggio mostrato in errore |
errorCode | ErrorCode | Code per logError |
logDetails | () => Record<string, unknown> | Dettagli aggiuntivi nel log |
onCancel | () => void | Hook post-cancel (es. stopPolling) |
Esempio
import { ref } from 'vue'
import { createCancelHandler } from '@pzeta/vue-importexport'
import { ErrorCode } from '@pzeta/vue-importexport'
const loading = ref(false)
const errore = ref<string | null>(null)
const cancel = createCancelHandler({
loading,
errore,
cancelFn: () => api.cancelUpload(),
cancelledMessage: "Caricamento file annullato dall'utente",
errorCode: ErrorCode.UPLOAD_FAILED,
logDetails: () => ({ fileName: file.value?.name }),
onCancel: () => { stato.value = 'error' },
})
// Da chiamare dal click "Annulla"
cancel()
Note
createCancelHandler non è esportato attualmente come API pubblica della libreria — viene usato internamente da useImport e useExport. È documentato qui per riferimento. Per gestire annullamenti custom, replicare il pattern manualmente.
usePolling
Composable generico per polling asincrono con cleanup automatico. Usato internamente da useImportStatus e useExport.
Inizializzazione
import { usePolling } from '@pzeta/vue-importexport'
const polling = usePolling<MyStatusType>({
statusFetcher: (id) => api.getStatus(id),
isCompleted: (s) => s.done === true,
isError: (s) => s.error === true,
onCompleted: (s) => console.log('Done!', s),
})
polling.startPolling('job-123')
PollingOptions<T>
| Opzione | Tipo | Default | Descrizione |
|---|---|---|---|
statusFetcher | (id: string) => Promise<T> | — | Funzione che esegue il check dello status |
isCompleted | (status: T) => boolean | — | True se l'operazione è completata |
isError | (status: T) => boolean | — | True se è in errore |
onCompleted | (status: T) => void | Promise<void> | — | Callback completion (può scaricare il file, ecc.) |
onError | (status: T) => void | — | Callback errore di stato |
onNetworkError | (error: Error) => void | — | Callback errore di rete (la chiamata fetcher è fallita) |
interval | number | 2000 | Intervallo polling in ms |
manualCleanup | boolean | false | Disabilita la registrazione automatica di onUnmounted |
Stato reattivo
| Proprietà | Tipo | Descrizione |
|---|---|---|
progresso | Ref<T | null> | Ultimo status ricevuto |
isPolling | Ref<boolean> | Polling attivo |
Metodi
| Metodo | Descrizione |
|---|---|
startPolling(id) | Avvia il polling per id. No-op se già attivo |
stopPolling() | Stop polling |
cleanup() | Alias di stopPolling, registrato automaticamente su onUnmounted |
Comportamento
- Al
startPolling, lancia subito un primopoll()(no delay iniziale) - A ogni iterazione: chiama
statusFetcher, aggiornaprogresso, valutaisCompleted→ stop +onCompleted, oppureisError→ stop +onError, altrimentisetTimeoutper la prossima iterazione - In caso di eccezione di rete, ferma il polling e chiama
onNetworkError - Se in setup di un componente Vue, registra automaticamente
onUnmounted(stopPolling)per evitare leak
Esempio con cleanup manuale
Necessario quando si invoca usePolling fuori dal setup() di un componente:
const polling = usePolling({
statusFetcher,
isCompleted,
isError,
manualCleanup: true,
})
// Devi chiamare manualmente cleanup quando appropriato
onUnmounted(polling.cleanup)
Esempio per export asincrono
const exportPolling = usePolling<ExportProgresso>({
statusFetcher: (id) => api.getExportStatus(id),
isCompleted: (s) => s.stato === 'completato',
isError: (s) => s.stato === 'errore',
onCompleted: async (s) => {
if (s.urlDownload) {
const blob = await api.downloadExport(s.urlDownload)
downloadBlob(blob, s.nomeFile ?? 'export.xlsx')
}
},
})