Pular para conteúdo

VARIABLE - Manipular Variáveis

O que é este Node?

O VARIABLE é o node responsável por criar, modificar e manipular variáveis no flow, permitindo operações como set, get, increment, decrement, concatenate.

Por que este Node existe?

Flows precisam armazenar e modificar dados. O VARIABLE existe para:

  1. Armazenar valores: Criar variável com valor específico
  2. Modificar valores: Alterar variável existente
  3. Incrementar/Decrementar: Contadores (contador++)
  4. Concatenar strings: Juntar textos
  5. Calcular: Operações matemáticas básicas

Como funciona internamente?

Quando o VARIABLE é executado, o sistema:

  1. Identifica operação: set, get, increment, decrement, concatenate
  2. Executa operação na variável
  3. Atualiza context.variables
  4. Retorna novo valor

Código interno (logic-control-executor.service.ts:154-192):

private async executeVariable(parameters: any, context: any): Promise<any> {
  const { name, value, operation } = parameters;

  const currentVariables = context.variables || {};
  let newValue = value;

  switch (operation) {
    case 'set':
      newValue = value;
      break;
    case 'get':
      newValue = currentVariables[name];
      break;
    case 'increment':
      newValue = (currentVariables[name] || 0) + (value || 1);
      break;
    case 'decrement':
      newValue = (currentVariables[name] || 0) - (value || 1);
      break;
    case 'concatenate':
      newValue = (currentVariables[name] || '') + (value || '');
      break;
    default:
      newValue = value;
  }

  return {
    success: true,
    action: 'variable_updated',
    variable: {
      name: name,
      value: newValue,
      operation: operation || 'set'
    },
    timestamp: new Date().toISOString()
  };
}

Quando você DEVE usar este Node?

Use VARIABLE quando precisar manipular dados:

Casos de uso

  1. Criar variável: Definir valor inicial
  2. Contador: Incrementar tentativas, visualizações
  3. Acumulador: Somar valores
  4. Concatenar: Juntar nome + sobrenome
  5. Calcular: Operações matemáticas

Parâmetros

Campo Tipo Obrigatório Descrição
name string Sim Nome da variável
value any Depende Valor (depende da operation)
operation string Não set, get, increment, decrement, concatenate (padrão: set)

Operações Disponíveis

set - Definir Valor

{
  "name": "contador",
  "value": 0,
  "operation": "set"
}

get - Obter Valor

{
  "name": "idade",
  "operation": "get"
}

increment - Incrementar

{
  "name": "tentativas",
  "value": 1,
  "operation": "increment"
}

decrement - Decrementar

{
  "name": "estoque",
  "value": 1,
  "operation": "decrement"
}

concatenate - Concatenar Strings

{
  "name": "nome_completo",
  "value": " Silva",
  "operation": "concatenate"
}

Exemplo 1: Contador de Tentativas

{
  "name": "Contador de Tentativas",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "variable_1",
      "type": "variable",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Inicializar Contador",
        "parameters": {
          "name": "tentativas",
          "value": 0,
          "operation": "set"
        }
      }
    },
    {
      "id": "input_1",
      "type": "input",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Senha",
        "parameters": {
          "message": "Digite a senha:",
          "variable": "senha"
        }
      }
    },
    {
      "id": "variable_2",
      "type": "variable",
      "position": { "x": 700, "y": 100 },
      "data": {
        "label": "Incrementar Tentativas",
        "parameters": {
          "name": "tentativas",
          "value": 1,
          "operation": "increment"
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 900, "y": 100 },
      "data": {
        "label": "Mostrar Tentativas",
        "parameters": {
          "message": "Tentativa {{tentativas}} de 3"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 1100, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "variable_1" },
    { "source": "variable_1", "target": "input_1" },
    { "source": "input_1", "target": "variable_2" },
    { "source": "variable_2", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Resposta do Node

{
  "success": true,
  "action": "variable_updated",
  "variable": {
    "name": "tentativas",
    "value": 1,
    "operation": "increment"
  },
  "timestamp": "2025-01-15T10:30:00.000Z"
}

Boas Práticas

SIM:

  • Use nomes descritivos (tentativas, total, nome_completo)
  • Inicialize variáveis antes de usar
  • Use operation apropriada

NÃO:

  • Não use nomes genéricos (a, b, x)
  • Não incrementa sem inicializar

Dicas

💡 Inicialização: Sempre faça set com valor inicial 💡 Increment padrão: Se não passar value, incrementa 1 💡 Concatenate: Útil para construir mensagens dinâmicas 💡 Get: Retorna valor atual sem modificar

Próximo Node

ACCUMULATOR - Acumular valores → CONDITION - Usar variáveis em condições