Refactor connection
This commit is contained in:
40
app/src/actions/Connection.ts
Normal file
40
app/src/actions/Connection.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { ActionTypes, NodeOrder, CustomAction, AppState } from '../reducers'
|
||||
import { MqttOptions } from '../../../backend/src/DataSource'
|
||||
import { Dispatch } from 'redux'
|
||||
import { rendererEvents, addMqttConnectionEvent, makeConnectionStateEvent, removeConnection } from '../../../events'
|
||||
|
||||
export const connect = (options: MqttOptions, connectionId: string) => (dispatch: Dispatch<any>, getState: () => AppState) => {
|
||||
dispatch(connecting(connectionId))
|
||||
rendererEvents.emit(addMqttConnectionEvent, { options, id: connectionId })
|
||||
const event = makeConnectionStateEvent(connectionId)
|
||||
rendererEvents.subscribe(event, (dataSourceState) => {
|
||||
if (dataSourceState.connected) {
|
||||
dispatch(connected())
|
||||
} else if (dataSourceState.error) {
|
||||
dispatch(showError(dataSourceState.error))
|
||||
dispatch(disconnect())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const connected: () => CustomAction = () => ({
|
||||
type: ActionTypes.connected,
|
||||
})
|
||||
|
||||
export const connecting: (connectionId: string) => CustomAction = (connectionId: string) => ({
|
||||
connectionId,
|
||||
type: ActionTypes.connecting,
|
||||
})
|
||||
|
||||
export const showError = (error?: string) => ({
|
||||
error,
|
||||
type: ActionTypes.showError,
|
||||
})
|
||||
|
||||
export const disconnect = () => (dispatch: Dispatch<CustomAction>, getState: () => AppState) => {
|
||||
rendererEvents.emit(removeConnection, getState().connectionId)
|
||||
|
||||
dispatch({
|
||||
type: ActionTypes.disconnect,
|
||||
})
|
||||
}
|
||||
@@ -2,5 +2,6 @@ import * as settingsActions from './Settings'
|
||||
import * as sidebarActions from './Sidebar'
|
||||
import * as treeActions from './Tree'
|
||||
import * as updateNotifierActions from './UpdateNotifier'
|
||||
import * as connectionActions from './Connection'
|
||||
|
||||
export { settingsActions, treeActions, sidebarActions, updateNotifierActions }
|
||||
export { settingsActions, treeActions, sidebarActions, updateNotifierActions, connectionActions }
|
||||
|
||||
Reference in New Issue
Block a user