import { Server } from './interfaces' ; export default class HotelApi { getServers = ( ) : Promise < Server [ ] > => { return fetch ( `${ HotelApi . getHotelUrl ( ) }/_/servers` ) . then ( async ( response ) => { if ( response . ok ) { return this . transformServersData ( await response . json ( ) ) ; } else { console . error ( 'Failed to load the servers' , response . body ) ; return [ ] ; } } ) ; } ; transformServersData = ( data ) : Server [ ] => { return Object . keys ( data ) . sort ( ) . map ( ( serverId ) => { const server = data [ serverId ] ; return { id : serverId , status : server . status , env : server . env , } ; } ) ; } ; watchServers = ( cb ) => { setInterval ( ( ) => this . getServers ( ) . then ( ( data ) => cb ( data ) ) , 3000 ) ; } ; static getHotelUrl = ( ) => { return process . env . NODE_ENV === 'development' ? '' : window . hotelUrl ; } ; sendCommand = ( id , command ) => { return this . postData ( `${ HotelApi . getHotelUrl ( ) }/_/servers/${ id }/${ command }` , null ) ; } ; startServer = ( id ) => { return this . sendCommand ( id , 'start' ) ; } ; stopServer = ( id ) => { return this . sendCommand ( id , 'stop' ) ; } ; postData = ( url , data ) => { return fetch ( url , { method : 'POST' , headers : { 'content-type' : 'application/json' , } , body : JSON . stringify ( data ) , } ) ; } ; }