import axios from 'axios' ; import { RuleType } from '../../../../plugins/alerting/server' ; import { Operator , Craft , ALERTING_EXAMPLE_APP_ID } from '../../common/constants' ; interface PeopleInSpace { people : Array < { craft : string ; name : string ; } > ; number : number ; } function getOperator ( op ) { switch ( op ) { case Operator . AreAbove : return ( left , right ) => left > right ; case Operator . AreBelow : return ( left , right ) => left < right ; case Operator . AreExactly : return ( left , right ) => left === right ; default : return ( ) => { throw new Error ( `Invalid Operator "${ op }" [${ Operator . AreAbove },${ Operator . AreBelow },${ Operator . AreExactly }]` ) ; } ; } } function getCraftFilter ( craft ) { return ( person ) => craft === Craft . OuterSpace ? true : craft === person . craft ; } export const alertType = { id : 'example.people-in-space' , name : 'People In Space Right Now' , actionGroups : [ { id : 'default' , name : 'default' } ] , minimumLicenseRequired : 'basic' , isExportable : true , defaultActionGroupId : 'default' , recoveryActionGroup : { id : 'hasLandedBackOnEarth' , name : 'Has landed back on Earth' , } , async executor ( { services , params } ) { const { outerSpaceCapacity , craft : craftToTriggerBy , op } = params ; const response = await axios . get < PeopleInSpace > ( 'http://api.open-notify.org/astros.json' ) ; const { data : { number : peopleInSpace , people = [ ] } , } = response ; const peopleInCraft = people . filter ( getCraftFilter ( craftToTriggerBy ) ) ; if ( getOperator ( op ) ( peopleInCraft . length , outerSpaceCapacity ) ) { peopleInCraft . forEach ( ( { craft , name } ) => { services . alertInstanceFactory ( name ) . replaceState ( { craft } ) . scheduleActions ( 'default' ) ; } ) ; } return { peopleInSpace , } ; } , producer : ALERTING_EXAMPLE_APP_ID , } ;