Skip to content

Connect Node-RED API #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"@fortawesome/fontawesome-free": "^6.5.2",
"@projectstorm/react-canvas-core": "^7.0.3",
"@projectstorm/react-diagrams": "^7.0.4",
"@reduxjs/toolkit": "^2.2.3",
"@reduxjs/toolkit": "^2.5.0",
"dompurify": "^3.1.0",
"easymde": "^2.18.0",
"i18next": "^23.11.2",
Expand Down
97 changes: 97 additions & 0 deletions packages/flow-client/src/app/redux/modules/api/flow.api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import environment from '../../../../environment';

// Base type for common properties
export interface NodeRedBase {
id: string;
type: string;
info: string;
env: { name: string; type: string; value: string }[];
}

// Type for regular Node-RED flows
export interface NodeRedFlow extends NodeRedBase {
type: 'tab';
label: string;
disabled: boolean;
}

// Type for Node-RED subflows
export interface NodeRedSubflow extends NodeRedBase {
type: 'subflow';
name: string;
category: string;
color: string;
icon: string;
in: NodeRedEndpoint[];
out: NodeRedEndpoint[];
}

// Type for nodes within flows or subflows
export interface NodeRedNode extends NodeRedBase {
name: string;
x: number;
y: number;
z: string;
wires: string[][];
inputs?: number;
outputs?: number;
inputLabels?: string[];
outputLabels?: string[];
icon?: string;
}

// Type for endpoints used in subflows (inputs and outputs)
export interface NodeRedEndpoint {
x: number;
y: number;
wires: { id: string; port?: number }[];
}

// Composite type for all Node-RED objects
export interface NodeRedFlows {
rev?: string;
flows: NodeRedBase[];
}

// Define a service using a base URL and expected endpoints for flows
export const flowApi = createApi({
reducerPath: 'flowApi',
baseQuery: fetchBaseQuery({
baseUrl: environment.NODE_RED_API_ROOT,
responseHandler: 'content-type',
prepareHeaders: headers => {
headers.set('Node-RED-API-Version', 'v2');
headers.set('Node-RED-Deployment-Type', 'nodes');
return headers;
},
}),
tagTypes: ['Flow'], // For automatic cache invalidation and refetching
endpoints: builder => ({
// Endpoint to fetch all flows
getFlows: builder.query<NodeRedFlows, void>({
query: () => ({
url: 'flows',
headers: {
Accept: 'application/json',
},
}),
providesTags: ['Flow'],
}),
// Endpoint to update all flows
updateFlows: builder.mutation<NodeRedFlows, NodeRedFlows>({
query: flows => ({
url: 'flows',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: flows,
}),
invalidatesTags: ['Flow'],
}),
}),
});

// Export hooks for usage in components
export const { useGetFlowsQuery, useUpdateFlowsMutation } = flowApi;
3 changes: 3 additions & 0 deletions packages/flow-client/src/app/redux/modules/flow/flow.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from './flow.slice';
import { GraphLogic } from './graph.logic';
import { NodeLogic } from './node.logic';
import { RedLogic } from './red.logic';
import { TreeLogic } from './tree.logic';

// checks if a given property has changed
Expand All @@ -37,11 +38,13 @@ export class FlowLogic {
public readonly graph: GraphLogic;
public readonly node: NodeLogic;
public readonly tree: TreeLogic;
public readonly red: RedLogic;

constructor() {
this.node = new NodeLogic();
this.graph = new GraphLogic(this.node);
this.tree = new TreeLogic();
this.red = new RedLogic();
}

public createNewFlow(
Expand Down
62 changes: 62 additions & 0 deletions packages/flow-client/src/app/redux/modules/flow/red.listener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { createListenerMiddleware, isAnyOf } from '@reduxjs/toolkit';
import type { AppLogic } from '../../logic';
import type { AppDispatch, RootState } from '../../store';
import { flowApi } from '../api/flow.api';
import { flowActions } from './flow.slice';

// Create the Node-RED sync middleware instance
export const createRedListener = (logic: AppLogic) => {
const nodeRedListener = createListenerMiddleware({
extra: logic,
});

return nodeRedListener;
};

export const startRedListener = (
listener: ReturnType<typeof createRedListener>
) => {
// Add a listener that responds to any flow state changes to sync with Node-RED
listener.startListening.withTypes<RootState, AppDispatch, AppLogic>()({
matcher: isAnyOf(
// Flow entity actions
flowActions.addFlowEntity,
flowActions.updateFlowEntity,
flowActions.removeFlowEntity,
flowActions.addFlowEntities,
flowActions.updateFlowEntities,
flowActions.removeFlowEntities,
// Flow node actions
flowActions.addFlowNode,
flowActions.updateFlowNode,
flowActions.removeFlowNode,
flowActions.addFlowNodes,
flowActions.updateFlowNodes,
flowActions.removeFlowNodes
),
effect: async (action, listenerApi) => {
// debounce pattern
listenerApi.cancelActiveListeners();
await listenerApi.delay(1000);

try {
const state = listenerApi.getState();
const logic = listenerApi.extra;

// Convert our state to Node-RED format
const nodeRedFlows = logic.flow.red.toNodeRed(state);

// Update flows in Node-RED
await listenerApi.dispatch(
flowApi.endpoints.updateFlows.initiate(nodeRedFlows)
);
} catch (error) {
// Log any errors but don't crash the app
console.error('Error updating Node-RED flows:', error);

// Could also dispatch an error action if needed:
// listenerApi.dispatch(flowActions.setError('Failed to update Node-RED flows'));
}
},
});
};
Loading