All files / src/api Open.ts

100% Statements 15/15
100% Branches 6/6
100% Functions 4/4
100% Lines 15/15

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 5327x 27x 27x                                                   27x 560x                 27x 551x 2x 1x   549x 23x 526x 524x 517x     2x    
import { AutoClose, AutoCloseType, typeToAutoClose } from "@jonloucks/contracts-ts/api/AutoClose";
import { AutoOpen, guard as guardAutoOpen } from "@jonloucks/contracts-ts/api/AutoOpen";
import { guardFunctions, isFunction } from "@jonloucks/contracts-ts/api/Types";
import { RequiredType } from "@jonloucks/contracts-ts/api/AutoCloseFactory";
 
/**
 * Interface representing an entity that can be opened, returning an AutoClose mechanism.
 */
export interface Open {
 
  /**
   * Open this instance.
   * @return the mechanism to close
   */
  open(): AutoClose;
}
 
/**
 * The type used to open an Idempotent
 */
export type OpenType = AutoOpen | Open | (() => AutoCloseType);
 
/**
 * Duck-typing check for Open interface.
 *
 * @param value the value to check
 * @returns true if the value implements Open, false otherwise
 */
export function guard(value: unknown): value is RequiredType<Open> {
  return guardFunctions(value, 'open');
}
 
/**
 * Convert an OpenType to an Open instance.
 *
 * @param type the OpenType to convert
 * @return the Open instance
 */
export function typeToOpen(type: OpenType): Open {
  if (guardAutoOpen(type)) {
    return {
      open: () => type.autoOpen()
    }
  } else if (guard(type)) {
    return type;
  } else if (isFunction(type)) {
    return {
      open: () => typeToAutoClose(type())
    };
  } else {
    throw new Error("Invalid Open type.");
  }
}