import { useState , useEffect } from 'react' ; import useAttempt from 'shared/hooks/useAttemptNext' ; import Ctx from 'teleport/teleportContext' ; import { StickyCluster } from 'teleport/types' ; import cfg from 'teleport/config' ; import { Node } from 'teleport/services/nodes' ; import { openNewTab } from 'teleport/lib/util' ; export default function useNodes ( ctx , stickyCluster ) { const { isLeafCluster , clusterId } = stickyCluster ; const [ nodes , setNodes ] = useState < Node [ ] > ( [ ] ) ; const { attempt , run , setAttempt } = useAttempt ( 'processing' ) ; const [ isAddNodeVisible , setIsAddNodeVisible ] = useState ( false ) ; const canCreate = ctx . storeUser . getTokenAccess ( ) . create ; const logins = ctx . storeUser . getSshLogins ( ) ; useEffect ( ( ) => { run ( ( ) => ctx . nodeService . fetchNodes ( clusterId ) . then ( setNodes ) ) ; } , [ clusterId ] ) ; const getNodeLoginOptions = ( serverId ) => makeOptions ( clusterId , serverId , logins ) ; const startSshSession = ( login , serverId ) => { const url = cfg . getSshConnectRoute ( { clusterId , serverId , login , } ) ; openNewTab ( url ) ; } ; const fetchNodes = ( ) => { return ctx . nodeService . fetchNodes ( clusterId ) . then ( setNodes ) . catch ( ( err ) => setAttempt ( { status : 'failed' , statusText : err . message } ) ) ; } ; const hideAddNode = ( ) => { setIsAddNodeVisible ( false ) ; fetchNodes ( ) ; } ; const showAddNode = ( ) => { setIsAddNodeVisible ( true ) ; } ; return { canCreate , attempt , nodes , getNodeLoginOptions , startSshSession , isAddNodeVisible , isLeafCluster , clusterId , hideAddNode , showAddNode , } ; } function makeOptions ( clusterId , serverId = '' , logins = [ ] as string [ ] ) { return logins . map ( login => { const url = cfg . getSshConnectRoute ( { clusterId , serverId , login , } ) ; return { login , url , } ; } ) ; } export type State = ReturnType < typeof useNodes > ;