Problem saving/restoring msg in subflow - what am I doing wrong?

Hey all,

I've got a subflow that does a database query to set some global context that I want to call in the middle of a another flow but I don't want the original msg object to get changed in the subflow.

Basically I want the msg that I sent into the subflow to be returned unaltered at the end of the subflow.

I've tried to save the msg to the flow context with flow.set("saved_msg",msg); and then restore the original msg with return flow.get("saved_msg"); but this doesn't seem to work.

I tried it with msg.payload and could successfully save/restore this, but it doesn't work with the msg object for some reason.

What am I missing? Is there a best practice way of saving the current msg context in a subflow?

The example below is a simplified version that illustrates my problem.

[{"id":"36c20be7.7b0104","type":"subflow","name":"Subflow 1","info":"","in":[{"x":40,"y":80,"wires":[{"id":"92d717b4.deaa08"}]}],"out":[{"x":820,"y":80,"wires":[{"id":"f215c528.b58038","port":0}]}]},{"id":"92d717b4.deaa08","type":"function","z":"36c20be7.7b0104","name":"Save Context","func":"\nflow.set(\"saved_msg\", msg);\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":200,"y":80,"wires":[["a2ac9d4e.12504"]]},{"id":"a2ac9d4e.12504","type":"function","z":"36c20be7.7b0104","name":"Do Something","func":"msg.payload = \"payload has been changed\";\nmsg.topic = \"topic has been changed\";\nmsg.somevariable = null;\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":410,"y":80,"wires":[["f215c528.b58038"]]},{"id":"f215c528.b58038","type":"function","z":"36c20be7.7b0104","name":"Restore Context","func":"// create a new message with the saved msg object\nvar newMsg = flow.get(\"saved_msg\");\n\n// return the new (restored) message\nreturn newMsg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","x":620,"y":80,"wires":[[]]},{"id":"3b90942f.8823cc","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"a47a4936.e574a8","type":"subflow:36c20be7.7b0104","z":"3b90942f.8823cc","name":"","env":[],"x":620,"y":340,"wires":[["51031ef6.46d64"]]},{"id":"709de5b4.346c4c","type":"inject","z":"3b90942f.8823cc","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"},{"p":"somevariable","v":"Some variable set","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"My original topic","payload":"My original payload","payloadType":"str","x":340,"y":340,"wires":[["a47a4936.e574a8","51031ef6.46d64"]]},{"id":"51031ef6.46d64","type":"debug","z":"3b90942f.8823cc","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":770,"y":420,"wires":[]}]

Thanks for helping!

Could you use a change node to set msg.savedpayload to msg.payload at the start of the subflow, and then the reverse at the end?

Yeah, I can save/restore msg.payload but not the entire msg object.