스키마 함수
스키마 함수헬퍼 함수 컬렉션

헬퍼 함수 컬렉션

Included in the “Power Extensions” bundle

GraphQL 스키마에 추가된 필드 컬렉션으로, URL, 날짜 형식 지정, 텍스트 조작 등과 관련된 유용한 기능을 제공합니다.

헬퍼 필드는 글로벌 필드이므로 GraphQL 스키마의 모든 타입, 즉 QueryRoot뿐만 아니라 Post, User 등에도 추가됩니다.

헬퍼 필드 목록

다음은 헬퍼 필드의 목록입니다.

_generateRandomString

무작위 문자열을 생성합니다.

예를 들어, 다음 쿼리를 실행하면:

{
  _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": "..."
}

따라서 출력과 입력 사이를 연결하기 위해 다음 쿼리를 사용할 수 있습니다:

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

_objectSpreadIDListValueAndFlip

키를 ID로, 값을 ID 목록으로 하는 JSON 오브젝트를 받아, 목록의 각 ID를 키로, 원래 키를 값으로 하는 다른 JSON 오브젝트로 변환합니다.

예를 들어, 다음 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로 변환합니다.

이 메서드는 어떤 필드나 뮤테이션의 입력으로 제공되는 HTML 콘텐츠를 생성하는 데 도움이 됩니다. Email Sender 확장 기능의 뮤테이션 _sendEmail이 그 예로, HTML 형식으로 이메일을 전송할 수 있습니다.

예를 들어, 다음 쿼리는 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으로 디코딩합니다.

이 메서드는 RSS 피드와 같은 XML 문자열을 처리할 때 도움이 됩니다. XML을 JSON 오브젝트로 변환함으로써 Gato GraphQL의 여러 필드로 조작할 수 있게 됩니다.

다음 쿼리:

{
  _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를 입력으로 받아 다른 함수 필드를 사용하여 추출·반복·조작할 수 있는 형식으로 변환합니다.

예를 들어, 다음 쿼리:

{
  _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 등에 업로드할 수 있습니다.

예를 들어, 다음 쿼리:

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 등 여러 타입의 값을 전달할 수 있습니다.

다음 쿼리:

{
  _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?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입니다.)

null 값은 URL에 추가되지 않는다는 점에 유의하시기 바랍니다.

다음 쿼리:

{
  _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?listParam[0]=1&listParam[2]=3&objectParam[dos]=2입니다.)

_urlRemoveParams

URL에서 파라미터를 제거합니다.

다음 쿼리:

{
  _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)
  • 배열 (재귀적으로 평탄화)
  • 오브젝트 (배열로 변환 후 평탄화)

다음 쿼리:

{
  _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

배열의 배열을 하나의 배열로 평탄화합니다.

다음 쿼리:

{
  _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

배열의 요소를 조합하여, 각 배열에서 하나의 항목을 추출하고 해당 레이블 아래 모든 요소와 결합합니다.

다음 쿼리:

{
  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 오브젝트 배열을 받아, 모든 오브젝트가 공통으로 두 가지 프로퍼티(예: namevalue)를 가지는 경우, 해당 프로퍼티의 값을 추출하여 JSON 오브젝트를 생성합니다. 한 프로퍼티를 키로, 다른 하나를 값으로 사용합니다.

다음 쿼리:

{
  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 오브젝트 배열을 받아, 모든 오브젝트가 공통 프로퍼티를 가지는 경우, 해당 프로퍼티의 값을 추출하여 배열의 요소로 반환합니다.

다음 쿼리:

{
  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 커스텀 엔드포인트나 퍼시스티드 쿼리 실행 시 현재 요청된 URL을 가져오고, 추가 파라미터를 붙여 새 URL로 다른 HTTP 요청을 전송할 수 있습니다.

예를 들어, 다음 쿼리에서는 웹사이트 사용자의 ID를 가져와 해당 ID를 파라미터로 전달하는 새 GraphQL 쿼리를 실행합니다:

{
  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
    }
  }
}