> For the complete documentation index, see [llms.txt](https://help.smallbuilder.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.smallbuilder.com/ko/smallbuilder-lists/undefined-1-1/datasource-setup/advanced-datasource/writing-an-apex-class.md).

# Apex Class 작성

데이터소스 고급 설정에서 사용할 Apex 클래스를 작성하려면 반드시 `SBLS.DataSourceService.Fetchable` **인터페이스를 구현**해야 합니다.

이 인터페이스에는 `execute` 메서드가 포함되어 있으며, 해당 메서드에 데이터 처리를 위한 로직 구현 후 처리된 데이터와 리스트 간의 매핑 정보를 담은 `SBLS.DataSourceService.Result` 객체를 반환해야 합니다.

***

### :small\_orange\_diamond: 예시 코드

해당 예시 코드는 외부 API를 호출하여 제품 코드별 재고 수량을 가져온 후, 리스트에 가상 열로 생성한 재고 열(`SBLS_Virtual1`)에 매핑한다고 가정하였습니다.

{% hint style="warning" %}
`SBLS.DataSourceService.Fetchable` 인터페이스는 패키지에서 제공되는 인터페이스이므로, 패키지 외부에서 접근하려면 Apex 클래스와 제공되는 메서드 모두 **`global`**&#xB85C; 선언해야 합니다.
{% endhint %}

{% code title="DataSourceInventory.cls" lineNumbers="true" fullWidth="false" %}

```java
global class DataSourceInventory implements SBLS.DataSourceService.Fetchable {
    global SBLS.DataSourceService.Result execute(SBLS.DataSourceService.Parameter params) {
        // 리스트에 검색된 레코드
        List<SObject> records = params.gets();
    
        // 외부 API를 호출하여 데이터소스 값 가져오기 (예: 재고 정보)
        // 키: 제품 코드, 값: 재고 수량
        Map<String, Integer> inventoryData = new Map<String, Integer>(); 
        inventoryData.put('Product001', 10);
        inventoryData.put('Product002', 20);

        // 결과 객체 생성
        SBLS.DataSourceService.Result result = new SBLS.DataSourceService.Result();

        // 리스트 개체와 데이터소스 매핑
        for (String productCode : inventoryData.keySet()) {
            SBLS.DataSourceService.Action action = new SBLS.DataSourceService.Action();
            action.setKeyValue(productCode); // 리스트 레코드와 매핑할 Key 값 설정
            action.putSourceToTargetField(
                inventoryData.get(productCode), // 데이터소스 값: 재고 정보
                'SBLS_Virtual1'                 // 리스트 가상 열 API명
            );
            result.addAction(action); // Action 추가
        }
        
        return result; // 결과 반환
    }
}
```

{% endcode %}

{% stepper %}
{% step %}
**리스트에 검색된 레코드 가져오기**

`params.gets()`를 사용하여 리스트의 검색된 레코드를 가져옵니다.
{% endstep %}

{% step %}
**데이터소스 값 준비**

* 외부 API 서버에서 데이터를 호출하여 재고 정보를 가져온다고 가정합니다.
* 예시에서는 제품 코드(`ProductCode`)를 기반으로 재고 정보를 매핑합니다.

```java
<String, Integer> inventoryData = new Map<String, Integer>(); 
inventoryData.put('Product001', 10);
inventoryData.put('Product002', 20);
```

{% endstep %}

{% step %}
**결과 생성**

* [`SBLS.DataSourceService.Action`](#sbli.datasourceservice.action) 객체를 생성하여 데이터소스 값(재고 정보)을 가상 열 재고(`SBLS_Virtual01`)에 매핑합니다.
* 생성된 Action 객체를 [`SBLS.DataSourceService.Result`](#sbli.datasourceservice.result)에 추가합니다.

```java
// 결과 객체 생성
SBLS.DataSourceService.Result result = new SBLS.DataSourceService.Result();

// 리스트 개체와 데이터소스 매핑
for (String productCode : inventoryData.keySet()) {
    SBLS.DataSourceService.Action action = new SBLS.DataSourceService.Action();
    action.setKeyValue(productCode); // 리스트 레코드와 매핑할 Key 값 설정
    action.putSourceToTargetField(
        inventoryData.get(productCode), // 데이터소스 값: 재고 정보
        'SBLS_Virtual1'                 // 리스트 가상 열 API명
    );
    result.addAction(action); // Action 추가
}
```

{% endstep %}

{% step %}
**반환**

매핑된 결과를 담은 Result 객체를 반환하여, 리스트에 매핑 정보를 전달합니다.
{% endstep %}
{% endstepper %}

***

### :small\_orange\_diamond: SBLS.DataSourceService.Parameter

**리스트의 정보**를 가진 객체입니다. 빌더에서 선택한 필드의 값만 담겨있습니다.

#### 예시 코드

```java
global SBLS.DataSourceService.Result execute(SBLS.DataSourceService.Parameter params) {
    List<SObject> records = params.gets();
    ...
}
```

#### Method

**`List<SObject> gets()`**

검색된 레코드를 반환합니다. 빌더에서 추가한 파라미터가 없는 경우, 값은 비어 있습니다.

***

### :small\_orange\_diamond: SBLS.DataSourceService.Result

리스트와 데이터소스 간의 모든 **매핑 정보를 담아 리스트로 반환**하는 객체입니다. 매핑 정보는 [`SBLS.DataSourceService.Action`](#sbls.datasourceservice.action) 객체에 저장한 뒤, `SBLS.DataSourceService.Result` 객체에 추가하여 반환합니다.

#### 예시 코드

<pre class="language-java" data-title="DataSourceInventory.cls" data-line-numbers><code class="lang-java">...
<strong>SBLS.DataSourceService.Result result = new SBLS.DataSourceService.Result();
</strong>for(String productCode : inventoryData.keySet()) {
    // SBLI.DataSourceService.Action 객체에 매핑 정보 저장
    SBLS.DataSourceService.Action action = new SBLS.DataSourceService.Action();
    action.setKayValue(productCode);
    action.putSourceToTargetField(
        inventoryData.get(productCode),
        'SBLS_Virtual1'
    );
<strong>    result.addAction(action); // 매핑 정보가 담긴 Action을 Result에 추가
</strong>}
return result;
</code></pre>

#### Method

**`addAction(SBLS.DataSourceService.Action action)`**

매핑 정보가 담긴 Action 객체를 Result 객체에 추가합니다.

<table><thead><tr><th width="118">매개변수</th><th>유형</th><th>값</th></tr></thead><tbody><tr><td><strong>action</strong></td><td><a href="#sbls.datasourceservice.action">SBLS.DataSourceService.Action</a></td><td>리스트와 데이터소스 값을 매핑한 정보를 담은 객체입니다.</td></tr></tbody></table>

***

### :small\_orange\_diamond: SBLS.DataSourceService.Action

리스트와 데이터소스 값을 **매핑한 정보를 담은 객체**입니다.

#### 예시 코드

<pre class="language-java" data-title="DataSourceInventory.cls" data-line-numbers><code class="lang-java">SBLS.DataSourceService.Result result = new SBLS.DataSourceService.Result();
// 데이터소스에서 각 제품코드와 재고 정보를 반복 처리
for(String productCode : inventoryData.keySet()) {
<strong>    SBLS.DataSourceService.Action action = new SBLS.DataSourceService.Action();
</strong><strong>    // 제품코드를 Key 값으로 설정하여 조회/라인 아이템과 매핑
</strong><strong>    action.setKayValue(productCode);
</strong><strong>    
</strong><strong>    // 재고 정보를 조회/라인 아이템의 Inventory__c 필드에 매핑 
</strong><strong>    action.putSourceToTargetField(
</strong><strong>        inventoryData.get(productCode),    // 데이터소스 값: 재고
</strong><strong>        'SBLS_Virtual1'                   // 가상 열 API명
</strong><strong>    );
</strong>    result.addAction(action); // 매핑 정보 추가
}
return result; // 최종 결과 반환
</code></pre>

#### Method

**`setKeyValue(Object keyValue)`**

리스트의 Key와 일치하는 데이터소스의 Key 값을 설정합니다.

<table><thead><tr><th width="129">매개변수</th><th width="99">유형</th><th>값</th></tr></thead><tbody><tr><td><strong>keyValue</strong></td><td>Object</td><td>데이터소스의 Key 값입니다.</td></tr></tbody></table>

**`putSourceToTargetField(Object sourceValue, String targetFieldApiName)`**

**데이터소스 값**을 원하는 **리스트 필드** 또는 **가상 열**에 할당합니다.

<table><thead><tr><th width="206">매개변수</th><th width="100">유형</th><th>값</th></tr></thead><tbody><tr><td><strong>sourceValue</strong></td><td>Object</td><td>데이터소스 값입니다.</td></tr><tr><td><strong>targetFieldApiName</strong></td><td>String</td><td>리스트의 필드 또는 가상 열의 API명입니다.</td></tr></tbody></table>
