Search code examples
node-red

Are nested If-Statements possible in Node-Red's Function Node?


Concerning the Function Node: It looks to me as if I can't use If-Elif-Else Statements inside other If's or Switch's.

Question: are nested If or Switch possible? Or is there a better way of implementing such thing in Nodered?

Example:

switch (msg.payload.auto)
{
case "Manuell":
    if (msg.payload.schattierung == "Ost")
    {
        var levelValue = "Schatten"
    }
    else if (msg.payload.schattierung == "Alle")
    {
        var levelValue = "Schatten"
    }
    else
    {
        var levelValue = "Offen"
    }

case "Auto":
    if (msg.payload.azimuth <= 225)
    {
        var levelValue = "Offen"
    }
    else if (msg.payload.azimuth < 235)
    {
        var levelValue = "Halb"
    }
    else
    {
        var levelValue = "Offen"
    }

default:
    var levelValue = "Offen"
}

var msgLevel = { payload: levelValue }

return msgLevel

Solution

  • Nested If blocks or nested Switch/If blocks will work just fine, but you can also probably build something similar with a switch node and a collection of change nodes to set the values.

    One thing to note, it's really inefficient and bad form to totally replace the incoming message with a new one in a function node. It is better to just replace the existing msg.payload. This also means that any nodes that use other keys on the msg object to keep state continue to work properly (e.g. http-response nodes needs the original message that is created by the http-in node to make it all the way down the flow to work properly)