All files / layers / L2W behaviorContract.ts

96.15% Statements 25/26
100% Branches 8/8
92.85% Functions 13/14
95.83% Lines 23/24

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    32x     8x 4x   10x   1x     296x 3146x       2x     8x 108x 108x 712x 712x 712x 712x         108x               13x 13x 55x   55x   55x 55x   13x        
import type { BehaviorContract, FieldPolicy } from '../interfaces'
 
export function createDefaultBehaviorContract<
  TEntity extends { id: string },
>(): BehaviorContract<TEntity, TEntity, Partial<TEntity>, Partial<TEntity>> {
  function populate<U extends TEntity>(entity: U): U {
    return { ...entity }
  }
 
  function toCreate<U extends TEntity>(form: U): Partial<TEntity> {
    return { ...form }
  }
 
  function toUpdate<U extends TEntity>(form: U): Partial<TEntity> {
    return { ...form }
  }
 
  function fieldPolicy(_mode: 'add' | 'edit'): FieldPolicy {
    return {}
  }
 
  return {
    defaults: () => ({} as TEntity),
    populate,
    toCreate,
    toUpdate,
    fieldPolicy,
  } as unknown as BehaviorContract<TEntity, TEntity, Partial<TEntity>, Partial<TEntity>>
}
 
export function createFieldPolicyFromConfig(
  fields: string[],
  mode: 'add' | 'edit',
  fieldBehavior?: {
    [field: string]: {
      visible?: { add?: boolean; edit?: boolean }
      editable?: { add?: boolean; edit?: boolean }
    }
  },
): FieldPolicy {
  const policy: FieldPolicy = {}
  for (const field of fields) {
    const fb = fieldBehavior?.[field]
    const visible =
      fb?.visible?.[mode] ?? true
    const editable =
      fb?.editable?.[mode] ?? true
    policy[field] = { visible, editable }
  }
  return policy
}
 
export { type BehaviorContract, type FieldPolicy }