import { pipe } from 'rxjs' ; import { map , mergeMap , withLatestFrom , filter } from 'rxjs/operators' ; import { getRobotByName } from '../discovery/selectors' ; import { fetchRobotApi } from './http' ; import * as Types from './types' ; import type { Observable , UnaryFunction , OperatorFunction } from 'rxjs' ; import type { State , Action } from '../types' ; import type { RobotHost } from './types' ; export type ActionToRequestMapper < TriggerAction > = ( triggerAction : TriggerAction , state : State ) => Types . RobotApiRequestOptions | null ; export type ResponseToActionMapper < TriggerAction > = ( response : Types . RobotApiResponse , triggerAction : TriggerAction , state : State ) => Action ; export function withRobotHost < A > ( state$ , getRobotName ) { return pipe ( withLatestFrom ( state$ , ( a , s ) : [ A , State , RobotHost | null ] => [ a , s , getRobotByName ( s , getRobotName ( a ) ) as RobotHost | null , ] ) , filter ( ( args ) : args is [ A , State , RobotHost ] => { const [ , , maybeRobot ] = args ; return maybeRobot !== null ; } ) ) ; } export function mapToRobotApiRequest < A > ( state$ , getRobotName , mapActionToRequest , mapResponseToAction ) { return pipe ( withRobotHost ( state$ , getRobotName ) , map ( ( [ a , s , host ] ) => [ host , mapActionToRequest ( a , s ) , a ] ) , filter ( ( [ _host , request , _origAction ] ) => request !== null ) , mergeMap ( ( [ host , request , origAction ] ) => { return fetchRobotApi ( host , request ) . pipe ( withLatestFrom ( state$ ) , map ( ( [ resp , state ] ) => mapResponseToAction ( resp , origAction , state ) ) ) ; } ) ) ; }