Skip to content

YuzeScript

What is YuzeScript?

YuzeScript is a JavaScript-based scripting language for writing custom logic in Yuze. It runs on the V8 engine and supports modern JavaScript features including async/await.

YuzeScript is used in:

  • Workflow steps: Process and transform datapoints with custom logic
  • Schema Mapping Expressions: Calculate field values during data transformation
  • API Connectors: Handle incoming HTTP requests and produce datapoints

The editor provides IntelliSense with type definitions based on your schemas, making it easier to write correct code.

YuzeScript in Workflow Steps

In a workflow step, YuzeScript lets you write custom processing logic.

Available globals: context (consume/produce/yuzecase), yuze (master data helpers), and console (logging).

source, target, and request are not available here. There is no HTTP client or fetch — outbound API calls are handled by connectors, not workflow scripts.

context.consume

Retrieves all datapoints from the consumed feed. Takes no arguments, returns an array matching the input feed schema.

javascript
const datapoints = await context.consume();

for (const dp of datapoints) {
  console.log(dp.EquipmentId);
}

context.produce

Writes datapoints to the produced feed. Accepts a single object or an array.

javascript
await context.produce({
  EquipmentId: 'PUMP-001',
  Status: 'Active'
});

// Or multiple datapoints
await context.produce([
  { EquipmentId: 'PUMP-001', Status: 'Active' },
  { EquipmentId: 'PUMP-002', Status: 'Inactive' }
]);

context.yuzecase

Identifies the current YuzeCase instance. Useful for logging or conditional logic.

javascript
console.log(context.yuzecase.Id);    // UUID string
console.log(context.yuzecase.Name);  // YuzeCase name

Complete Workflow Step Example

javascript
const datapoints = await context.consume();

const results = datapoints.map(dp => ({
  ...dp,
  processed: true,
  processedAt: new Date().toISOString()
}));

await context.produce(results);

Enriching with Master Data

When looking up master data for each item, use a for loop instead of .map() because each iteration requires await:

javascript
const items = await context.consume();
const enriched = [];
for (const item of items) {
  const ref = await yuze.createExternalMasterDataItemReference('Equipment', 'SAP', item.EquipmentId);
  const equipment = await yuze.lookupMasterDataItem(ref);
  enriched.push({
    ...item,
    EquipmentName: equipment?.displayName || 'Unknown'
  });
}
await context.produce(enriched);

YuzeScript in Schema Mappings

In schema mapping expressions, YuzeScript calculates field values during data transformation. You work with source (input data) and assign values to target fields.

Available globals: source (read-only input), target (writable output), yuze (master data helpers), and console (logging).

context and request are not available here. Only explicitly mapped fields assigned to target appear in the output.

source

The input data being transformed. Contains all fields from the source schema (read-only).

javascript
console.log(source.FirstName);  // 'John'
console.log(source.LastName);   // 'Doe'
console.log(source.Address.City);

target

The output data structure. Assign values to target properties to set the output fields.

javascript
target.FullName = source.FirstName + ' ' + source.LastName;
target.ProcessedAt = new Date().toISOString();

Complete Schema Mapping Example

javascript
target.FullName = source.FirstName + ' ' + source.LastName;
target.Address = [source.Street, source.City, source.Country].filter(Boolean).join(', ');
target.Priority = source.Severity > 7 ? 'High' : 'Low';

YuzeScript in API Connectors

API connectors use YuzeScript to handle incoming HTTP requests and produce datapoints.

Available globals: request (incoming HTTP request), context.produce() (write datapoints), yuze (master data helpers), and console (logging).

context.consume(), source, and target are not available here.

request

The incoming HTTP request object:

  • request.method — HTTP method ('POST', 'GET', etc.)
  • request.headers — Object with header names as keys
  • request.query — Query parameters from the URL
  • request.path — URL path after connector base URL
  • request.body — Parsed body. JSON is parsed natively. XML is auto-converted to JSON: all values become strings, single child elements are objects (not arrays), attributes become @name, text content becomes #text.
  • request.bodyRaw — Raw unparsed body string. Use when you need the exact original text or when the auto-converted JSON shape is not suitable.
javascript
console.log(request.method);              // 'POST'
console.log(request.headers['content-type']);
console.log(request.query.status);        // query parameter
console.log(request.path);                // URL path after connector base URL
console.log(request.body);                // parsed body (JSON or XML-to-JSON)
console.log(request.bodyRaw);            // raw unparsed body string

response (Return Value)

Return an object { status, body?, headers? } to define the HTTP response.

javascript
return {
  status: 200,
  body: { success: true }
};

// Error response
return {
  status: 400,
  body: { error: 'Invalid request' }
};

// With custom response headers
return {
  status: 200,
  body: { ok: true },
  headers: { 'X-Request-Id': request.headers['x-request-id'] || 'none' }
};

context.produce (API Connector)

Writes datapoints to the configured feed.

javascript
await context.produce(request.body);

Complete API Connector Example

javascript
await context.produce(request.body);

return {
  status: 200,
  body: { success: true }
};

Built-in Functions

The yuze object provides helper functions available in all contexts.

yuze.createExternalMasterDataItemReference

Creates a reference to a master data item from an external system.

javascript
const ref = await yuze.createExternalMasterDataItemReference(
  'Equipment',  // type
  'SAP',        // source system
  'PUMP-001'    // source ID
);
// Returns: 'master-data-ext:Equipment:SAP:PUMP-001'

yuze.createInternalMasterDataItemReference

Creates a reference to an internally managed master data item.

javascript
const ref = await yuze.createInternalMasterDataItemReference(
  'Location',   // type
  'SITE-A'      // ID
);
// Returns: 'master-data:Location:SITE-A'

yuze.lookupMasterDataItem

Retrieves a master data item by its identifier. Returns null if not found.

javascript
const item = await yuze.lookupMasterDataItem('master-data:Equipment:PUMP-001');

if (item) {
  console.log(item.displayName);
  console.log(item.properties.Status);
  console.log(item.mappingIdentifiers.SAP[0]);
}

yuze.searchMasterDataItems

Searches for master data items with filters. Returns paginated results with a continue token for fetching additional pages.

Parameters:

  • query: Search criteria
    • type: Master data type to search
    • onlyRootItems: (optional) Filter to only root items
    • metadata: (optional) Filter by metadata field values
  • pagination: Pagination options
    • pageSize: Number of items per page
    • nextPageToken: (optional) Token from previous result for next page

Returns: CursorPagingResult<MasterDataItem>

  • items: Array of matching master data items
  • nextPageToken: Token for fetching the next page (undefined if no more pages)

Basic Example

javascript
const result = await yuze.searchMasterDataItems(
  {
    type: 'Equipment',
    onlyRootItems: true,
    metadata: { Status: 'Active' }
  },
  { pageSize: 50 }
);

for (const item of result.items) {
  console.log(item.displayName);
}

Paginating Through All Results

Use a do-while loop to fetch all pages using the nextPageToken:

javascript
let nextPageToken = undefined;

do {
  const result = await yuze.searchMasterDataItems(
    {
      type: 'Equipment',
      metadata: { Status: 'Active' }
    },
    {
      pageSize: 100,
      nextPageToken: nextPageToken
    }
  );

  for (const item of result.items) {
    console.log(`Processing: ${item.displayName}`);
  }

  nextPageToken = result.nextPageToken;
} while (nextPageToken);

yuze.lookupMasterDataItemSystemKey

Gets the external system identifier for a master data item.

javascript
const sapId = await yuze.lookupMasterDataItemSystemKey(
  'master-data:Equipment:PUMP-001',
  'SAP'
);
// Returns: 'SAP-PUMP-001' or null

yuze.saveMasterDataItem

Creates or updates a master data item.

javascript
await yuze.saveMasterDataItem({
  identifier: 'master-data-ext:Equipment:SAP:PUMP-001',
  displayName: 'Main Cooling Pump',
  parentId: 'master-data:Location:PLANT-A',
  properties: {
    SerialNumber: 'SN-12345',
    Status: 'Active'
  },
  mappingIdentifiers: {
    SAP: ['10001234']
  }
});

yuze.sha256Hash

Calculates a SHA-256 hash. Useful for deduplication.

javascript
const hash = await yuze.sha256Hash({ id: 123, name: 'Test' });
// Returns: 64-character hex string

Console Logging

Standard console methods are available and captured in execution logs:

javascript
console.log('Processing started');
console.warn('Missing optional field');
console.error('Failed to process item');
MethodLog Level
console.log()Information
console.warn()Warning
console.error()Error

Error Handling

Script errors include line numbers and stack traces. Use try-catch for graceful error handling:

javascript
try {
  const item = await yuze.lookupMasterDataItem(identifier);
  if (!item) {
    console.warn(`Item not found: ${identifier}`);
    return null;
  }
  return item.properties;
} catch (error) {
  console.error(`Lookup failed: ${error.message}`);
  throw error;
}

Tips

  • Use async/await: All yuze functions and context methods are asynchronous
  • Check for null: Lookup functions return null when items are not found
  • Use console.log: Debug your scripts by logging intermediate values