Momen Docs
Go to Momen
  • Get Started
    • Introduction
    • Quick Start
    • Software Development Process
    • Editor Overview
  • Changelog
    • Latest Product Update
  • Build UI
    • Pages
    • Components
    • Canvas
    • Layout
    • Component - Display
    • Component - Input
    • Component - View
    • Component - List
    • Component - Tab View
    • Component - Select View
    • Component - Conditional View
    • Component - Others
    • Component - Map
    • Custom Component
  • Data
    • Overview
    • Data Model and Database
    • API
    • Variable
    • Parameter
    • Formula and Conditions
  • Actions
    • Overview
    • Request
    • Navigation
    • Actionflow
      • Custom Code
      • Database Trigger
    • AI
      • AI Data Model
      • AI Point
      • Vector Data Storage and Sorting
    • User Actions
    • Component Management
    • App and Page Management
    • Toast Notifications & Modal
    • Payment
    • SSO
    • Share
    • Location
    • File Management
    • QR Code
    • Clipboard
    • Conditional
    • Loop
  • Release and Growth
    • Publish Application
    • Upgrade Project
    • Multiple Clients
    • Permission
    • Log Service
    • SEO
    • Hosting Files
  • My Account and Community
    • My Wallet
    • Promoting Momen
    • Code Component
    • Collaboration
  • Debugging
    • How to Debug in Momen
    • Request Error Reference
  • Tutorial
    • How to Build an AI Needs Analysis Project?
    • How to Set Up Payment with Stripe Plugin?
    • How to Embed an Iframe Component into Your Momen Project?
    • How to Build Your Login Page?
    • How to Convert Momen App to Native Mobile App?
    • How to Build a CMS (MVP Version) in Hours?
    • How to Set a Countdown Timer When Sending a Verification Code
  • Template
    • AI Mental Health Assistant
    • Angry Dietitian
    • AI Help Center
    • AI Knowledge Base
    • SaaS Corporate Site
    • Blog
    • AI Feedback Tool
    • Feedback Tool, a Nod to Canny
    • Portfolio
    • Online Courses, a Nod to Udemy
    • Mobile Auto Repair AI Scheduler
Powered by GitBook
On this page
  • Introduction
  • Prerequisites
  • Adding Custom Code
  • Configure Custom Code
  • Configuring and Getting Inputs
  • Configuring and Returning Output
  • Running gql in a Custom Code
  • Basic Code Structure
  • runGql Parameter Description
  • Graphql Basics and Role
  • Altair Interface
  • Configuring the Request URL and Headers
  • How to View Docs
  • Requests
  • Mutation - Insert Request
  • Mutation - Update Request
  • Mutation - Delete Request
  • Running the API in a Custom Code
  1. Actions
  2. Actionflow

Custom Code

Learn to add and use custom code in Momen

PreviousActionflowNextDatabase Trigger

Last updated 1 day ago

Introduction

In this tutorial, you will learn to add and use custom code in Momen.

Prerequisites

Have a basic foundation of JavaScript, familiar with the definition of variables, functions, loops, conditional judgment, and other conventional code writing.

Adding Custom Code

Currently, the "Custom Code" in Momen's action flow only supports the JavaScript language.

If you want to write JS code to realize more complex business logic, you can add code blocks in the action flow, click the node where you want to add a code block and select the code block.

Configure Custom Code

After adding a code block, you can click on the code block to change its name. You can also directly write JS code in the code editing area on the right side. Or you can click on the Expand button in the upper right corner of the code editor to expand the code editor interface and use a bigger window to edit code.

Configuring and Getting Inputs

If you have a code block that needs to process user input (the uppermost "Input " of the action flow) or data generated by a higher-level node, you first need to have the required [Input] in the code block.

Take the example of processing cell phone number encryption:

First, configure the input parameter in the "action flow", the purpose here is to call the behavior flow on the page, you can enter parameters into the behavior flow.

Configure the input in the "Custom Code", the purpose here is to tell the code block what the specific value of the input is.

Note: The Input name has to be the same as the one in the function's parentheses that gets the Input in step 3!

To get the input parameter in "code", you need to use Momen built-in context.getArg("input parameter name"); function to get the input parameter.

Note: Names must be wrapped in semi-colonized "single quotes" or "double quotes.

const thing1 = context.getArg('thing1');
const thing4 = context.getArg('thing4');
const date2 = context.getArg('date2');
const accountId = context.getArg('accountId');
const data = { 'thing1':thing1, 'date2':date2, 'thing4':thing4
};
const gql = `mutation publishWechatMessage($data: Map_String_StringScalar,$accountId:Long!){
  publishWechatMessage(
    accountId: $accountId
    data: $data
    miniprogramState: FORMAL
    page: "pages/lil7gbne/lil7gbne"
    lang: CN
    templateId: "RQH7FafxS4_jQsRSN6ujLLKUoWuXpC3uLvYP1WL75Ys"
  )
}`;
context.runGql('publishWechatMessage', gql,{data,accountId}, { role: 'admin'});

Configuring and Returning Output

If you need to take the result of the code block to other nodes below the action flow, you need to configure the output parameter of the code block and write the code to return the parameter.

To return the Output in the Code, you need to use Momen's built-in context.setReturn("name of the Output", content of the Output); function to return the Output.

const phone_number = context.getArg('phone_number'); 
const result = `${phone_number.substring(0,3)}****${phone_number.substring(7,11)}`; 
context.setReturn('result_phone', result) ; 

Configure the output in "Custom Code", which tells the subordinate node the name and type of the output.

Note: The name of the output should be the same as the name in the context.setReturn() function in the code.

Configure the output in the action flow, the function here is to return the data in the parent node to be used by the front-end to the front-end. After this step, when the front-end page calls this action flow, there will be result data for the page to value/use.

Running gql in a Custom Code

Prerequisites: Understanding GraphQL basics below.

Basic Code Structure

// GraphQL content
const gql = `query findPaymentTransactionById ($paymentTransactionId: bigint!){
    response: payment_transaction_by_pk(id:$paymentTransactionId) {
      id
      status
      currency
      amount
      description
      order_id
      account_id
      payment_method
    }
  }`;

// Run GraphQL query
context.runGql('findPaymentTransactionById', gql, { paymentTransactionId: 1 }, { role: 'admin' });

runGql Parameter Description

context.runGql( operationName , gql , variables , permission );

  • operationName: is the name of the gql.

  • operationName: the name of the gql, it needs to be the same as the name inside the gql, e.g. the name after the query in the above gql is the name of the gql.

  • gql: the content of the gql, e.g. the request in the symbol is the result of the keystroke above the tab key in English input mode

  • variables: If gql uses a parameter declaration, the parameter cannot be null.

  • permission: Declare the role of calling gql, usually admin.

Graphql Basics and Role

Graphql is a data query language developed internally by Facebook in 2012.

The way that Momen sends requests from frontend to backend is Graphql, hereinafter referred to as gql. You can use gql to send requests to the back-end of Momen, usually used for debugging.

Implanting Graphql into ActionFlow, you can define various code blocks in Momen's actionflow to achieve complex functional requirements, such as various types of batch operations.

Altair Interface

Altair GraphQL Client is a tool for debugging gql, hereinafter referred to as Altair, download and open the interface as follows

Altair Debugging gql Configuration Content

  • Add new Adds a request.

  • Set Headers Set request headers

  • Set Request Method

  • Add a link to the request

  • Click Docs to view the request documentation.

  • Configure test parameters

  • Beautify the request code: prettify

Configuring the Request URL and Headers

  1. Go to Momen and create a new project, create a data table called reference, add the ‘content’ field to the data table, and update the backend.

  2. Go to the database, open console, click Network, clear the request, click the reference table in the database, and click Requests in Network:

  1. Copy the inner URL from the Request URL in the General under Headers and paste it into the Altair request, with the request method defaulting to POST;

  2. Copy the Authorization and its value from Request Headers in General under Headers and paste it into the Altair request header.

How to View Docs

Configure a query request for the data in the reference table, click on Docs on the right side of Altair, type in reference, you can see the requests for this table here, select the first one, you can see the left and right parameters, types, fields under this request, you can click on any of them to learn more about the request configuration.

ARGUMENTS Request Parameters: When requesting data, it's generally necessary to configure parameters such as where (conditions), order_by (sorting fields), distinct_on (deduplication of field content), offset (starting index), and limit (quantity limit).

Type Determination of Request Parameters: If there are no symbols, it is an object; if there is an [], it is an array. Specific types can also be specified (e.g., int).

Selection of Request Parameters: Clicking on a specific request parameter allows you to see what configurations can be made under that parameter. Clicking on the content allows you to see which operators (methods of evaluation) can be configured for that content.

Basic Comparison Operators (Evaluation Methods):

Equal to (_eq), is null (_is_null:true), is not null (_is_null:false)

Greater than or equal to (_gte), less than or equal to (_lte)

AND condition _and: [condition1, condition2], OR condition _or: [condition1, condition2], NOT condition _not: condition

Greater than (_gt), less than (_lt)

Contains (_in), does not contain (_nin)

Similar to (_like), not similar to (_nlike), case-insensitive similarity (_ilike)

Increment (_inc), decrement (_dec)

Sorting: Descending (desc), Ascending (asc)

TYPE: Which table

FIELDS: Which fields in this table can be requested. If the requested data includes content from related tables, you can continue to click to see how to configure conditions for related tables, and other related content.

Requests

Query Basic Scenarios

  1. According to the filter conditions, get the data in the one-to-one association table: get the personal information of the current user.

query getAccount($accountID: bigint) {
account(where: { id: { _eq: $accountID } }) {
id
profile {
id
name: ud_xingming_e1693e
gender: ud_xingbie_7644ed
phone_number: ud_shoujihaoma_e3188e
}
}
}
  1. Based on the filter conditions, get the data in the one-to-many association table: get the registration record of this event in the event table, get the media - image data.

# Request sign-up records for a specific activity
query getsign_record($activityID: bigint) {
activity(where: {}, order_by: [{}], distinct_on: [id], offset: 1, limit: 1) {
id
name
image {
url
}
sign_record(where: { activity_id_activity: { _eq: $activityID } }) {
id
activity_id_activity
ud_account_id_zhanghu_999f9c
}
}
}
  1. Request aggregated data: Search the query request for "table_aggregate" in Docs to request aggregated data for this table.

# Request aggregate information from the reference table
query getReferenceAggregate {
reference_aggregate {
aggregate {
count(columns: [id, content], distinct: true)
max {
id
}
}
}
}
  1. Requests the count of a related table to sort and displays the count of the related table, for example, to display the content of an event in descending order based on the number of registrations for the event.

# Request activity information ordered by sign-up count in descending order
query activity_order_by_sign_count {
activity(order_by: [{ sign_record_aggregate: { count: desc } }]) {
id
name
image {
url
}
sign_record_aggregate {
aggregate {
count
}
}
}
}

Query - Query Request Search for a table name in Docs, find a query request for that table, and click on it to go to the request Docs.

Adding a Request

When the mouse hovers over the top table name, on the right side you can click ADD QUERY, which will automatically populate the request code to the left side (so you don't actually have to write the gql yourself), and in the left editing area you can delete/increase the conditions, fields, and associated table content, keeping the condition you want.

Basic Structure of the Request

# Query
query commandName($argumentName1: type) {
tableName(where: {field1: { comparisonMethod: comparisonValue },
field2: { comparisonMethod: comparisonValue }
},
order_by: [{ field: sortingMethod }],
distinct_on: [distinctField],
limit: 1) {
alias: desiredReturnField
}
}

when: Used to configure request conditions and is an object.

order_by: Used to configure sorting conditions and is an array. The array contains individual objects specifying sorting criteria.

distinct_on: Used to set deduplication conditions and is an array. The array contains fields for deduplication.

limit: Used to set the number of data records to be requested and is an integer.

To tailor the returned data fields based on your needs and set request parameters:

  1. After the query's "command name," add a pair of parentheses. Inside the parentheses, provide the request parameter name and type, like this: $argumentname1: parameter type

In the editing interface, click on 【VARVARLABES】 to expand the parameter editing window. Start by entering a pair of curly braces {}. Inside the curly braces, specify the content of the parameters. The parameter names within this content should still begin with a dollar sign $. Since this parameter is an object, if you configured multiple parameters in the command name, you can set multiple parameter contents here.

To execute the request:

Click on the "send query" button located above the request. The execution of the request will then take place, and you can view the results on the right side of the interface.

Mutation - Insert Request

Search for insert_tableName in Docs, find the mutation request for that table, and click on it to go to the request Docs.

Adding a request

When hovering over the top table name, you can click ADD QUERY on the right side, which will automatically copy the request code on the left side.

Basic structure of the request


mutation commandName {
insert_tableName(
objects: [
{ data1_field1: value1, data1_field2: value2 },
{ data2_field1: value1, data2_field2: value2 }
],
on_conflict: {
constraint: constraintName,
update_columns: [updateField1, updateField2],
}
) {
# You can ignore this section; it's for more advanced users. Beginners don't need to worry about it.
whatever: anything
}
}

objects: Used to specify the data to be inserted, in the form of an array. Each item in the array represents a set of data and is structured as an object.

on_conflict: Used to determine the actions to be taken when there is a conflict in data insertion. It is an object type, and if there are no constraints, it may not need to be configured.

constraint: Specifies the name of the constraint causing the conflict.

update_columns: Specifies the fields that should be updated in the event of a conflict.

Mutation - Update Request

To search for or add an update request:

In the documentation (Docs), search for update_tableName.

Locate the mutation request associated with the table you're interested in.

Click on the specific update request to navigate to the request documentation.

Follow the same approach as described above for adding requests.

Basic structure of the request

/mutation commandName {
update_tableName(
_set: { field1: value1, field2: value2 },
where: { field1: { comparisonMethod: comparisonValue }, field2: { comparisonMethod: comparisonValue } }
) {
# You can ignore this section; it's for more advanced users. Beginners don't need to worry about it.
whatever: anything
}
}

_set: Used to define the fields and their corresponding values that need to be updated. It is of object type.

where: Used to configure the conditions for the update. It is also of object type.

Mutation - Delete Request

To search for or add a delete request:

In the documentation (Docs), search for delete_tableName.

Locate the mutation request associated with the table you're interested in.

Click on the specific delete request to navigate to the request documentation.

Follow the same approach as described earlier for adding requests.

Basic Structure of the Request:

mutation commandName {
delete_tableName(
where: { field1: { comparisonMethod: comparisonValue }, field2: { comparisonMethod: comparisonValue } }
) {
# You can ignore this section; it's for more advanced users. Beginners don't need to worry about it.
whatever: anything
}
}

where: Used to configure the conditions for deleting data. It is of object type.

Running the API in a Custom Code

Prerequisites: The API has been added to Momen and debugged successfully.

callThirdPartyApi('$operationId', $args) : Call the API after Momen configuration.

● $operationId: API id ● $args: API arguments, such as {fz_body:{"appKey": "f46dce7fa0566f0c"}}

context.callThirdPartyApi('$operationId', {"body": {"appKey": "f46dce7fa0566f0c","sign": "OTljNjYyNXXX=="}});

How to find the API id:

In Altair's Docs, enter operation in the search box, and the related request will appear. When you configure more than one API, there will be more than one request, you can click on the request to see the configuration parameters to determine which one it is.

If you encounter any issues during the process, feel free to join our for assistance.​​​

Discord community