Skip to content

User Functions

Actions are written using JavaScript, but user functions are used for JavaScript content that is used repeatedly or that requires preparation for calls such as SQL or REST.
User functions are created using the GUI, and the created functions can be called from actions.

User Function Types

Two types of user functions exist.

FunctionScope
Local Function
  • Only within an action
  • Cannot be called directly from another action.
  • Global Function
  • App
  • Available for other actions in the app.
  • Tips

    JavaScript

    JavaScript processing used repeatedly in actions can be registered as functions.

    How to create

    1. Click the "Add" button in the left panel of the Action Editor.
    2. Select "Script" from the Function Type.
    3. Enter a string of alphanumeric characters starting with any letter + underscore for the function name.
    4. Click the "Save" button.
    5. Select the function type.
    6. Displays the JavaScript function editor.
    7. Write the function process in the JavaScript editor.

    Tips

    Arguments

    Arguments will be the only param object.

    NameTypeAdd Arguments
    paramobjectnot allowed

    To get a value from arguments param in a JavaScript function, write the following in the function editor

    const input1 = param.arg1;
    const input2 = param.arg2;
    return input1 + input2;

    On the other hand, when calling a function, call it as follows

    const obj = {} ; // Create empty object
    obj.arg1 = 10;
    obj.arg2 = 20;
    myfunc(obj);

    Tips

    Sample

    Here is a sample of using a JavaScript function that adds two numbers in an action.

    Step 1

    Prepare three numeric fields and buttons that will be Arguments in the UI.

    ComponentComponent IDComponent Label
    Number Fieldnumber_field_1Number Field 1
    Number Fieldnumber_field_2Number Field 2
    Number Fieldnumber_ansResult Field
    Buttonbutton_calcCalculate button

    Step 2

    Open the button_calc action editor and Create a JavaScript function named my_func.

    [Contents of my_func]

    const input1 = param.arg1;
    const input2 = param.arg2;
    return input1 + input2;

    Step 3

    Write a call to my_func on the action board and display the result in the calculated result field.

    [Action Board Contents]

    const obj = {};
    obj.arg1 = $ui.number_field_1.value;
    obj.arg2 = $ui.number_field_2.value;
    $ui.number_ans.value = my_func(obj);

    Step 4

    Save the action and deploy the application.

    Step 5

    From the application, enter numeric values in Numeric Field 1, Numeric Field 2, and click the Calculate button. Verify that the addition result is displayed in the Calculation Result field.

    SQL

    Issue SQL to the database and retrieve the results. The SQL editor contains only SQL statements.

    Tips

    How to create

    1. Click the "Add" button in the left panel of the Action Editor.
    2. Select "SQL" from the function types.
    3. Enter a string of alphanumeric characters starting with any letter + underscore for the function name.
    4. Click the "Save" button.
    5. Displays the SQL function editor.
    6. Write SQL in the SQL editor.

    Arguments

    Arguments will be the only param object.

    NameTypeAdd Arguments
    paramObjectnot allowed

    Tips

    Asynchronous functions and await operators

    SQL functions are processed asynchronously. To wait until the value is returned, use the await operator during SQL function execution as follows.

    Return value = await SQL function

    await SQL function

    The return value of the SQL function will be an object containing the following properties

    PropertyTypeDescription
    dataobject arrayArray of ROW data in SQL results, or results of executing a DML statement
    sqlStatestringSQLSTATE value
    errorCodestringError code
    errorMessagestringError message

    Tips

    About Transaction Control

    Transactions are action units.
    If there are multiple SQL function calls in an action, all will roll back if any one exception occurs. Commit only when all SQL function calls succeed. Commit and rollback are implicit. All rollbacks occur even if throw new Error(); is called by the user description in the action. However, if an exception is caught with a try-catch statement, the calling action will not supplement the exception unless throw is performed in the catch clause, so no rollback will be performed.

    Sample

    The following is an example of issuing a SQL SELECT to a table in an action and displaying the results as a JSON string in a textarea component.

    Step 1

    Prepare a textarea component that displays the results in the UI and a button that executes the action.

    ComponentComponent IDComponent Label
    textareatext_area_1Result JSON
    buttonbutton_sqlSELECT

    Step 2

    Create a table named t1 in a database named mydb with the following configuration.

    Column nameData typeMDfspPKNNUQAI
    idINTTrueTrue
    nameVARCHAR20

    Store the data for testing from the Data tab of the column.

    idname
    1a
    2b

    Step 3

    Open the button_sqlaction editor and create an SQL function named sql1.

    [Contents of sql1]

    select * from mydb.t1;

    Step 4

    Write SQL function calls on the action board to display the results of data acquisition in a text area.

    Tips

    [Action Board Contents]

    const obj = await sql1();
    $ui.text_area_1.value = JSON.stringify(obj.data);

    Step 5

    Save the action and deploy the application.

    Step 6

    Click the SELECT button from the application. Verify that the SQL SELECT results are displayed in JSON format in the Results JSON text area.

    [{"id":1,"name":"a"},{"id":2,"name":"b"}]

    REST

    REST functions are functions for calling the REST API or Amazon API Gateway.

    How to create

    1. Click the "Add" button in the left panel of the Action Editor.
    2. Select "REST" from the function type.
    3. Enter a string of alphanumeric characters starting with any letter + underscore for the function name.
    4. Click the "Save" button.
    5. Displays the REST function editor.
    6. Configure the REST editor to call the REST API.

    Basic Settings

    ParametersDescription
    Function nameThe name set when the function was created is displayed.
    ArgumentsArgument is the only param object, as are other user functions.
    MethodDepending on the API to be called, choose from the following
    • GET
    • POST
    • PUT
    • PATCH
    • DELETE
    URLFill in the REST API URL.
    You can embed parameter values at any point using the following format.
    ${param.property_name}
    Request headersSet the request header.
    Click the "Add" button to add a header name and value entry. Typical header names are available as options, but they can also be entered arbitrarily.
    Request bodyFor the POST/PUT/PATCH/DELETE method, request body can be specified. The input format changes depending on the Conent-Type specified in the header.
    Binary acquisitionThe return value of the response is a string, but for services that return binaries, check this box to obtain the return value as a Buffer object.

    Request headers

    Request headers are set from the [Headers] tab. The request header is provided as an option, but can also be entered directly.

    Header nameValue
    Accept
  • /
  • application/
  • audio/
  • image/
  • text/
  • Accept-Charset
  • utf-8
  • Accept-Encoding
  • compress
  • deflate
  • gzip
  • Accept-Language
  • en-US
  • ja
  • Authorization
    Cache-Control
  • max-age=3600
  • no-cache
  • no-store
  • Connection
  • close
  • keep-alive
  • Content-Length
    Content-Type
  • application/json
  • application/octet-stream
  • application/x-www-form-urlencoded
  • application/xml
  • multipart/form-data
  • text/css
  • text/html
  • text/plain
  • Content-Length
    Cookie
  • name=value
  • name=value; name2=value2; name3=value3
  • Date
  • Wed, 21 Oct 2015 07:28:00 GMT
  • Expect
  • 100-continue
  • From
  • webmaster@example.org
  • Host
    Proxy-Authorization
    Refererhttps://example.com/
    User-Agent
    X-Amz-Content-Sha256
    X-Amz-Date
    X-Amz-Security-Token
    X-API-Key

    Tips

    Request body

    The request body is set from the [Body] tab. The input format changes depending on the Content-Type specification in the request header.

    Content-Type of the request headerInput FormatInput details
    application/jsontextareaText
    application/octet-streamtext fieldFile path
    application/x-www-form-urlencoded"Add" button
    Text field (name)
    Text field (value)
    Parameter name
    Parameter value
    application/xmltextareatext
    multipart/form-data"Add Text Part" button
    "Add File Part" button
    Text field (name)
    Text field (value)
    Parameter name
    Parameter value
    text/csstextareatext
    text/htmltextareatext
    text/plaintextareatext

    Asynchronous functions and await operators

    REST functions are processed asynchronously. To wait for the value to return, use the await operator during REST function execution as follows

    Return value = await REST function

    Return value

    The return value of the REST function will be an object containing the following properties.

    PropertyTypeDescription
    statusobjectHTTP Status Object
    Property Type
    codenumber
    text string
    headersobjectResponse header
    bodystring | BufferResponse
    errorMessagestringEror message

    Sample

    The following is an example of calling a GET type REST API (one parameter) in an action and displaying the result as a JSON string in a textarea component.

    Tips

    ParameterJSON string
    URLhttps://bl2dqouo8g.execute-api.ap-northeast-1.amazonaws.com/dev/res1?name=string
    API keybcVrf52Wvs3jAKMFYOK596hlLsTtmczH5tTCjQxI

    Step 1

    Prepare text fields, text areas, and buttons in the UI.

    ComponentComponent IDComponent Label
    Text fieldtext_field_nameName
    textareatext_area_responseResponse
    Buttonbutton_restREST API

    Step 2

    Open the button_rest action editor and Create a REST function named my_rest.

    [Basic settings for my_rest]

    Function namemy_rest
    Argumentsparam
    MethodGET
    URLhttps://bl2dqouo8g.execute-api.ap-northeast-1.amazonaws.com/dev/res1?name=${param.name}
    Request headerName- X-API-Key
    Value-bcVrf52Wvs3jAKMFYOK596hlLsTtmczH5tTCjQxI
    Binary acquisitionUnchecked

    Step 3

    Write a call to the REST function on the action board and display the response in a text area.

    Tips

    [Action Board Contents]

    const encoded_name = encodeURIComponent($ui.text_field_name.value);
    const obj = {name: encoded_name};
    const ret = await my_rest(obj);
    $ui.text_area_response.value = ret.body;

    Step 4

    Save the action and deploy the application.

    Step 5

    From the application, enter any string in the “Name” text field and click the "REST API" button. Confirm that the "Hello input string" appears in the [Response] text area.

    (Ex:) Hello World!

    Sample of calling asynchronous functions with synchronous JavaScript functions

    When calling asynchronous functions (SQL functions, REST functions, built-in functions such as $fn.getFile, etc.) in JavaScript functions, they must be returned as Promise objects as shown in the sample. In the following executeScript function, examples of executing REST functions, SQL functions, JavaScript functions, and built-in functions and returning the results are described.
    The action board contains an example of setting the result returned from the executeScript function to the value of each table component.

    Action Board

    {const { books, tasks, plans, files } = await executeScript();}
    // Books
    $ui.books.value = books.map((book) => ({
    bookTitle: book?.volumeInfo?.title,
    bookPublisher: book?.volumeInfo?.publisher,
    bookPublishedDate: book?.volumeInfo?.publishedDate,
    }));
    // Tasks
    $ui.tasks.value = tasks;
    // Plans
    $ui.plans.value = plans.map((plan) => ({
    planId: plan.id,
    planName: plan.name,
    }));
    // Files
    $ui.files.value = files.map((fileName) => ({ fileName }));

    JavaScript Function: executeScript(Function type: Synchronous)

    const execute = async () => {
    // REST function call
    const sendResult = await sendGetBooksRequest();
    const body = JSON.parse(sendResult.body);
    const books = body.items;
    // SQL Function Call
    const selectResult = await selectTaskRecords();
    const tasks = selectResult.data;
    // JavaScript Function Call
    const plans = getPlans();
    // Built-in function call
    const files = await $fn.getFileNames("/");
    return {
    books,
    tasks,
    plans,
    files,
    }
    }
    // Returns a Promise object
    return execute();

    JavaScript Function: getPlans(Function type: Synchronous)

    return [
    {
    name: "Plan1",
    id: "p001",
    },
    {
    name: "Plan2",
    id: "p002",
    },
    {
    name: "Plan3",
    id: "p003",
    },
    ];