Schema Functions
Schema FunctionsColección de Funciones Auxiliares

Colección de Funciones Auxiliares

Included in the “Power Extensions” bundle

Colección de campos añadidos al esquema GraphQL, proporcionando funcionalidad útil relacionada con URLs, formato de fechas, manipulación de texto, y otros.

Los campos auxiliares son Campos Globales, por lo que se añaden a cada tipo del esquema GraphQL: en QueryRoot, pero también en Post, User, etc.

Lista de Campos Auxiliares

Esta es la lista de campos auxiliares.

_generateRandomString

Genera un string aleatorio.

Por ejemplo, ejecutando esta consulta:

{
  _generateRandomString(
    length: 24,
    characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
  )
}

podría producir:

{
  "data": {
    "_generateRandomString": "BPXV1T1UJLH2S7VG3IO33FUP"
  }
}

### `_htmlParseHTML5`

Parsea HTML usando el parser HTML5 y devuelve el HTML parseado.

### `_objectConvertToNameValueEntryList`

Recupera las propiedades de un objeto JSON para crear una lista de entradas JSON.

Este campo se usa para transformar una salida `JSONObject` de algún campo, en un `[JSONObject]` que se pasa como entrada a otro campo.

Por ejemplo, la respuesta de `_httpRequestHeaders` (de la extensión **HTTP Request via Schema**) es un `StringValueJSONObject`, y las cabeceras pasadas como entrada en `_sendHTTPRequest` son `[HTTPRequestOptionHeaderInput!]`, teniendo cada `HTTPRequestOptionHeaderInput` la forma:

```json
{
  "name": "...",
  "value": "..."
}

Entonces, la siguiente consulta permite hacer de puente entre la salida y la entrada:

{
  headers: _httpRequestHeaders
  headersInput: _objectConvertToNameValueEntryList(
    object: $__headers
  )
  _sendHTTPRequest(
    input: {
      url: "...",
      options: {
        headers: $__headersInput
      }
    }
  ) {
    # ...
  }
}

_objectSpreadIDListValueAndFlip

Dado un objeto JSON con un ID como clave, y una lista de IDs como valor, lo invierte en otro objeto JSON, donde cada uno de los IDs de la lista se convierte en la clave, y la clave se convierte en el valor.

Por ejemplo, si proporcionamos el siguiente objeto JSON (mapeando los IDs desde una entrada a todas sus entradas traducidas):

{
  "originPostToTranslationPostIDs": {
    "1": [3, 4, 5],
    "8": [10, 11],
    "17": [19, 20, 21]
  }
}

...al aplicar el campo _objectSpreadIDListValueAndFlip:

query SpreadAndFlipJSONObjectIDs(
  $originPostToTranslationPostIDs: JSONObject!
) {
  translationPostToOriginPostID: _objectSpreadIDListValueAndFlip(object: $originPostToTranslationPostIDs)
}

la respuesta se convertirá en:

{
  "translationPostToOriginPostID": {
    "3": "1",
    "4": "1",
    "5": "1",
    "10": "8",
    "11": "8",
    "19": "17",
    "20": "17",
    "21": "17"
  }
}

_strConvertMarkdownToHTML

Convierte Markdown a HTML.

Este método puede ayudar a producir contenido HTML que se proporciona como entrada a algún campo o mutación. Es el caso con la mutación _sendEmail (de la extensión Email Sender), que puede enviar emails en formato HTML.

Por ejemplo, esta consulta usa contenido Markdown para producir el HTML a enviar en el email:

query GetPostData($postID: ID!) {
  post(by: {id: $postID}) {
    title @export(as: "postTitle")
    excerpt @export(as: "postExcerpt")
    url @export(as: "postLink")
    author {
      name @export(as: "postAuthorName")
      url @export(as: "postAuthorLink")
    }
  }
}
 
query GetEmailData @depends(on: "GetPostData") {
  emailMessageTemplate: _strConvertMarkdownToHTML(
    text: """
 
There is a new post by [{$postAuthorName}]({$postAuthorLink}):
 
**{$postTitle}**: {$postExcerpt}
 
[Read online]({$postLink})
 
    """
  )
  emailMessage: _strReplaceMultiple(
    search: ["{$postAuthorName}", "{$postAuthorLink}", "{$postTitle}", "{$postExcerpt}", "{$postLink}"],
    replaceWith: [$postAuthorName, $postAuthorLink, $postTitle, $postExcerpt, $postLink],
    in: $__emailMessageTemplate
  )
    @export(as: "emailMessage")
  subject: _sprintf(string: "New post created by %s", values: [$postAuthorName])
    @export(as: "emailSubject")
}
 
mutation SendEmail @depends(on: "GetEmailData") {
  _sendEmail(
    input: {
      to: "target@email.com"
      subject: $emailSubject
      messageAs: {
        html: $emailMessage
      }
    }
  ) {
    status
  }
}

_strDecodeXMLAsJSON

Decodifica un string XML como JSON.

Este método puede ayudar a procesar un string XML, como un feed RSS, convirtiéndolo en un objeto JSON que puede ser manipulado por varios campos en Gato GraphQL.

Esta consulta:

{
  _strDecodeXMLAsJSON(xml: """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>  
  <book category="COOKING">  
    <title lang="en">Everyday Italian</title>  
    <author>Giada De Laurentiis</author>  
    <year>2005</year>  
    <price>30.00</price>  
  </book>  
  <book category="CHILDREN">  
    <title lang="en">Harry Potter</title>  
    <author>J K. Rowling</author>  
    <year>2005</year>  
    <price>29.99</price>  
  </book>  
  <book category="WEB">  
    <title lang="en">Learning XML</title>  
    <author>Erik T. Ray</author>  
    <year>2003</year>  
    <price>39.95</price>  
  </book>  
</bookstore>
  """)
}

...producirá:

{
  "data": {
    "_strDecodeXMLAsJSON": {
      "bookstore": {
        "book": [
          {
            "@category": "COOKING",
            "title": {
              "@lang": "en",
              "_": "Everyday Italian"
            },
            "author": "Giada De Laurentiis",
            "year": "2005",
            "price": "30.00"
          },
          {
            "@category": "CHILDREN",
            "title": {
              "@lang": "en",
              "_": "Harry Potter"
            },
            "author": "J K. Rowling",
            "year": "2005",
            "price": "29.99"
          },
          {
            "@category": "WEB",
            "title": {
              "@lang": "en",
              "_": "Learning XML"
            },
            "author": "Erik T. Ray",
            "year": "2003",
            "price": "39.95"
          }
        ]
      }
    }
  }
}

_strParseCSV

Parsea un string CSV en una lista de objetos JSON.

Este campo tomará un CSV como entrada, y lo convertirá en un formato que puede extraerse, iterarse y manipularse usando otros campos de función.

Por ejemplo, esta consulta:

{
  _strParseCSV(
    string: """Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition"" (2008)","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large"" (2008)","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00"""
  )
}

...producirá:

{
  "data": {
    "_strParseCSV": [
      {
        "Year": "1997",
        "Make": "Ford",
        "Model": "E350",
        "Description": "ac, abs, moon",
        "Price": "3000.00"
      },
      {
        "Year": "1999",
        "Make": "Chevy",
        "Model": "Venture \"Extended Edition\" (2008)",
        "Description": "",
        "Price": "4900.00"
      },
      {
        "Year": "1999",
        "Make": "Chevy",
        "Model": "Venture \"Extended Edition, Very Large\" (2008)",
        "Description": "",
        "Price": "5000.00"
      },
      {
        "Year": "1996",
        "Make": "Jeep",
        "Model": "Grand Cherokee",
        "Description": "MUST SELL!\nair, moon roof, loaded",
        "Price": "4799.00"
      }
    ]
  }
}

_dataMatrixOutputAsCSV

Genera datos como un CSV.

Este campo tomará una matriz de datos, y producirá un string CSV. Este string puede entonces subirse a la Librería de Medios, o subirse a un bucket de S3 o FileStack, u otro.

Por ejemplo, esta consulta:

csv: _dataMatrixOutputAsCSV(
  fields: 
    ["Name", "Surname", "Year"]
  data: [
    ["John", "Smith", 2003],
    ["Pedro", "Gonzales", 2012],
    ["Manuel", "Perez", 2008],
    ["Jose", "Pereyra", 1999],
    ["Jacinto", "Bloomberg", 1998],
    ["Jun-E", "Song", 1983],
    ["Juan David", "Santamaria", 1943],
    ["Luis Miguel", null, 1966],
  ]
)

...producirá:

{
  "data": {
    "csv": "Name,Surname,Year\nJohn,Smith,2003\nPedro,Gonzales,2012\nManuel,Perez,2008\nJose,Pereyra,1999\nJacinto,Bloomberg,1998\nJun-E,Song,1983\nJuan David,Santamaria,1943\nLuis Miguel,,1966\n"
  }
}

_urlAddParams

Añade parámetros a una URL.

La entrada de parámetros es un JSONObject de nombre del parámetro => valor, lo que nos permite pasar valores de múltiples tipos, incluyendo String, Int, Lista (por ejemplo: [String]) y también JSONObject.

Esta consulta:

{
  _urlAddParams(
    url: "https://gatographql.com",
    params: {
      stringParam: "someValue",
      intParam: 5,
      stringListParam: ["value1", "value2"],
      intListParam: [8, 9, 4],
      objectParam: {
        "1st": "1stValue",
        "2nd": 2,
        "3rd": ["uno", 2.5]
        "4th": {
          nestedIn: "nestedOut"
        }
      }
    }
  )
}

...produce:

{
  "data": {
    "_urlAddParams": "https:\/\/gatographql.com?stringParam=someValue&intParam=5&stringListParam%5B0%5D=value1&stringListParam%5B1%5D=value2&intListParam%5B0%5D=8&intListParam%5B1%5D=9&intListParam%5B2%5D=4&objectParam%5B1st%5D=1stValue&objectParam%5B2nd%5D=2&objectParam%5B3rd%5D%5B0%5D=uno&objectParam%5B3rd%5D%5B1%5D=2.5&objectParam%5B4th%5D%5BnestedIn%5D=nestedOut"
  }
}

(La URL decodificada es https://gatographql.com?stringParam=someValue&intParam=5&stringListParam[0]=value1&stringListParam[1]=value2&intListParam[0]=8&intListParam[1]=9&intListParam[2]=4&objectParam[1st]=1stValue&objectParam[2nd]=2&objectParam[3rd][0]=uno&objectParam[3rd][1]=2.5&objectParam[4th][nestedIn]=nestedOut.)

Por favor, ten en cuenta que los valores null no se añaden a la URL.

Esta consulta:

{
  _urlAddParams(
    url: "https://gatographql.com",
    params: {
      stringParam: null,
      listParam: [1, null, 3],
      objectParam: {
        uno: null,
        dos: 2
      }
    }
  )
}

...produce:

{
  "data": {
    "_urlAddParams": "https:\/\/gatographql.com?listParam%5B0%5D=1&listParam%5B2%5D=3&objectParam%5Bdos%5D=2"
  }
}

(La URL decodificada es https://gatographql.com?listParam[0]=1&listParam[2]=3&objectParam[dos]=2.)

_urlRemoveParams

Elimina parámetros de una URL.

Esta consulta:

{
  _urlRemoveParams(
    url: "https://gatographql.com/?existingParam=existingValue&stringParam=originalValue&stringListParam[]=firstVal&stringListParam[]=secondVal&stringListParam[]=thirdVal",
    names: [
      "existingParam"
      "stringParam"
      "stringListParam"
    ]
  )
}

...produce:

{
  "data": {
    "_urlRemoveParams": "https:\/\/gatographql.com\/"
  }
}

_arrayDeepFlatten

Extrae todos los valores de un array mixto que contiene valores individuales, arrays y objetos, hasta su nivel más profundo, y los devuelve como un array aplanado.

Este campo es similar a _arrayFlatten, pero maneja tipos mixtos y aplana recursivamente estructuras anidadas a cualquier profundidad. Puede procesar:

  • Valores individuales (strings, números, booleanos, null)
  • Arrays (aplanados recursivamente)
  • Objetos (convertidos a arrays y aplanados)

Esta consulta:

{
  _arrayDeepFlatten(array: [
    "single string",
    ["array", "of", "strings"],
    {
      key1: "value1",
      key2: "value2"
    },
    42,
    true,
    null,
    ["nested", ["deep", "array"]],
    {
      nested: {
        inner: "value"
      }
    }
  ])
}

...produce:

{
  "data": {
    "_arrayDeepFlatten": [
      "single string",
      "array",
      "of",
      "strings",
      "value1",
      "value2",
      42,
      true,
      null,
      "nested",
      "deep",
      "array",
      "value"
    ]
  }
}

_arrayFlatten

Aplana un array de arrays en un array.

Esta consulta:

{
  _arrayFlatten(array: [
    [
      {
        "id": 2302,
        "url": "https://mysite.com/media/143"
      }
    ],
    [
      {
        "id": 2303,
        "url": "https://mysite.com/media/146"
      },
      {
        "id": 2304,
        "url": "https://mysite.com/media/147"
      },
    ]
  ])
}

...produce:

{
  "data": {
    "_arrayFlatten": [
      {
        "id": 2302,
        "url": "https://mysite.com/media/143"
      },
      {
        "id": 2303,
        "url": "https://mysite.com/media/146"
      },
      {
        "id": 2304,
        "url": "https://mysite.com/media/147"
      }
    ]
  }
}

_arrayGenerateAllCombinationsOfItems

Combina los elementos de los arrays, extrayendo un elemento de cada array y fusionándolo con todos los demás, bajo la etiqueta correspondiente.

Esta consulta:

{
  dataCombinations: _arrayGenerateAllCombinationsOfItems(labelItems: [
    {
      label: "person",
      items: ["Sam", "Eric"]
    },
    {
      label: "location",
      items: ["Paris", "Rome"]
    },
    {
      label: "meal",
      items: ["Pasta", "Bagel"]
    }
  ])
}

...produce:

{
  "data": {
    "dataCombinations": [
      {
        "person": "Sam",
        "location": "Paris",
        "meal": "Pasta"
      },
      {
        "person": "Sam",
        "location": "Paris",
        "meal": "Bagel"
      },
      {
        "person": "Sam",
        "location": "Rome",
        "meal": "Pasta"
      },
      {
        "person": "Sam",
        "location": "Rome",
        "meal": "Bagel"
      },
      {
        "person": "Eric",
        "location": "Paris",
        "meal": "Pasta"
      },
      {
        "person": "Eric",
        "location": "Paris",
        "meal": "Bagel"
      },
      {
        "person": "Eric",
        "location": "Rome",
        "meal": "Pasta"
      },
      {
        "person": "Eric",
        "location": "Rome",
        "meal": "Bagel"
      }
    ]
  }
}

_arrayOfJSONObjectsExtractPropertiesAndConvertToObject

Dado un array de objetos JSON, donde todos tienen dos propiedades comunes (como name y value), extrae los valores de estas propiedades y crea un objeto JSON, con una propiedad como clave y la otra como valor.

Esta consulta:

{
  arrayToObject: _arrayOfJSONObjectsExtractPropertiesAndConvertToObject(
    array: [
      {
        label: "person",
        items: ["Sam", "Eric"]
      },
      {
        label: "location",
        items: ["Paris", "Rome"]
      },
      {
        label: "meal",
        items: ["Pasta", "Bagel"]
      }
    ],
    key: "label",
    value: "items"
  )
}

...produce:

{
  "data": {
    "arrayToObject": {
      "person": ["Sam", "Eric"],
      "location": ["Paris", "Rome"],
      "meal": ["Pasta", "Bagel"]
    }
  }
}

_arrayOfJSONObjectsExtractProperty

Dado un array de objetos JSON, donde todos tienen una propiedad común, extrae el valor de esta propiedad y la reemplaza como elementos en el array.

Esta consulta:

{
  arrayOfProperties: _arrayOfJSONObjectsExtractProperty(
    array: [
      {
        label: "person",
        items: ["Sam", "Eric"]
      },
      {
        label: "location",
        items: ["Paris", "Rome"]
      },
      {
        label: "meal",
        items: ["Pasta", "Bagel"]
      }
    ],
    key: "label"
  )
}

...produce:

{
  "data": {
    "arrayOfProperties": ["person", "location", "meal"]
  }
}

Ejemplos

En combinación con las extensiones HTTP Request via Schema y Field to Input, podemos recuperar la URL actualmente solicitada al ejecutar un endpoint personalizado de GraphQL o una persisted query, añadir parámetros extra, y enviar otra petición HTTP a la nueva URL.

Por ejemplo, en esta consulta, recuperamos los IDs de los usuarios en el sitio web y ejecutamos una nueva consulta GraphQL pasando su ID como parámetro:

{
  users {
    userID: id
    url: _urlAddParams(
      url: "https://somewebsite/endpoint/user-data",
      params: {
        userID: $__userID
      }
    )
    headers: _httpRequestHeaders
    headerNameValueEntryList: _objectConvertToNameValueEntryList(
      object: $__headers
    )
    _sendHTTPRequest(input: {
      url: $__url
      options: {
        headers: $__headerNameValueEntryList
      }
    }) {
      statusCode
      contentType
      body
    }
  }
}