Synchra.24
menu_bookDocumentation
Practical guides for setup and development

Find guides for getting started, building workflows and adding your own tools to your company workspace.

folderAutomation

JavaScript handler

How to write transform(input, context), verify data, keep logs, and transform responses from external systems.

Machine translation

The handler translates the data between the source and destination. It is suitable when external systems use different field names, structures, value types, or formats.

The code is stored separately from the automation configuration in the tab The handler.

Button Format JavaScript it indents and aligns the handler code in the editor panel. If there is a syntax error, the source text is saved and a message with the reason appears. To save the changes, click Check and save.

It is enough to enable JavaScript conversion in the configuration.:

transform:
  type: javascript
  timeout_seconds: 2

Required function

The script should declare a regular synchronous function. transform:

function transform(input, context) {
  return input;
}
Argument Content
input Data obtained from a source or sources and already parsed according to response.format.
context Service information about the launch.

The return value becomes the result of the handler and is passed to the destination. Return data that can be represented in JSON: an object, an array, a string, a number, a boolean value, or null.

The handler is executed synchronously. Do not use async, Promise or waiting for external operations.

What is in the input

One source

During configuration source + destination in input The source's response is immediately found:

function transform(input, context) {
  return {
    employees: input.items,
    importedAt: context.started_at
  };
}

Multiple sources

When using steps in input the object is located. His keys match with id source steps:

steps:
  - id: employees
    kind: source
    # ...
  - id: departments
    kind: source
    # ...
function transform(input, context) {
  return {
    employees: input.employees,
    departments: input.departments
  };
}

Learn more about distributing the result between multiple assignments: Multiple sources and destinations.

context

For a regular launch, the following options are available:

Field Appointment
provider_id Company ID in Synchra24.
run_id Launch ID. It is convenient for comparison with the launch log.
started_at Start time in ISO 8601 format.
artifacts The values of the connected JSON artifacts by alias; an empty object if there are no connections.

During the test run, instead of run_id transmitted test: true.

function transform(input, context) {
  console.info("Режим проверки:", context.test === true);
  return input;
}

Example: renaming and filtering fields

function transform(input, context) {
  if (!Array.isArray(input.items)) {
    throw new Error("Источник не вернул массив items");
  }

  return input.items
    .filter(function (item) {
      return item.active === true;
    })
    .map(function (item) {
      return {
        externalId: String(item.id),
        fullName: [item.last_name, item.first_name, item.middle_name]
          .filter(Boolean)
          .join(" "),
        phone: item.phone || null,
        department: item.department_name || "Без отдела"
      };
    });
}

Example: XML from 1C

The XML is converted to a JavaScript object before the function is run. The same XML element can become an object or an array: it depends on the number of elements in the response. It is convenient to immediately cast the value to an array.

function asArray(value) {
  if (value == null) return [];
  return Array.isArray(value) ? value : [value];
}

function transform(input, context) {
  var rows = asArray(input.CommercialInformation.Document);

  return rows.map(function (document) {
    return {
      number: String(document.Number || ""),
      date: document.Date,
      amount: Number(document.Amount || 0),
      currency: document.Currency || "RUB"
    };
  });
}

The features of Windows-1251 XML, attributes, and encoding are described in the section Data formats.

Example: numbers from CSV

CSV values are received as strings. Convert the numbers explicitly and consider the comma as a decimal separator if the source uses it.

function toNumber(value) {
  var normalized = String(value || "0")
    .replace(/\s/g, "")
    .replace(",", ".");
  var result = Number(normalized);
  return Number.isFinite(result) ? result : 0;
}

function transform(input, context) {
  return input.map(function (row) {
    return {
      employeeId: row.employee_id,
      workedHours: toNumber(row.worked_hours),
      amount: toNumber(row.amount)
    };
  });
}

Example: different data for two appointments

The handler can return the object, and the destination steps can select the necessary parts from it.:

function transform(input, context) {
  var employees = input.employees || [];

  return {
    hrPayload: {
      employees: employees
    },
    analyticsPayload: {
      employeeCount: employees.length,
      generatedAt: context.started_at
    }
  };
}
- id: send_to_hr
  kind: destination
  input: ${transform.output.hrPayload}
  # ...

- id: send_to_analytics
  kind: destination
  input: ${transform.output.analyticsPayload}
  # ...

Handler logs

Four levels can be used during the test run:

function transform(input, context) {
  console.log("Получено записей:", Array.isArray(input) ? input.length : 1);
  console.info("Запуск:", context.started_at);
  console.warn("Пустые телефоны будут пропущены");

  if (!input) {
    console.error("Источник вернул пустой ответ");
    throw new Error("Нет данных для обработки");
  }

  return input;
}

Logs are displayed in a separate block as a result of verification. Up to 200 messages are saved per launch, each with up to 4,000 characters. Do not log tokens, passwords, personal data, or complete responses from external systems.

Errors and input validation

Stop processing with a clear message if the data does not match the expected structure.:

function transform(input, context) {
  if (!input || !Array.isArray(input.orders)) {
    throw new Error("Ожидался объект с массивом orders");
  }

  var invalid = input.orders.find(function (order) {
    return !order.id;
  });

  if (invalid) {
    throw new Error("У одной из записей отсутствует order.id");
  }

  return input.orders;
}

This message will be visible in the test run and the launch log.

Limitations of the environment

  • The size of the script is from 1 byte to 256 KB.
  • The execution time is from 1 to 5 seconds, the default is 2 seconds.
  • There is no access to the network and file system from JavaScript.
  • Unavailable fetch, XMLHttpRequest, require, import, process and Deno.
  • External requests are described in source, destination or steps, and are not executed from the handler.
  • Secret variables are not passed to JavaScript. Insert them into the URL and configuration headers.

AI Agent's Help

In the handler editor, you can enable the AI agent and describe the transformation in plain text, for example:

From the array input.orders keep only the paid orders. Rename it client_id in customerId, convert the amount to a number, and the date to ISO 8601.

The agent will suggest a function and show the changes before insertion. Check the names of the fields, the handling of empty values, and the result via Test launch. The code gets into the editor only after confirmation. This feature is available if an AI agent is enabled in the company's license.

Recommendations

  1. Make the function small and deterministic: the same input should produce the same result.
  2. Check the required fields before conversion.
  3. Do not change the original object unnecessarily — collect a new result through map.
  4. First, test the function on a small amount of data.
  5. Log the number and stage of processing, not the contents of secret or personal fields.

Artifact Data

Connect the names in YAML: artifacts: {settings: service.settings}. The following values are available in the synchronous function context.artifacts.settings, including arrays, objects, and null. Network request and await They are not needed. This is the data at the start of the startup; changing the JavaScript object does not save it or change the substitution of other stages. For recording, return the result to the destination type: artifact. A missing connected artifact stops the startup before the handler. Full example and limitations.

Handler in a portable ZIP template

Exporting a ZIP from the editor header includes the current JavaScript in a separate transform.js along with the configuration and metadata. The file is not executed during import; the creation server checks its syntax if JavaScript transform is enabled. The new automation is always turned off. Secret values are not unloaded from the storage, but the literals inside the code are saved unchanged. Package format and installation.