How to reference context based on topic (without using function node)?

#1

Basically I'm wondering if there's a way to do the equivalent of flow.set(msg.topic,"foo"); in a Change node and switch(flow.get(msg.topic)) in a Switch. I've tried variations of $(x) , $.x , {{x}}, and [x] with no luck.

Note that I am not trying to save the topic to flow.foo. I'm trying to save "foo" to flow.[msg.topic]

Ultimately it doesn't matter since I can just use a function, but it seems like it would be a common-enough use case for the basic nodes to handle.

0 Likes

#2

I don't think there is.

It would require some kind of "templating" in common input fields much like we currently get for environment variables.

0 Likes

#3

I only was able to workout a partial workaround solution.

In this example flow it is injected:

msg.payload = foo
msg.topic  = alarm

The change node uses a jsonata expression to create the object {alarm : msg.payload} and have it stored in flow.sta

The function node will read to the object msg the object flow.sta

Flow:

[{"id":"35baa7cd.9b2f08","type":"tab","label":"Flow 4","disabled":false,"info":""},{"id":"5ae8597e.4bdc08","type":"debug","z":"35baa7cd.9b2f08","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":690,"y":120,"wires":[]},{"id":"42343f37.f095a","type":"inject","z":"35baa7cd.9b2f08","name":"","topic":"alarm","payload":"foo","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":160,"y":120,"wires":[["df81e676.991df8"]]},{"id":"df81e676.991df8","type":"change","z":"35baa7cd.9b2f08","name":"","rules":[{"t":"set","p":"#:(memoryOnly)::sta","pt":"flow","to":"$.{topic : payload}","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":350,"y":120,"wires":[["f7335a43.eb7498"]]},{"id":"f7335a43.eb7498","type":"function","z":"35baa7cd.9b2f08","name":"read flow.sta","func":"\nmsg = flow.get(\"sta\",\"memoryOnly\");\nreturn msg;","outputs":1,"noerr":0,"x":520,"y":120,"wires":[["5ae8597e.4bdc08"]]}]

r-01

1 Like

#4

Haha, I wondered if someone would come up with that. I decided not to include it since the Riven5 was looking for something simpler than a function node and the danger with JSONata (though I like it) is that it can be hard to parse 6 months down the line. :slight_smile:

0 Likes

#5

That's an interesting solution I hadn't considered. I agree with @TotallyInformation that it could be confusing 6 months later, but it does the trick in a one-liner, seems to work fine with a variety of nodes, and I can retrieve it at the other end with $flowContext('sta.'&topic) . I'm going to go ahead and mark this solved. Thanks.

2 Likes

#6

Slight revision. Since this is setting the whole object each time, it overwrites any other topics that have been previously saved. Need to do this instead:

$merge([$flowContext("sta"),{$.topic: payload}]) 

At which point I'm leaning towards just returning to the original function.

0 Likes