All files / layers / L2W coordinatorResolver.ts

100% Statements 17/17
100% Branches 4/4
100% Functions 4/4
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55        630x 630x 30x   600x   38x   630x 630x 630x 68x 68x 68x   10x   68x           68x 68x     630x                                              
import { createCoordinator } from './coordinator'
import {
  createDefaultBehaviorContract,
  createFieldPolicyFromConfig,
} from './behaviorContract'
import { hooksByPath } from '../L1/entityResolver'
import type { EntityPath } from '../L1/contracts'
import type { RouteContext, EntitySelectSource } from '../interfaces'
 
function cacheKey(entityPath: EntityPath, fieldSet: string[], entitySelectSources?: Record<string, EntitySelectSource>): string {
  const base = `${entityPath}:${fieldSet.join(',')}`
  if (entitySelectSources) {
    return `${base}:es:${JSON.stringify(entitySelectSources)}`
  }
  return base
}
 
const coordinatorCache = new Map<
  string,
  any
>()
 
function getCoordinator(entityPath: EntityPath, fieldSet: string[], entitySelectSources?: Record<string, EntitySelectSource>) {
  const key = cacheKey(entityPath, fieldSet, entitySelectSources)
  const existing = coordinatorCache.get(key)
  if (existing) return existing
 
  const hooks = hooksByPath[entityPath]
  const base = createDefaultBehaviorContract()
 
  const behavior = {
    ...base,
    fieldPolicy: (mode: 'add' | 'edit') =>
      createFieldPolicyFromConfig(fieldSet, mode),
  }
 
  const coord = createCoordinator({
    hooks: hooks as any,
    behavior: behavior as typeof base,
    owner: entityPath,
    entitySelectSources,
  })
  coordinatorCache.set(key, coord)
  return coord
}
 
export function useEntityCoordinator(
  entityPath: EntityPath,
  fieldSet: string[],
  routeContext: RouteContext,
  entitySelectSources?: Record<string, EntitySelectSource>,
) {
  return getCoordinator(entityPath, fieldSet, entitySelectSources).useCoordinator(routeContext)
}