Todos los productos
Search
Centro de documentos

DataWorks:Mejores prácticas para usar funciones Aviator como filtros

Última actualización: Sep 04, 2026

DataService Studio permite escribir funciones y asociarlas con una API para utilizarlas como filtros. Este tema proporciona ejemplos sobre cómo escribir la lógica de las funciones mediante funciones Aviator y su sintaxis.

Escenarios

  • Si configura una función como prefiltro de una API, esta puede preprocesar los parámetros de solicitud de la API cuando se invoca.

  • Si configura una función como posfiltro de una API, esta puede reprocesar y transformar los valores de retorno de la API cuando se invoca.

Guía de uso

Ejemplos de parámetros de entrada

Nota

En el código Aviator, el nombre de variable predeterminado $0 hace referencia a toda la entrada de la función.

  • Escenario 1: Uso de una función Aviator como prefiltro de API

    En este escenario, los parámetros de solicitud de la API se utilizan como entrada completa de la función en una estructura JSON de un solo nivel. El siguiente ejemplo muestra los parámetros de solicitud como entrada de la función:

    ## The request parameter is user_id
    ## Multiple parameter values are passed when the API is called: user_id = (0,1,2)
    {
      "user_id": [0,1,2]
    }
  • Escenario 2: Uso de una función Aviator como posfiltro de API

    En este escenario, el valor de retorno de la API se utiliza como entrada completa de la función en una estructura JSON de varios niveles. El siguiente ejemplo muestra un valor de retorno como entrada de la función:

    ## The return result contains three columns: user_id, city, and tags
    ## After the API is called, three matching data records are returned (see rows)
    {
      "data": {
        "totalNum": 3,
        "pageSize": 10,
        "rows": [
          {
            "user_id": 2,
            "city": "BJ",
            "tags": "B,D,dongcs,ccccc"
          },
          {
            "user_id": 3,
            "city": "SH",
            "tags": "A,C,D,F"
          },
          {
            "user_id": 1,
            "city": "HZ",
            "tags": "A,B,C"
          }
        ],
        "pageNum": 1
      },
      "errCode": 0,
      "requestId": "0bb211c516357674333185698eb07b",
      "errMsg": "success",
      "apiLog": null
    }

Ejemplos de uso de funciones

Escenario 1: Uso de una función Aviator como prefiltro de API. Los siguientes ejemplos muestran cómo utilizar la función:

  • Ejemplo 1: Al invocar la función, esta modifica el valor de un parámetro de solicitud enviado desde el cliente.

    • Función Aviator:

      ## For the request parameter user_id, the original value passed from the client is user_id=1
      ## After being processed by the filter, the actual value for the query is user_id=2
      if $0.user_id == 1
      {
          $0.user_id = $0.user_id + 1;
      }
      return $0;
    • Entrada y salida de la función:

      ## Input:
      {
          "user_id": 1
      }
      
      ## Output:
      {
        "user_id": 2
      }
  • Ejemplo 2: Al invocar la función, esta asigna un valor a un parámetro de solicitud que el cliente no envió. Esto aplica cuando el parámetro de solicitud no es obligatorio y no se transmite ningún valor.

    • Función Aviator:

      ## For the request parameter user_id, the original value passed from the client is user_id=
      ## After being processed by the filter, the actual value for the query is user_id=1
      $0.user_id = 1;
      return $0;
    • Entrada y salida de la función:

      ## Input:
      {
          "user_id": ""
      }
      
      ## Output:
      {
        "user_id": 1
      }
  • Ejemplo 3: Al invocar la función, si un parámetro de solicitud enviado por el cliente es una matriz (lo que significa que se pasan varios valores para un solo parámetro), la función puede recorrer la matriz y modificar cada valor según la condición del bucle.

    • Función Aviator:

      ## For the request parameter user_id, the original value passed from the client is user_id=(0,1,2)
      ## After being processed by the filter, the actual value for the query is user_id=(1,2,3)
      user_id = $0.user_id;
      for index in user_id
      {
          user_id[index] = index + 1;
      }
      return $0;
    • Entrada y salida de la función:

      ## Input:
      {
        "user_id": [0,1,2]
      }
      
      ## Output:
      {
        "user_id": [
          1,
          2,
          3
        ]
      }

Escenario 2: Uso de una función Aviator como posfiltro de API. Los siguientes ejemplos muestran cómo utilizar la función:

  • Ejemplo 1: Tras invocar la función, esta modifica un registro específico en el valor de retorno de la API, el cual tiene formato JSON.

    • Función Aviator:

      ## First, get the innermost array 'rows' from the JSON. Then, traverse the array. When a record with "city":"BJ" is found, change "tags":"" to "tags":"DataService Studio"
      rows = $0.data.rows;
      for row in rows
      {
          if(row.city == "BJ")
          {
              row.tags = "DataService Studio";
          }
      }
      return $0;
    • Entrada y salida de la función:

      ## Input:
      {
        "data": {
          "totalNum": 3,
          "pageSize": 10,
          "rows": [
            {
              "user_id": 2,
              "city": "BJ",
              "tags": "DataService Studio"
            },
            {
              "user_id": 1,
              "city": "HZ",
              "tags": "A,B,C"
            },
            {
              "user_id": 3,
              "city": "SH",
              "tags": "A,C,D,F"
            }
          ],
          "pageNum": 1
        },
        "errCode": 0,
        "requestId": "0bb211e016357705412263266e571e",
        "errMsg": "success",
        "apiLog": null
      }
      
      ## Output:
      {
        "data": {
          "totalNum": 3,
          "pageSize": 10,
          "rows": [
            {
              "user_id": 2,
              "city": "BJ",
              "tags": "DataService Studio"
            },
            {
              "user_id": 1,
              "city": "HZ",
              "tags": "A,B,C"
            },
            {
              "user_id": 3,
              "city": "SH",
              "tags": "A,C,D,F"
            }
          ],
          "pageNum": 1
        },
        "errCode": 0,
        "requestId": "0bb211e016357705412263266e571e",
        "errMsg": "success"
      }
  • Ejemplo 2: Tras invocar la función, esta agrega una columna constante a cada registro en el valor de retorno de la API, el cual tiene formato JSON.

    • Función Aviator:

      ## First, get the innermost array 'rows' from the JSON. Then, traverse the array and add a constant column is_target= "Y" to each record.
      rows = $0.data.rows;
      for row in rows
      {
          row.is_target= "Y";
      }
      
      return $0;
    • Entrada y salida de la función:

      ## Input:
      {
        "data": {
          "totalNum": 3,
          "pageSize": 10,
          "rows": [
            {
              "user_id": 2,
              "city": "BJ",
              "tags": "DataService Studio"
            },
            {
              "user_id": 1,
              "city": "HZ",
              "tags": "A,B,C"
            },
            {
              "user_id": 3,
              "city": "SH",
              "tags": "A,C,D,F"
            }
          ],
          "pageNum": 1
        },
        "errCode": 0,
        "requestId": "0bb211e016357705412263266e571e",
        "errMsg": "success",
        "apiLog": null
      }
      
      ## Output:
      {
        "data": {
          "totalNum": 3,
          "pageSize": 10,
          "rows": [
            {
              "is_target": "Y",
              "user_id": 2,
              "city": "BJ",
              "tags": "DataService Studio"
            },
            {
              "is_target": "Y",
              "user_id": 1,
              "city": "HZ",
              "tags": "A,B,C"
            },
            {
              "is_target": "Y",
              "user_id": 3,
              "city": "SH",
              "tags": "A,C,D,F"
            }
          ],
          "pageNum": 1
        },
        "errCode": 0,
        "requestId": "0bb211e016357705412263266e571e",
        "errMsg": "success"
      }
  • Ejemplo 3: Tras invocar la función, si el valor de retorno de la API (en formato JSON) contiene muchos campos y no desea verificar el valor de cada campo individualmente, puede usar una función para recorrer todos los campos y modificar los valores de campos específicos.

    • Función Aviator:

      ## First, get the innermost array 'rows' from the JSON. Then, perform a nested traversal of the 'rows' array. For each element in 'rows', get its map. If a value in the map is null, change it to "test".
      ## In Aviator syntax, 'nil' is the null constant, equivalent to 'null' in other syntaxes.
      rows = $0.data.rows;
      for row in rows
      {
          for index in row
          {
              if(index.value == nil)
              {
                  index.value = "test"
              }
          }
      }
      return $0;
    • Entrada y salida de la función:

      ## Input:
      {
        "data": {
          "totalNum": 3,
          "pageSize": 10,
          "rows": [
            {
              "user_id": null,
              "city": "SH",
              "tags": "A,C,D,F"
            },
            {
              "user_id": 2,
              "city": "BJ",
              "tags": "DataService Studio"
            },
            {
              "user_id": null,
              "city": null,
              "tags": "A,B,C"
            }
          ],
          "pageNum": 1
        },
        "errCode": 0,
        "requestId": "0bb211f016372870359913841e52d8",
        "errMsg": "success",
        "apiLog": null
      }
      
      ## Output:
      {
        "data": {
          "totalNum": 3,
          "pageSize": 10,
          "rows": [
            {
              "user_id": "test",
              "city": "SH",
              "tags": "A,C,D,F"
            },
            {
              "user_id": 2,
              "city": "BJ",
              "tags": "DataService Studio"
            },
            {
              "user_id": "test",
              "city": "test",
              "tags": "A,B,C"
            }
          ],
          "pageNum": 1
        },
        "errCode": 0,
        "requestId": "0bb211f016372870359913841e52d8",
        "errMsg": "success"
      }