辅助函数集合
GraphQL 模式中新增的字段集合,提供与 URL、日期格式化、文本操作等相关的实用功能。
辅助字段是全局字段,因此它们会被添加到 GraphQL 模式中的每一个类型:不仅包括 QueryRoot,还包括 Post、User 等。
辅助字段列表
以下是辅助字段的列表。
_generateRandomString
生成随机字符串。
例如,执行以下 Query:
{
_generateRandomString(
length: 24,
characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
)
}可能会产生:
{
"data": {
"_generateRandomString": "BPXV1T1UJLH2S7VG3IO33FUP"
}
}
### `_htmlParseHTML5`
使用 HTML5 解析器解析 HTML 并返回解析后的 HTML。
### `_objectConvertToNameValueEntryList`
从 JSON 对象中获取属性,创建 JSON 条目列表。
此字段用于将某个字段的 `JSONObject` 输出转换为 `[JSONObject]`,以作为另一个字段的输入。
例如,`_httpRequestHeaders`(来自 **HTTP Request via Schema** 扩展)的响应为 `StringValueJSONObject`,而传入 `_sendHTTPRequest` 的请求头为 `[HTTPRequestOptionHeaderInput!]`,每个 `HTTPRequestOptionHeaderInput` 的结构如下:
```json
{
"name": "...",
"value": "..."
}
因此,可以使用以下 Query 在输出与输入之间进行桥接:
{
headers: _httpRequestHeaders
headersInput: _objectConvertToNameValueEntryList(
object: $__headers
)
_sendHTTPRequest(
input: {
url: "...",
options: {
headers: $__headersInput
}
}
) {
# ...
}
}_objectSpreadIDListValueAndFlip
给定一个以 ID 为键、以 ID 列表为值的 JSON 对象,将其翻转为另一个 JSON 对象,其中列表中的每个 ID 成为键,原始键成为值。
例如,如果提供以下 JSON 对象(将文章 ID 映射到其所有翻译文章):
{
"originPostToTranslationPostIDs": {
"1": [3, 4, 5],
"8": [10, 11],
"17": [19, 20, 21]
}
}...应用字段 _objectSpreadIDListValueAndFlip:
query SpreadAndFlipJSONObjectIDs(
$originPostToTranslationPostIDs: JSONObject!
) {
translationPostToOriginPostID: _objectSpreadIDListValueAndFlip(object: $originPostToTranslationPostIDs)
}响应将变为:
{
"translationPostToOriginPostID": {
"3": "1",
"4": "1",
"5": "1",
"10": "8",
"11": "8",
"19": "17",
"20": "17",
"21": "17"
}
}_strConvertMarkdownToHTML
将 Markdown 转换为 HTML。
此方法有助于生成作为某个字段或 mutation 输入的 HTML 内容。Email Sender 扩展的 mutation _sendEmail 就是一个例子,它可以发送 HTML 格式的电子邮件。
例如,以下 Query 使用 Markdown 内容生成用于发送电子邮件的 HTML:
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
将 XML 字符串解码为 JSON。
此方法有助于处理 XML 字符串(如 RSS 订阅源),通过将其转换为 JSON 对象,使其可由 Gato GraphQL 中的多个字段进行操作。
以下 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>
""")
}...将产生:
{
"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
将 CSV 字符串解析为 JSON 对象列表。
此字段以 CSV 作为输入,将其转换为可通过其他函数字段进行提取、迭代和操作的格式。
例如,以下 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"""
)
}...将产生:
{
"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
将数据输出为 CSV。
此字段接受数据矩阵并生成 CSV 字符串。该字符串随后可上传至媒体库、S3 存储桶、FileStack 等。
例如,以下 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],
]
)...将产生:
{
"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
向 URL 添加参数。
参数输入为 JSONObject(参数名 => 值),允许传递多种类型的值,包括 String、Int、列表(如 [String])以及 JSONObject。
以下 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"
}
}
}
)
}...将产生:
{
"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"
}
}(解码后的 URL 为 https://gatographql.com?
请注意,null 值不会被添加到 URL 中。
以下 Query:
{
_urlAddParams(
url: "https://gatographql.com",
params: {
stringParam: null,
listParam: [1, null, 3],
objectParam: {
uno: null,
dos: 2
}
}
)
}...将产生:
{
"data": {
"_urlAddParams": "https:\/\/gatographql.com?listParam%5B0%5D=1&listParam%5B2%5D=3&objectParam%5Bdos%5D=2"
}
}(解码后的 URL 为 https://gatographql.com?
_urlRemoveParams
从 URL 中移除参数。
以下 Query:
{
_urlRemoveParams(
url: "https://gatographql.com/?existingParam=existingValue&stringParam=originalValue&stringListParam[]=firstVal&stringListParam[]=secondVal&stringListParam[]=thirdVal",
names: [
"existingParam"
"stringParam"
"stringListParam"
]
)
}...将产生:
{
"data": {
"_urlRemoveParams": "https:\/\/gatographql.com\/"
}
}_arrayDeepFlatten
从包含单个值、数组和对象的混合数组中提取所有值直至最深层,并以扁平数组的形式返回。
此字段与 _arrayFlatten 类似,但它能处理混合类型并递归地展平任意深度的嵌套结构。它可以处理:
- 单个值(字符串、数字、布尔值、null)
- 数组(递归展平)
- 对象(转换为数组后展平)
以下 Query:
{
_arrayDeepFlatten(array: [
"single string",
["array", "of", "strings"],
{
key1: "value1",
key2: "value2"
},
42,
true,
null,
["nested", ["deep", "array"]],
{
nested: {
inner: "value"
}
}
])
}...将产生:
{
"data": {
"_arrayDeepFlatten": [
"single string",
"array",
"of",
"strings",
"value1",
"value2",
42,
true,
null,
"nested",
"deep",
"array",
"value"
]
}
}_arrayFlatten
将数组的数组展平为单个数组。
以下 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"
},
]
])
}...将产生:
{
"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
将数组中的元素组合,从每个数组中取出一个元素,并与对应标签下的所有其他元素合并。
以下 Query:
{
dataCombinations: _arrayGenerateAllCombinationsOfItems(labelItems: [
{
label: "person",
items: ["Sam", "Eric"]
},
{
label: "location",
items: ["Paris", "Rome"]
},
{
label: "meal",
items: ["Pasta", "Bagel"]
}
])
}...将产生:
{
"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
给定一个 JSON 对象数组,所有对象均包含两个共同属性(如 name 和 value),提取这些属性的值并创建一个 JSON 对象,以其中一个属性作为键,另一个作为值。
以下 Query:
{
arrayToObject: _arrayOfJSONObjectsExtractPropertiesAndConvertToObject(
array: [
{
label: "person",
items: ["Sam", "Eric"]
},
{
label: "location",
items: ["Paris", "Rome"]
},
{
label: "meal",
items: ["Pasta", "Bagel"]
}
],
key: "label",
value: "items"
)
}...将产生:
{
"data": {
"arrayToObject": {
"person": ["Sam", "Eric"],
"location": ["Paris", "Rome"],
"meal": ["Pasta", "Bagel"]
}
}
}_arrayOfJSONObjectsExtractProperty
给定一个 JSON 对象数组,所有对象均包含一个共同属性,提取该属性的值并将其作为数组的元素返回。
以下 Query:
{
arrayOfProperties: _arrayOfJSONObjectsExtractProperty(
array: [
{
label: "person",
items: ["Sam", "Eric"]
},
{
label: "location",
items: ["Paris", "Rome"]
},
{
label: "meal",
items: ["Pasta", "Bagel"]
}
],
key: "label"
)
}...将产生:
{
"data": {
"arrayOfProperties": ["person", "location", "meal"]
}
}示例
结合 HTTP Request via Schema 和 Field to Input 扩展,我们可以在执行 GraphQL 自定义端点或持久化 Query 时获取当前请求的 URL,添加额外参数,并向新 URL 发送另一个 HTTP 请求。
例如,在以下 Query 中,我们获取网站上的用户 ID,并将其 ID 作为参数传递执行新的 GraphQL Query:
{
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
}
}
}