Keyboard shortcuts

Press ← or → to navigate between chapters

Press ? to show this help

Press Esc to hide this help

온톨로지 조회, 파생 열과 편집 예제

함수와 SDK 코드는 실제 생성된 온톨로지 바인딩을 사용합니다. 다음 예제는 항공 및 지원 업무 모델을 사용하며, 예제에 적힌 유형과 API 이름을 자신의 온톨로지에 정의하고 사용 리소스로 가져온 환경을 전제로 합니다.

TypeScript v1의 준비

TypeScript functions 저장소를 만들고 다음 유형을 리소스로 가져옵니다.

유형 또는 접근자필요한 속성
Objects.search().flights()문자열 departureAirportCode, arrivalAirportCode
FlightAlert숫자 timeOfDelayHours
DemoTicket문자열 ticketPriority, ticketTitle

각 객체 유형에는 자신의 기본 키가 있어야 합니다. 출발 공항 코드는 검색 가능한 속성으로 구성합니다. 아래 클래스를 functions-typescript/src/index.ts에 두면 세 메서드를 함께 내보낼 수 있습니다. 다른 파일에 두었다면 index에서 클래스를 다시 내보내야 합니다.

import {
    Edits,
    Function,
    FunctionsMap,
    OntologyEditFunction,
    UserFacingError,
} from "@foundry/functions-api";
import {
    DemoTicket,
    FlightAlert,
    Objects,
    ObjectSet,
} from "@foundry/ontology-api";

export class FlightFunctions {
    @Function()
    public currentFlightDestinations(airportCode: string): Set<string> {
        const flights = Objects.search()
            .flights()
            .filter(flight => flight.departureAirportCode.exactMatch(airportCode))
            .all();
        const destinations = new Set<string>();
        for (const flight of flights) {
            const destination = flight.arrivalAirportCode;
            if (destination === undefined) {
                throw new UserFacingError("도착 공항 코드가 없는 항공편이 있습니다.");
            }
            destinations.add(destination);
        }
        return destinations;
    }

    @Function()
    public flightAlertCalculateUrgency(
        flightAlerts: ObjectSet<FlightAlert>,
    ): FunctionsMap<FlightAlert, string> {
        const urgency = new FunctionsMap<FlightAlert, string>();
        for (const flightAlert of flightAlerts.all()) {
            const hours = flightAlert.timeOfDelayHours;
            if (hours === undefined) {
                throw new UserFacingError("지연 시간이 없는 경고가 있습니다.");
            }
            urgency.set(
                flightAlert,
                hours > 4 ? "High" : hours > 2 ? "Medium" : "Low",
            );
        }
        return urgency;
    }

    @Edits(DemoTicket)
    @OntologyEditFunction()
    public addPriorityToTitle(ticket: DemoTicket): void {
        const priority = ticket.ticketPriority;
        const title = ticket.ticketTitle;
        if (priority === undefined || title === undefined) {
            throw new UserFacingError("티켓의 우선순위와 제목이 모두 필요합니다.");
        }
        ticket.ticketTitle = `[${priority}]${title}`;
    }
}

currentFlightDestinations는 출발 공항이 일치하는 항공편의 도착 공항을 중복 없는 집합으로 반환합니다. 날짜 조건은 추가하지 않은 조회입니다.

flightAlertCalculateUrgency는 지연이 4시간을 초과하면 High, 2시간을 초과하면 Medium, 나머지는 Low로 계산합니다. 따라서 정확히 4시간은 Medium, 정확히 2시간은 Low입니다. 값이 없는 경고는 긴급도가 낮다고 처리하지 않고 오류로 알립니다. Workshop Object Table의 함수 기반 열에 연결할 때 객체 집합 입력을 매핑합니다. 런타임 입력을 사용하면 현재 표시된 객체만 계산 대상으로 받을 수 있습니다.

addPriorityToTitle은 티켓 제목 앞에 대괄호로 감싼 우선순위를 붙이는 편집을 정의합니다. 실제 적용은 게시한 함수를 함수 기반 액션에 연결하고 해당 액션을 제출할 때 이루어집니다. 같은 티켓에 반복 적용하면 접두사가 반복해서 붙는 동작입니다.

all()은 객체를 메모리에 불러오므로 함수 런타임의 객체 및 실행 한도에 맞는 집합을 전달합니다. 게시 절차는 TypeScript v1 시작을 따릅니다.

Python 함수

Python 함수 템플릿의 함수 모듈에서 문자열을 반환하는 예입니다.

from functions.api import String, function


@function
def my_function() -> String:
    return "Hello World!"

온톨로지 편집을 수행하려면 별도의 편집 대상 선언과 편집 반환 계약이 필요합니다. 일반 문자열 반환 함수와 편집 함수를 같은 실행 효과로 해석하지 않습니다.

외부 TypeScript 앱의 첫 페이지 조회

다음 예제는 Employee를 포함하는 생성 SDK 패키지를 사용합니다. @example-osdk/sdk는 예시 패키지 이름이며 Developer Console에서 생성한 실제 패키지의 import 경로에 맞춰야 합니다. @osdk/client와 생성 SDK가 설치된 TypeScript 앱에 다음 함수를 둘 수 있습니다.

import { createClient } from "@osdk/client";
import { Employee } from "@example-osdk/sdk";

export async function fetchFirstEmployeePage(
    foundryUrl: string,
    ontologyRid: string,
    auth: Parameters<typeof createClient>[2],
) {
    const client = createClient(foundryUrl, ontologyRid, auth);
    const result = await client(Employee).fetchPage();
    return result.data;
}

호출자는 실제 플랫폼 URL, 온톨로지 RID와 기존 OAuth 흐름 또는 지원되는 토큰 제공자를 전달합니다. 인증 정보를 코드에 하드코딩하지 않습니다. 반환값은 첫 페이지의 객체 배열이며 전체 직원 목록을 모두 가져오는 함수는 아닙니다. 앱의 인증과 생성 패키지 구성은 OSDK 추가에서 설명합니다.

Slate의 OSDK 조회

Slate의 Functions editor에서는 JavaScript와 Slate에 생성한 OSDK version 1 인터페이스를 사용합니다. F1Driver 유형과 문자열 속성 forename, surname을 선택해 OSDK를 생성한 앱에서 다음 코드를 사용할 수 있습니다.

import { client } from "@slate/osdk";

const driverResponse = await client.ontology.objects.F1Driver.fetchPage({
    pageSize: 10,
});
return driverResponse.data.map(
    driver => `${driver.forename} ${driver.surname}`,
);

이 코드도 최대 10개를 요청하는 페이지 한 번의 결과입니다. Slate의 client.ontology.objects와 외부 TypeScript 앱의 client(Employee) 형태를 혼용하지 않습니다. 실제 엔터티 추가와 SDK 생성은 Slate OSDK의 절차를 따릅니다.