Collection de Fonctions Auxiliaires
Collection de champs ajoutés au schéma GraphQL, fournissant des fonctionnalités utiles concernant les URLs, la mise en forme des dates, la manipulation de texte, et autres.
Les champs auxiliaires sont des Champs Globaux, ils sont donc ajoutés à chaque type du schéma GraphQL : dans QueryRoot, mais aussi dans Post, User, etc.
Liste des Champs Auxiliaires
Voici la liste des champs auxiliaires.
_generateRandomString
Génère une chaîne de caractères aléatoire.
Par exemple, en exécutant cette requête :
{
_generateRandomString(
length: 24,
characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
)
}le résultat pourrait être :
{
"data": {
"_generateRandomString": "BPXV1T1UJLH2S7VG3IO33FUP"
}
}
### `_htmlParseHTML5`
Parse le HTML à l'aide du parser HTML5 et retourne le HTML parsé.
### `_objectConvertToNameValueEntryList`
Récupère les propriétés d'un objet JSON pour créer une liste d'entrées JSON.
Ce champ est utilisé pour transformer une sortie `JSONObject` de certains champs, en un `[JSONObject]` passé en entrée à un autre champ.
Par exemple, la réponse de `_httpRequestHeaders` (de l'extension **HTTP Request via Schema**) est un `StringValueJSONObject`, et les en-têtes passés en entrée dans `_sendHTTPRequest` sont `[HTTPRequestOptionHeaderInput!]`, chaque `HTTPRequestOptionHeaderInput` ayant la forme :
```json
{
"name": "...",
"value": "..."
}
Ainsi, la requête suivante permet de faire le pont entre la sortie et l'entrée :
{
headers: _httpRequestHeaders
headersInput: _objectConvertToNameValueEntryList(
object: $__headers
)
_sendHTTPRequest(
input: {
url: "...",
options: {
headers: $__headersInput
}
}
) {
# ...
}
}_objectSpreadIDListValueAndFlip
Étant donné un objet JSON avec un ID comme clé et une liste d'IDs comme valeur, le retourne dans un autre objet JSON, où chacun des IDs de la liste devient la clé, et la clé devient la valeur.
Par exemple, si nous fournissons l'objet JSON suivant (associant les IDs d'un article à tous ses articles traduits) :
{
"originPostToTranslationPostIDs": {
"1": [3, 4, 5],
"8": [10, 11],
"17": [19, 20, 21]
}
}...en appliquant le champ _objectSpreadIDListValueAndFlip :
query SpreadAndFlipJSONObjectIDs(
$originPostToTranslationPostIDs: JSONObject!
) {
translationPostToOriginPostID: _objectSpreadIDListValueAndFlip(object: $originPostToTranslationPostIDs)
}la réponse deviendra :
{
"translationPostToOriginPostID": {
"3": "1",
"4": "1",
"5": "1",
"10": "8",
"11": "8",
"19": "17",
"20": "17",
"21": "17"
}
}_strConvertMarkdownToHTML
Convertit le Markdown en HTML.
Cette méthode peut aider à produire du contenu HTML fourni en entrée à un champ ou une mutation. C'est le cas avec la mutation _sendEmail (de l'extension Email Sender), qui peut envoyer des e-mails en format HTML.
Par exemple, cette requête utilise du contenu Markdown pour produire le HTML à envoyer dans l'e-mail :
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
Décode une chaîne XML en JSON.
Cette méthode peut aider à traiter une chaîne XML, comme un flux RSS, en la convertissant en objet JSON pouvant être manipulé par plusieurs champs dans Gato GraphQL.
Cette requête :
{
_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>
""")
}...produira :
{
"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
Parse une chaîne CSV en une liste d'objets JSON.
Ce champ prend un CSV en entrée et le convertit dans un format pouvant être extrait, itéré et manipulé à l'aide d'autres champs de fonction.
Par exemple, cette requête :
{
_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"""
)
}...produira :
{
"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
Génère des données au format CSV.
Ce champ prend une matrice de données et produit une chaîne CSV. Cette chaîne peut ensuite être téléchargée dans la Médiathèque, ou téléchargée vers un bucket S3 ou FileStack, ou autre.
Par exemple, cette requête :
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],
]
)...produira :
{
"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
Ajoute des paramètres à une URL.
L'entrée des paramètres est un JSONObject de nom du paramètre => valeur, nous permettant de passer des valeurs de plusieurs types, notamment String, Int, Liste (par exemple : [String]) et aussi JSONObject.
Cette requête :
{
_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"
}
}
}
)
}...produit :
{
"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"
}
}(L'URL décodée est https://gatographql.com?
Veuillez noter que les valeurs null ne sont pas ajoutées à l'URL.
Cette requête :
{
_urlAddParams(
url: "https://gatographql.com",
params: {
stringParam: null,
listParam: [1, null, 3],
objectParam: {
uno: null,
dos: 2
}
}
)
}...produit :
{
"data": {
"_urlAddParams": "https:\/\/gatographql.com?listParam%5B0%5D=1&listParam%5B2%5D=3&objectParam%5Bdos%5D=2"
}
}(L'URL décodée est https://gatographql.com?
_urlRemoveParams
Supprime des paramètres d'une URL.
Cette requête :
{
_urlRemoveParams(
url: "https://gatographql.com/?existingParam=existingValue&stringParam=originalValue&stringListParam[]=firstVal&stringListParam[]=secondVal&stringListParam[]=thirdVal",
names: [
"existingParam"
"stringParam"
"stringListParam"
]
)
}...produit :
{
"data": {
"_urlRemoveParams": "https:\/\/gatographql.com\/"
}
}_arrayDeepFlatten
Extrait toutes les valeurs d'un tableau mixte contenant des valeurs simples, des tableaux et des objets, jusqu'à leur niveau le plus profond, et les retourne sous forme de tableau aplati.
Ce champ est similaire à _arrayFlatten, mais il gère les types mixtes et aplatit récursivement les structures imbriquées à n'importe quelle profondeur. Il peut traiter :
- Des valeurs simples (chaînes, nombres, booléens, null)
- Des tableaux (aplatis récursivement)
- Des objets (convertis en tableaux et aplatis)
Cette requête :
{
_arrayDeepFlatten(array: [
"single string",
["array", "of", "strings"],
{
key1: "value1",
key2: "value2"
},
42,
true,
null,
["nested", ["deep", "array"]],
{
nested: {
inner: "value"
}
}
])
}...produit :
{
"data": {
"_arrayDeepFlatten": [
"single string",
"array",
"of",
"strings",
"value1",
"value2",
42,
true,
null,
"nested",
"deep",
"array",
"value"
]
}
}_arrayFlatten
Aplatit un tableau de tableaux en un tableau.
Cette requête :
{
_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"
},
]
])
}...produit :
{
"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
Combine les éléments des tableaux, en extrayant un élément de chaque tableau et en le fusionnant avec tous les autres, sous l'étiquette correspondante.
Cette requête :
{
dataCombinations: _arrayGenerateAllCombinationsOfItems(labelItems: [
{
label: "person",
items: ["Sam", "Eric"]
},
{
label: "location",
items: ["Paris", "Rome"]
},
{
label: "meal",
items: ["Pasta", "Bagel"]
}
])
}...produit :
{
"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
Étant donné un tableau d'objets JSON, tous ayant deux propriétés communes (comme name et value), extrait les valeurs de ces propriétés et crée un objet JSON, avec une propriété comme clé et l'autre comme valeur.
Cette requête :
{
arrayToObject: _arrayOfJSONObjectsExtractPropertiesAndConvertToObject(
array: [
{
label: "person",
items: ["Sam", "Eric"]
},
{
label: "location",
items: ["Paris", "Rome"]
},
{
label: "meal",
items: ["Pasta", "Bagel"]
}
],
key: "label",
value: "items"
)
}...produit :
{
"data": {
"arrayToObject": {
"person": ["Sam", "Eric"],
"location": ["Paris", "Rome"],
"meal": ["Pasta", "Bagel"]
}
}
}_arrayOfJSONObjectsExtractProperty
Étant donné un tableau d'objets JSON, tous ayant une propriété commune, extrait la valeur de cette propriété et la remplace comme éléments dans le tableau.
Cette requête :
{
arrayOfProperties: _arrayOfJSONObjectsExtractProperty(
array: [
{
label: "person",
items: ["Sam", "Eric"]
},
{
label: "location",
items: ["Paris", "Rome"]
},
{
label: "meal",
items: ["Pasta", "Bagel"]
}
],
key: "label"
)
}...produit :
{
"data": {
"arrayOfProperties": ["person", "location", "meal"]
}
}Exemples
En combinaison avec les extensions HTTP Request via Schema et Field to Input, nous pouvons récupérer l'URL actuellement demandée lors de l'exécution d'un endpoint GraphQL personnalisé ou d'une persisted query, ajouter des paramètres supplémentaires, et envoyer une autre requête HTTP vers la nouvelle URL.
Par exemple, dans cette requête, nous récupérons les IDs des utilisateurs du site web et exécutons une nouvelle requête GraphQL en passant leur ID comme paramètre :
{
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
}
}
}