import type { Middleware } from '@owlmeans/context' import { MiddlewareType, MiddlewareStage, assertContext } from '@owlmeans/context' import type { ClientEntrypoint } from '@owlmeans/client-entrypoint' import type { ApiConfig } from '@owlmeans/api-config' import { API_CONFIG } from '@owlmeans/api-config' import { configHelper } from '@owlmeans/config' import type { CommonConfig } from '@owlmeans/config' import type { ClientContext, ClientConfig } from '@owlmeans/client-context' import { logger } from '@owlmeans/log' const log = logger('api-config-client') export const apiConfigMiddleware: Middleware = { type: MiddlewareType.Context, stage: MiddlewareStage.Loading, apply: async (ctx) => { const context = assertContext>( ctx as any, 'api-config-middleware' ) const module = context.entrypoint>(API_CONFIG) if (context.cfg.primaryHost != null) { module.route.route.host = context.cfg.primaryHost if (context.cfg.primaryPort != null) { module.route.route.port = context.cfg.primaryPort } try { const config = await module.call() const target: CommonConfig = context.cfg as unknown as CommonConfig configHelper.mergeConfig(target, config as CommonConfig) } catch (e) { log.warn('API config not loaded', e) } } } }