Types

MFEContext

Bridge runtime shell → MFE. Contiene basePath, navigazione, HTTP client autenticato, event bus, tema condiviso, utente e ambiente.

Contratto

interface MFEContext {
  /** Base path per routing relativo (es: "/crm") */
  basePath: string

  /** Rotta corrente da visualizzare (path completo) */
  currentRoute?: string

  /** Callback per navigazione coordinata con shell */
  onNavigate: (path: string) => void

  /** Token autenticazione JWT */
  getToken?: () => string | null

  /** Utente corrente autenticato */
  getUser?: () => MFEUser | null

  /** EventBus globale per comunicazione cross-MFE */
  eventBus?: MFEEventBus

  /** Client HTTP con autenticazione gestita dalla shell */
  http: MFEHttpClient

  /** Configurazione ambiente */
  env?: {
    mode: 'development' | 'staging' | 'production'
    apiBaseUrl?: string
    [key: string]: unknown
  }

  /** Gestione tema condivisa */
  theme?: MFETheme
}

Campi

Obbligatori

CampoTipoDescrizione
basePathstringPrefisso URL del MFE nella shell (es. /crm). Da passare a createMemoryHistory(basePath)
onNavigate(path) => voidCallback per sincronizzare la navigazione con la shell. Da chiamare in router.afterEach() del MFE
httpMFEHttpClientClient HTTP con auth gestita dalla shell. Tutte le chiamate API del MFE devono passare da qui

Opzionali

CampoTipoDescrizione
currentRoutestringRotta corrente visualizzata (path completo, es. /crm/dashboard)
getToken() => string | nullToken JWT corrente o null se non autenticato
getUser() => MFEUser | nullUtente corrente o null
eventBusMFEEventBusBus per comunicazione cross-MFE (emit/on/off)
env{ mode, apiBaseUrl?, ... }Configurazione ambiente. mode: 'development' | 'staging' | 'production'
themeMFEThemeGestione tema condiviso (light/dark/system)

Provide / Inject

Il pattern standard per esporre MFEContext ai componenti del MFE:

// Lato MFE — in mount()
import { MFE_CONTEXT_KEY } from '@pzeta/mfe-contracts'

async mount(container, context) {
  app = createApp(AppRoot)
  app.provide(MFE_CONTEXT_KEY, context)
  app.mount(container)
}
// Lato componente — qualsiasi setup
import { useMfeContext } from '@pzeta/mfe-contracts/composables'

const ctx = useMfeContext()
// ctx è tipato MFEContext, throw se non disponibile

Vedi useMfeContext.

Esempi d'uso

HTTP call

const ctx = useMfeContext()

const { data } = await ctx.http.get<Cliente[]>('/api/clienti', {
  params: { page: 1, limit: 20 },
  timeout: 5000,
})

L'header Authorization è già gestito dalla shell (refresh token incluso): non aggiungerlo manualmente.

const ctx = useMfeContext()

function vaiAlDashboard() {
  ctx.onNavigate('/crm/dashboard')
}

In alternativa, usa il router locale del MFE e fai sì che router.afterEach chiami ctx.onNavigate(to.path).

Lettura utente

const ctx = useMfeContext()

const user = ctx.getUser?.()
if (user) {
  console.log(`Logged in as ${user.username}`)
  console.log('Permessi:', user.permissions)
}

Comunicazione cross-MFE

const ctx = useMfeContext()

// Pubblica evento
ctx.eventBus?.emit('cliente-creato', { id: '42', ragioneSociale: '...' })

// Sottoscrivi (in onMounted)
const handler = (payload) => console.log('Nuovo cliente:', payload)
ctx.eventBus?.on('cliente-creato', handler)

// Cleanup (in onBeforeUnmount)
ctx.eventBus?.off('cliente-creato', handler)

Tema condiviso

const ctx = useMfeContext()

if (ctx.theme?.isDark) {
  document.documentElement.classList.add('dark')
}

ctx.theme?.setTheme('system')

Ambiente

const ctx = useMfeContext()

if (ctx.env?.mode === 'development') {
  console.log('Dev mode, base URL:', ctx.env.apiBaseUrl)
}

Best practice

DO
  • Usa ctx.http per tutte le chiamate API
  • Sincronizza la navigazione con ctx.onNavigate(path) in router.afterEach()
  • Sottoscrivi eventi con ctx.eventBus?.on() e rimuovi sempre in onBeforeUnmount
  • Leggi utente/permessi via ctx.getUser(), non da localStorage del MFE
DON'T
  • Bypassare ctx.http con fetch o axios diretti (perdi auth + refresh + tracing)
  • Modificare ctx (è read-only dal punto di vista del MFE)
  • Salvare riferimenti a ctx.getUser() o ctx.getToken() in variabili: chiamali ogni volta (i valori cambiano)

Tipi correlati