Raccolta di Funzioni Helper
Raccolta di campi aggiunti allo schema GraphQL, che forniscono funzionalità utili relative a URL, formattazione delle date, manipolazione del testo e altro.
I campi helper sono Campi Globali, quindi vengono aggiunti a ogni singolo tipo dello schema GraphQL: in QueryRoot, ma anche in Post, User, ecc.
Elenco dei Campi Helper
Questo è l'elenco dei campi helper.
_generateRandomString
Genera una stringa casuale.
Per esempio, eseguendo questa query:
{
_generateRandomString(
length: 24,
characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
)
}il risultato potrebbe essere:
{
"data": {
"_generateRandomString": "BPXV1T1UJLH2S7VG3IO33FUP"
}
}
### `_htmlParseHTML5`
Analizza l'HTML utilizzando il parser HTML5 e restituisce l'HTML analizzato.
### `_objectConvertToNameValueEntryList`
Recupera le proprietà da un oggetto JSON per creare un elenco di voci JSON.
Questo campo viene utilizzato per trasformare un output `JSONObject` di un certo campo in un `[JSONObject]` passato in input a un altro campo.
Per esempio, la risposta di `_httpRequestHeaders` (dell'estensione **HTTP Request via Schema**) è uno `StringValueJSONObject`, e gli header passati in input in `_sendHTTPRequest` sono `[HTTPRequestOptionHeaderInput!]`, dove ogni `HTTPRequestOptionHeaderInput` ha la forma:
```json
{
"name": "...",
"value": "..."
}
Quindi, la query seguente consente di fare da ponte tra output e input:
{
headers: _httpRequestHeaders
headersInput: _objectConvertToNameValueEntryList(
object: $__headers
)
_sendHTTPRequest(
input: {
url: "...",
options: {
headers: $__headersInput
}
}
) {
# ...
}
}_objectSpreadIDListValueAndFlip
Dato un oggetto JSON con un ID come chiave e un elenco di ID come valore, lo capovolge in un altro oggetto JSON, dove ciascuno degli ID dell'elenco diventa la chiave e la chiave diventa il valore.
Per esempio, se forniamo il seguente oggetto JSON (che associa gli ID di un articolo a tutti i suoi articoli tradotti):
{
"originPostToTranslationPostIDs": {
"1": [3, 4, 5],
"8": [10, 11],
"17": [19, 20, 21]
}
}...applicando il campo _objectSpreadIDListValueAndFlip:
query SpreadAndFlipJSONObjectIDs(
$originPostToTranslationPostIDs: JSONObject!
) {
translationPostToOriginPostID: _objectSpreadIDListValueAndFlip(object: $originPostToTranslationPostIDs)
}la risposta diventerà:
{
"translationPostToOriginPostID": {
"3": "1",
"4": "1",
"5": "1",
"10": "8",
"11": "8",
"19": "17",
"20": "17",
"21": "17"
}
}_strConvertMarkdownToHTML
Converte il Markdown in HTML.
Questo metodo può aiutare a produrre contenuto HTML fornito in input a un campo o a una mutation. È il caso della mutation _sendEmail (dell'estensione Email Sender), che può inviare email in formato HTML.
Per esempio, questa query utilizza contenuto Markdown per produrre l'HTML da inviare nell'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 una stringa XML in JSON.
Questo metodo può aiutare a elaborare una stringa XML, come un feed RSS, convertendola in un oggetto JSON che può essere manipolato da diversi campi in Gato GraphQL.
Questa query:
{
_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>
""")
}...produrrà:
{
"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
Analizza una stringa CSV in un elenco di oggetti JSON.
Questo campo prende un CSV in input e lo converte in un formato che può essere estratto, iterato e manipolato utilizzando altri campi funzione.
Per esempio, questa query:
{
_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"""
)
}...produrrà:
{
"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 dati in formato CSV.
Questo campo prende una matrice di dati e produce una stringa CSV. Questa stringa può poi essere caricata nella Libreria Media, oppure caricata su un bucket S3 o su FileStack, o altro.
Per esempio, questa query:
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],
]
)...produrrà:
{
"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
Aggiunge parametri a un URL.
L'input dei parametri è un JSONObject di nome del parametro => valore, che ci consente di passare valori di più tipi, tra cui String, Int, Lista (ad esempio: [String]) e anche JSONObject.
Questa query:
{
_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"
}
}(L'URL decodificato è https://gatographql.com?
Si noti che i valori null non vengono aggiunti all'URL.
Questa query:
{
_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"
}
}(L'URL decodificato è https://gatographql.com?
_urlRemoveParams
Rimuove parametri da un URL.
Questa query:
{
_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
Estrae tutti i valori da un array misto contenente valori singoli, array e oggetti, fino al loro livello più profondo, e li restituisce come array appiattito.
Questo campo è simile a _arrayFlatten, ma gestisce tipi misti e appiattisce ricorsivamente le strutture annidate a qualsiasi profondità. Può elaborare:
- Valori singoli (stringhe, numeri, booleani, null)
- Array (appiattiti ricorsivamente)
- Oggetti (convertiti in array e appiattiti)
Questa query:
{
_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
Appiattisce un array di array in un array.
Questa query:
{
_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 gli elementi degli array, estraendo un elemento da ciascun array e fondendolo con tutti gli altri, sotto l'etichetta corrispondente.
Questa query:
{
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
Dato un array di oggetti JSON, tutti aventi due proprietà comuni (come name e value), estrae i valori di queste proprietà e crea un oggetto JSON, con una proprietà come chiave e l'altra come valore.
Questa query:
{
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
Dato un array di oggetti JSON, tutti aventi una proprietà comune, estrae il valore di questa proprietà e lo sostituisce come elementi nell'array.
Questa query:
{
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"]
}
}Esempi
In combinazione con le estensioni HTTP Request via Schema e Field to Input, possiamo recuperare l'URL attualmente richiesto durante l'esecuzione di un endpoint GraphQL personalizzato o di una persisted query, aggiungere parametri extra e inviare un'altra richiesta HTTP al nuovo URL.
Per esempio, in questa query recuperiamo gli ID degli utenti del sito web ed eseguiamo una nuova query GraphQL passando il loro ID come parametro:
{
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
}
}
}