이 페이지의 소스 가져오기 지침과 코드 예제는 TypeScript v1 Functions에만 해당합니다. Ontology SDK 지원과 구성 가능한 리소스 요청 등 더욱 강력한 기능을 활용하려면 TypeScript v2로 마이그레이션하는 것을 권장합니다.
이 가이드에서는 웹훅을 사용하여 외부 시스템에 요청을 보낼 수 있는 Function을 설정하는 방법을 안내합니다.
TypeScript v2 또는 Python Functions에서 웹훅을 사용하려면 웹훅 Function으로 게시하세요. 게시된 Function을 Functions 리포지토리로 가져온 다음 Ontology SDK를 사용하여 호출하세요. 웹훅 Functions는 Workshop, Function 기반 액션, 다른 Functions에서도 호출할 수 있습니다.
아웃바운드 애플리케이션을 기반으로 하는 웹훅이 지원됩니다. 자세한 내용은 아웃바운드 애플리케이션 구성 페이지의 지원되는 워크플로 섹션을 참조하세요.
이 가이드를 진행하기 전에 다음 사항을 확인하세요.
먼저 소스를 Code Repositories로 가져올 수 있도록 활성화해야 합니다. REST API 소스의 코드 가져오기 활성화 메뉴로 이동하여 소스를 Code Repositories로 가져올 수 있도록 허용하는 옵션을 활성화하세요. Functions가 사용되는 모든 워크플로에서 내보내기 가능한 마킹 검증을 수행할 수는 없으므로, 각 소스의 내보내기 활성화 메뉴에서 마킹 검증 없이 소스로 내보내는 기능도 활성화해야 합니다.


다음으로, Functions에서 웹훅을 사용하려면 웹훅의 기반 REST API 소스를 먼저 리포지토리로 가져와야 합니다. 왼쪽 리소스 가져오기 패널을 선택하여 리포지토리로 가져온 소스를 확인하세요. 추가 > 소스를 선택하면 가져올 소스를 선택할 수 있는 검색 대화 상자가 표시됩니다. 이 대화 상자에서는 API 이름이 있는 소스만 가져올 수 있습니다.

웹훅 사용을 위해 Function 리포지토리로 소스를 가져오는 방식은 Python 변환 리포지토리 및 컴퓨트 모듈로 소스를 가져오는 방식과 다릅니다. 특정 소스를 웹훅 용도로만 사용하는 Function 리포지토리는 소스 전체보기에 표시되는 리포지토리 목록에 표시되지 않습니다. 소스에 대한 뷰어 액세스 권한이 있는 모든 사용자는 해당 웹훅을 가져와 외부 Functions에서 사용할 수 있습니다.
REST API 소스를 Functions 리포지토리로 가져오면 TypeScript 환경에서 사용할 수 있으며, 소스의 네임스페이스를 통해 액세스할 수 있습니다.
Copied!1 2import { Function } from "@foundry/functions-api"; import { MyDictionarySource } from "@foundry/external-systems/sources";
Cannot find module '@foundry/external-systems' or its corresponding type declarations. 오류가 발생하면 functions-typescript/functions.json 파일에서 enableExternalSystems 값이 true로 설정되어 있는지 확인하세요. 값을 업데이트하고 변경 사항을 커밋하면 시스템이 @foundry/external-systems를 포함한 필수 패키지를 설치합니다.

아래 예제에서는 단일 Function을 사용하여 사전 API를 여러 번 호출하는 방법을 설명합니다.
Function이 온톨로지를 편집하지 않는 경우 @Query() 함수를 생성합니다. 온톨로지를 편집하려는 경우에는 @OntologyEditFunction 데코레이터가 필요합니다. Functions에서 온톨로지를 편집하는 방법에 대한 자세한 내용은 관련 문서를 확인해주세요.
표준 TypeScript async/await 패턴 ↗을 사용하면 Function에서 여러 웹훅 호출을 동시에 수행할 수 있습니다. @foundry/functions-api에서 내보내는 isOk 헬퍼 함수를 사용하여 호출의 성공 여부를 확인하세요.
다음 Function은 단어 목록을 TypeScript 스트링 배열로 받아 각 단어에 대해 한 번씩 호출합니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26import { OntologyEditFunction, isOk } from "@foundry/functions-api"; import { MyDictionarySource } from "@foundry/external-systems/sources"; export class MyFunctions { @OntologyEditFunction() public async defineWords(words: string[]): Promise<void> { const results = await Promise.all(words.map(word => MyDictionarySource.webhooks.GetDefinition.call({ wordToDefine: word }))); results.forEach((result, i) => { if (isOk(result)) { const output = result.value.output; output.dictionary_definitions.forEach(definitions_for_word => { definitions_for_word.meanings.forEach(meaning => { meaning.definitions.forEach(def_for_part_of_speech => { console.log(`Found a ${meaning.partOfSpeech} definition for "${words[i]}": ${def_for_part_of_speech.definition}`); }) }) }); } }); } }
입력이 ["tuba", "cool"]인 경우의 로그 결과물:
LOG [2023-07-28T03:16:22.968Z] Found a noun definition for "tuba": A large brass musical instrument, usually in the bass range, played through a vibration of the lips upon the mouthpiece and fingering of the keys.
LOG [2023-07-28T03:16:22.968Z] Found a noun definition for "tuba": A type of Roman military trumpet, distinct from the modern tuba.
LOG [2023-07-28T03:16:22.968Z] Found a noun definition for "tuba": A large reed stop in organs.
LOG [2023-07-28T03:16:22.968Z] Found a noun definition for "tuba": A Malayan plant whose roots are a significant source of rotenone, Derris malaccensis.
LOG [2023-07-28T03:16:22.968Z] Found a noun definition for "tuba": A reddish palm wine made from coconut or nipa sap.
LOG [2023-07-28T03:16:22.968Z] Found a noun definition for "tuba": A tube or tubular organ.
LOG [2023-07-28T03:16:22.968Z] Found a noun definition for "cool": A moderate or refreshing state of cold; moderate temperature of the air between hot and cold; coolness.
LOG [2023-07-28T03:16:22.968Z] Found a noun definition for "cool": A calm temperament.
네트워크로 연결된 시스템에서 작업할 때 발생하는 실패를 완화하기 위해, Functions는 웹훅에서 전파된 오류를 Result 오브젝트를 통해 노출합니다. 이 오브젝트는 발생한 오류의 종류에 대한 정보를 제공합니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29import { OntologyEditFunction, isOk } from "@foundry/functions-api"; import { MyDictionarySource } from "@foundry/external-systems/sources"; export class MyFunctions { @OntologyEditFunction() public async defineWords(words: string[]): Promise<void> { const results = await Promise.all(words.map(word => MyDictionarySource.webhooks.GetDefinition.call({ wordToDefine: word }))); results.forEach((result, i) => { if (isOk(result)) { // 응답 추출 } else { const errorName = result.error.name; if (errorName === "WebhookExecutionFailedToStart") { console.log("We were unable to initiate a request to the dictionary API."); } else if (errorName === "ParsingResponseFailed") { console.log("The external request succeeded, but the response couldn't be parsed."); } else { console.log("Something went wrong."); } } }); } }
오류를 처리할 때 작성한 코드는 특정 오류 이름을 감지하고 그에 따라 대응해야 합니다. Functions는 현재 다음 오류를 반환합니다.
| 오류 | 설명 |
|---|---|
WebhookExecutionFailedToStart | 웹훅을 시작하지 못했습니다. 이 오류가 반환되면 외부 시스템에 요청이 전송되지 않았다고 확실히 간주할 수 있습니다. |
WebhookExecutionTimedOut | 웹훅 실행이 시작되었지만 구성된 웹훅 시간 제한 내에 외부 시스템으로부터 응답을 받지 못했습니다. |
RemoteRestApiReturnedError | 외부 시스템이 오류를 반환했습니다. REST API 소스에 구성된 웹훅에 대해서만 반환됩니다. |
RemoteApiReturnedError | 외부 시스템이 오류를 반환했습니다. REST API가 아닌 소스에 구성된 웹훅에 대해서만 반환됩니다. |
ParsingResponseFailed | 웹훅 실행은 성공했지만 외부 시스템의 응답을 성공적으로 파싱하지 못했습니다. 예를 들어 외부 시스템의 응답에 예상한 필드가 포함되지 않은 경우 발생할 수 있습니다. 웹훅 호출의 결과가 반드시 사용되는 것은 아니므로, 이를 최종 사용자에게 실패로 표시할지는 애플리케이션 빌더가 결정합니다. |
ServerError | 웹훅 서비스 또는 커넥터 내부에서 문제가 발생했습니다. |
UnknownError | 특정 Foundry 서비스에서 직접 발생했다고 볼 수 없는 오류가 발생했습니다. |
이 오류 유형 목록은 변경될 수 있습니다. Function 실행기가 새로운 이름의 오류를 반환하는 경우에 대비해, 사용자는 Base case를 포함하도록 코드를 구성해야 합니다.
다음 코드는 동일한 함수 내에서 일부는 성공하고 일부는 실패하는 여러 웹훅 호출을 처리하는 방법을 보여 줍니다. 이 예제에서는 사전 서버가 주어진 단어의 정의를 찾지 못할 경우 RemoteRestApiReturnedError가 반환됩니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30import { OntologyEditFunction, isOk } from "@foundry/functions-api"; import { MyDictionarySource } from "@foundry/external-systems/sources"; export class MyFunctions { @OntologyEditFunction() public async defineWords(words: string[]): Promise<void> { const results = await Promise.all(words.map(word => MyDictionarySource.webhooks.GetDefinition.call({ wordToDefine: word }))); results.forEach((result, i) => { if (isOk(result)) { const output = result.value.output; output.dictionary_definitions.forEach(definitions_for_word => { definitions_for_word.meanings.forEach(meaning => { meaning.definitions.forEach(def_for_part_of_speech => { console.log(`Found a ${meaning.partOfSpeech} definition for "${words[i]}": ${def_for_part_of_speech.definition}`); }) }) }); } else { if (result.error.name === "RemoteRestApiReturnedError") { console.log(`ERROR: ${words[i]} could not be defined`, result.error.message); } } }); } }
위 Function에 ["asdf", "shire"]를 입력하면 다음 결과가 반환됩니다.
LOG [2023-07-28T15:38:47.263Z] ERROR: asdf could not be defined Request returned an unsuccessful response code: 404 Response body: {"title":"No Definitions Found","message":"Sorry pal, we couldn't find definitions for the word you were looking for.","resolution":"You can try the search again at later time or head to the web instead."}
LOG [2023-07-28T15:38:47.264Z] Found a noun definition for "shire": Physical area administered by a sheriff.
LOG [2023-07-28T15:38:47.264Z] Found a noun definition for "shire": Former administrative area of Britain; a county.
LOG [2023-07-28T15:38:47.264Z] Found a noun definition for "shire": The general area in which a person lives or comes from, used in the context of travel within the United Kingdom.
LOG [2023-07-28T15:38:47.264Z] Found a noun definition for "shire": A rural or outer suburban local government area of Australia.
LOG [2023-07-28T15:38:47.264Z] Found a noun definition for "shire": A shire horse.
LOG [2023-07-28T15:38:47.264Z] Found a verb definition for "shire": To (re)constitute as one or more shires or counties.
현재 온톨로지 편집 Function 내에서 수행할 수 있는 요청 수에는 제한이 없지만, 기존 Functions 리소스 제한은 계속 적용됩니다. 웹훅 제한도 적용됩니다.
Functions는 현재 다음 입력 및 결과물 유형을 사용하는 웹훅을 지원합니다.
@Query Function에서 웹훅을 호출할 때 웹훅은 외부 시스템을 변경하지 않는 읽기 API 호출만 수행해야 합니다. 쿼리 Function은 자주 재시도되거나 페이지 로드 시 자동으로 실행되므로, @OntologyEditFunction에서 가능한 것과 동일한 수준의 체계적이고 명시적인 실행을 제공하지 않습니다. 웹훅을 구성할 때 읽기 API 또는 쓰기 API 옵션을 사용하여 쿼리 Function에서 실행해도 안전한지 지정할 수 있습니다.
OR 유형을 사용하는 웹훅은 현재 지원되지 않습니다. 이러한 웹훅에 대해서는 코드가 생성되지 않습니다.Functions와 웹훅에는 버젼이 있으며, 호출자는 Function 또는 웹훅의 모든 버젼을 호출할 수 있습니다. Function이 게시되면 해당 시점에 사용 가능한 최신 웹훅 버젼이 고정됩니다.
Code Repositories 애플리케이션에서 Functions 리포지토리를 열면 자동 완성에 사용되는 생성된 코드 바인딩은 항상 최신 웹훅 버젼을 사용합니다. 이 웹훅 버젼은 왼쪽의 리소스 가져오기 사이드 패널에 표시됩니다.

웹훅의 기능에 의존하는 Function을 게시하기 전에 웹훅이 안정적인지 확인하세요.
웹훅 또는 Function이 변경되면 Function을 다시 게시하고 사용자가 새 버젼을 사용하도록 전환해야 합니다. 이전에 게시되어 고정된 Function 버젼은 계속 사용할 수 있습니다.
다음 표는 외부 Function을 작성, 게시 및 사용하는 데 필요한 권한을 요약합니다.
| 액션 | 사용자 | 필요한 권한 |
|---|---|---|
| Functions 리포지토리로 웹훅 가져오기 | Function 에디터 | 웹훅에 대한 webhooks:editor 권한. 에디터 기본 역할에 부여됩니다. |
| 웹훅을 호출하는 Function 게시 | Function 에디터 | 소스에 대한 webhooks:execute 권한. 소유자 및 에디터 기본 역할에만 부여됩니다. |
웹훅을 호출하는 @OntologyEditFunction()을 사용하도록 액션 구성 | 액션 에디터 | 웹훅에 대한 webhooks:grant-action-validated-execution 권한 및 Function에 대한 뷰어 권한 |
Workshop에서 @Query() 웹훅 실행 | 최종 사용자 | 소스에 대한 webhooks:execute 권한. 소유자 및 에디터 기본 역할에만 부여됩니다. |
액션에서 @OntologyEditFunction() 실행 | 최종 사용자 | 사용자는 액션의 제출 기준을 충족해야 합니다. 이 경우 소스, 웹훅 또는 Function에 대한 권한은 확인되지 않습니다. 액션을 생성하고 관리하는 사용자는 제출 기준이 적절하게 구성되었는지 확인해야 합니다. |
다음 플랫폼 도구를 사용하여 Function에서 실행되는 웹훅에 대한 더 자세한 정보를 확인하세요.
외부 소스를 사용하여 Function에서 웹훅을 호출할 때 다음 모범 사례를 권장합니다.
record 유형 파라미터를 사용하세요. JSON 대신 명시적 유형을 사용하면 Function 코드에서 예기치 않은 런타임 오류가 발생할 가능성이 줄어듭니다.@foundry/functions-api에서 내보내는 isOk 및 isErr 내장 함수를 사용하여 성공 및 오류 상태를 확인하고, 이름 필드를 통해 오류 유형을 좁혀 나가세요.