Help Center/ FunctionGraph/ devg/ Node.js/ Developing an Event Function
Updated on 2024-11-11 GMT+08:00

Developing an Event Function

Function Syntax

You are advised to use Node.js 12.13.

  • Node.js 6.10

    Use the following syntax when creating a handler function in Node.js 6.10:

    export.handler = function(event, context, callback)

    • handler: name of the function that FunctionGraph invokes to execute your code. The name must be consistent with that you define when creating a function.
    • event: event parameter defined for the function. The parameter is in JSON format.
    • context: runtime information provided for executing the function. For details, see SDK APIs.
    • callback: used to return the defined err and message information to the frontend. The general syntax is callback(err, message). You can define the error or message content, for example, a character string.
    • Function handler: index.handler.

      The function handler is in the format of [File name].[Function name]. For example, if you set the handler to index.handler in your function, FunctionGraph will load the handler function defined in the index.js file.

  • Node.js 8.10, Node.js 10.16, Node.js 12.13, Node.js 14.18, Node.js 16.17, and Node.js 18.15

    Node.js 8.10, Node.js 10.16, Node.js 12.13, Node.js 14.18, Node.js 16.17, and Node.js 18.15 are compatible with the APIs of Node.js 6.10, and supports an async handler.

    exports.handler = async (event, context, callback [optional]) => { return data;}

    Responses are output through return.

Node.js Initializer

FunctionGraph supports the following Node.js runtimes:

  • Node.js6.10 (runtime = Node.js6)
  • Node.js8.10 (runtime = Node.js8)
  • Nodejs10.16(runtime = Node.js10)
  • Nodejs12.13(runtime = Node.js12)
  • Node.js14.18(runtime = Node.js14)
  • Node.js16.17(runtime = Node.js16)

Initializer syntax:

[File name].[Initializer name]

For example, if the initializer is named index.initializer, FunctionGraph loads the initializer function defined in the index.js file.

To use Node.js to build initialization logic, define a Node.js function as the initializer. The following is a simple initializer:

exports.initializer = function(context, callback) {
    callback(null, '');
    };
  • Function Name

    The function name exports.initializer must be the initializer function name specified for a function.

    For example, if the initializer is named index.initializer, FunctionGraph loads the initializer function defined in the index.js file.

  • context

    The context parameter contains the runtime information about a function. For example, request ID, temporary AK, and function metadata.

  • callback

    The callback parameter is used to return the invocation result. The signature of this parameter is function(err, data), which is the same as that of the common callback parameter used in Node.js. If the value of err is not null, the function will return HandledInitializationError. The value of data is invalid because no value will be returned for function initialization. You can set the data parameter to null by referring to the previous example.

SDK APIs

Table 1 describes the context methods provided by FunctionGraph.

Table 1 Context methods

Method

Description

getRequestID()

Obtains a request ID.

getRemainingTimeInMilliSeconds ()

Obtains the remaining running time of a function.

getAccessKey()

Obtains the AK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

NOTE:

FunctionGraph has stopped maintaining the getAccessKey API in the Runtime SDK. You cannot use this API to obtain a temporary AK.

getSecretKey()

Obtains the SK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

NOTE:

FunctionGraph has stopped maintaining the getSecretKey API in the Runtime SDK. You cannot use this API to obtain a temporary SK.

getSecurityAccessKey()

Obtains the SecurityAccessKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getSecuritySecretKey()

Obtains the SecuritySecretKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getSecurityToken()

Obtains the SecurityToken (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getUserData(string key)

Uses keys to obtain the values passed by environment variables.

getFunctionName()

Obtains the name of a function.

getRunningTimeInSeconds ()

Obtains the timeout of a function.

getVersion()

Obtains the version of a function.

getMemorySize()

Obtains the allocated memory.

getCPUNumber()

CPU usage of a function.

getPackage()

Obtains a function group, that is, an app.

getToken()

Obtains the token (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getLogger()

Obtains the logger method provided by the context and returns a log output class. Logs are output in the format of Time-Request ID-Content by using the info method.

For example, use the info method to output logs:

logg = context.getLogger()

logg.info("hello")

getAlias

Obtains function alias.

Results returned by using the getToken(), getAccessKey(), and getSecretKey() methods contain sensitive information. Exercise caution when using these methods.

Developing a Node.js Function

The following procedure uses a local function as an example. You can also create a new one on the console.

  1. Create a function project.

    1. Write function code with a sync handler.

      Open the text editor, compile a function, and save the code file as index.js. The following is a sync handler:

      exports.handler = function (event, context, callback) {
          const error = null;
          const output = {
              'statusCode': 200,
              'headers':
              {
                  'Content-Type': 'application/json'
              },
              'isBase64Encoded': false,
              'body': JSON.stringify(event),
          }
          callback(error, output);
      }
      1. If the first parameter returned by callback is not null, the function execution fails and the HTTP error message defined in the second parameter is returned.
      2. When an APIG trigger is used, the response must be in the output format used in this example. The body only supports the following values: For details about the constraints, see Base64 Decoding and Response Structure.

        null: The HTTP response body is empty.

        []byte: The content in this byte array is the body of an HTTP response.

        string: The content in this string is the body of an HTTP response.

    2. Write function code with an async handler and runtime 8.10 or later.
      exports.handler = async (event, context) => {
          const output =
          {
              'statusCode': 200,
              'headers':
              {
                  'Content-Type': 'application/json'
              },
              'isBase64Encoded': false,
              'body': JSON.stringify(event),
          }
          return output;
      }

      If your Node.js function contains an asynchronous task, use Promise to execute the task in the current invocation. You can directly return the declared Promise or await to execute it. The asynchronous task can be executed only before the function responds to requests.

      exports.handler =  async(event, context ) => {
          const output =
          {
              'statusCode': 200,
              'headers':
              {
                  'Content-Type': 'application/json'
              },
              'isBase64Encoded': false,
              'body': JSON.stringify(event),
          }
       
          const promise = new Promise((resolve, reject) => {
              setTimeout(() => {
                  resolve(output)
              }, 2000)
          })
          return promise
          // anthor way 
          // res = await promise;
          // return res 
      }

      If you want the function to first respond and then execute the task, use an SDK or directly call the asynchronous invocation API. When using an APIG trigger, click the trigger name to go to the APIG console, and call the API in asynchronous mode.

  2. Package the project files.

    This step uses an async handler as an example. After creating the function project, you get the following directory. Select all files under the directory and package them into the fss_examples_nodejs.zip file.

    Figure 1 Packaging the project files

    In this example, the function project files are saved under the ~/Code/ directory. Select and package all files under the directory to ensure that the index.js file, the handler of your FunctionGraph function, is under the root directory when the fss_examples_nodejs.zip file is decompressed.

  3. Create a FunctionGraph function and upload the code package.

    Log in to the FunctionGraph console, create a Node.js function, and upload the fss_examples_nodejs.zip file, as shown in Figure 2.
    Figure 2 Uploading the code package
    1. In the function configuration, the index of the handler must be consistent with the name of the function file created in Step 1, because the file name will help to locate the function file.
    2. The handler is a function name, which must be the same as that in the index.js file created in Step 1.

    In the navigation pane on the left of the FunctionGraph console, choose Functions > Function List. Click the name of the function to be set. On the function details page that is displayed, choose Configuration > Basic Settings and set the Handler parameter, as shown in Figure 3. The parameter value is in the format of index.handler. The values of index and handler can be customized.

    Figure 3 Handler parameter

  4. Test the function.

    1. Create a test event.

      On the function details page that is displayed, click Configure Test Event. Configure the test event information, as shown in Figure 4, and then click Create.

      Figure 4 Configuring a test event
    2. On the function details page, select the configured test event, and click Test.

  5. View the function execution result.

    The function execution result consists of three parts: function output (returned by callback), summary, and logs (output by using the console.log or getLogger() method), as shown in Figure 5.

    Figure 5 Test result

Execution Result

The execution result consists of the function output, summary, and log output.

Table 2 Description of the execution result

Parameter

Successful Execution

Failed Execution

Function Output

The defined function output information is returned.

A JSON file that contains errorMessage and errorType is returned. The format is as follows:

{
    "errorMessage": "", 
    "errorType":"", 
}

errorMessage: Error message returned by the runtime.

errorType: Error type.

Summary

Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed.

Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed.

Log Output

Function logs are printed. A maximum of 4 KB logs can be displayed.

Error information is printed. A maximum of 4 KB logs can be displayed.