# Code

## Actions: Uso del nodo "Code" en Dapta

### Caso de uso

Obtener un dato ingresado desde un trigger y transformarlo mediante lógica JavaScript personalizada en un flujo automatizado.

{% embed url="<https://www.loom.com/share/6600a103b53749f893f081356d67938b?sid=e6ea0799-8d0f-42a7-b4ea-4d1a6dc6ec0d>" %}

***

### ✅ ¿Qué es el nodo "Code"?

Es una acción nativa de Dapta que te permite escribir lógica en JavaScript directamente dentro del flujo. Este nodo es útil para transformar datos, aplicar condiciones, sumar valores, generar fechas, entre muchas otras funciones personalizadas.

***

### 🎯 ¿Qué vas a lograr?

En este ejemplo, aprenderás a recibir un número desde el nodo trigger, sumarle un valor y exportar ese resultado para reutilizarlo en otros nodos del flujo. También verás cómo obtener la hora actual usando código.

***

### 🧭 Paso a paso para configurar el nodo

#### 1. Crea el flujo y añade el nodo "Code"

* Abre Flow Studio en Dapta.
* Crea un nuevo flujo o usa uno existente.
* Añade el nodo "Code" desde la sección de Actions.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeyT_mmlYxD3UOQWOcd1HTsw7dd_EfzzM1IVpwxQ7jtgSshiuAUkvWi1-5-JB5sNPAmUpkiGmmgAtwnIr0c7IgNxnxRfkDEdGMKUwGHknFgiutzbdr0a7TXtkFXKCrXYGGC-YHNkA?key=yDxfMdsnAqL1hX97DQZheA" alt=""><figcaption></figcaption></figure>

2\. Define el trigger de entrada

* Configura el método como POST.
* En el body, define un parámetro llamado numero.
* * Ejemplo: { "numero": "1" }
* Este será el valor que se manipulará desde el nodo de código.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcG0qv-5K2axHsgBNJBS1Utm6nG8ge4YQnODVZU5EABLe5OyPQwDQ5YpmxhvY2gZRJ6UbWJYwN3GNcTW8DU_dfB4dIEirtkOGF0wcRyiPSTAzbW1h0DIhnKouQIDgHAHP8Xn6f0pA?key=yDxfMdsnAqL1hX97DQZheA" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeT0Vu1dTRgjG9E1ONUdDVDU3LXnNThxqbxA-d9UR3V1TUIurL4HEyZqm_SrQAjLVJdAoi5vKlHhNpJDL9VIIL1vJO1m_kQq7is5zXCyM_kY116xXHxGaa9WohRM9lkMHxhVtPvOA?key=yDxfMdsnAqL1hX97DQZheA" alt=""><figcaption></figcaption></figure>

3\. Configura el nodo Code

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXe1cj18sT08kXqBLST_FTJN7ayRysvc-N1tdXHYtSw1PI9U8HrqdGJ-RjA-KWAHW8LGiRh9W9O_fAb7fXMbRxuTNX1zlXiK7eW7Fh3vOrCFWI1u8q4zJbuSdQV7mJfo2GhqAx8S6g?key=yDxfMdsnAqL1hX97DQZheA" alt=""><figcaption></figcaption></figure>

**A. Accede a los datos de entrada:**

const numero = params.trigger.body.numero;

params permite acceder a la información proveniente de cualquier nodo anterior del flujo. En este caso, usamos trigger.body.numero.

**B. Convierte el valor a número:**

Number(numero\_input)

Es importante convertirlo porque los datos ingresados por body suelen llegar como texto (string).

**C. Aplica la lógica que necesites:**

function suma (numero\_input) {\
return Number(numero\_input) + 2

}

const resultado = suma(numero)

**D. Exporta el valor:**

module.exports = { resultado };

Así podrás usar este resultado en otros nodos del flujo.

***

### 🕒 Bonus: Exportar la hora actual

Puedes agregar también esta línea al final para exportar la hora actual:

function getCurrentDateTimeInBogota() {

const bogotaTime = new Date().toLocaleString('en-US', { timeZone: 'America/Bogota' }); const date = new Date(bogotaTime); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); return \`${year}-${month}-${day} ${hours}:${minutes}:${seconds}\`;

}

const bogotaTime = getCurrentDateTimeInBogota();

***

### 💡 Buenas prácticas

* Siempre valida si los valores entrantes son texto antes de operar con ellos.
* Usa funciones para encapsular lógica reutilizable.
* Exporta sólo los valores que vayas a usar después en el flujo.
* Si estás trabajando con datos sensibles, considera usar variables de entorno.

***

#### 4. Respuesta Añadir un nodo de “response” ayuda a controlar la salida de la información

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXetkOAzBTLb38ED3DNg0o9fFT-8f65wayPdGBWrWsYRIiUOs8G9ReFkyTA8tU2taz9occyZWS2t7IDhrTUDt-X_QfebehUATGUy1QtsBk5q9U-oV571rsorqiP0i6cM_-UuBTtSrQ?key=yDxfMdsnAqL1hX97DQZheA" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdicT579E8heY05pJfR9NvMC5iI3SCEB9rvsLvbxumvUVPbI9hxbVRl94hbKxS3xifSZHHZZPGSMuBnmT5pRCeycRXBWbcUaIkqQJAqI1hd9GQ5usbXT6P5o2XF1A4OlMh2Zj9_?key=yDxfMdsnAqL1hX97DQZheA" alt=""><figcaption></figcaption></figure>

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.dapta.ai/dapta-docs-es/actions/code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
