# 외부 서비스와 연동

> Extend Cloud Code modules with external services using NuGet packages or HTTP clients.

Cloud Code 모듈을 외부 서비스와 연동할 수 있습니다.

커스텀 데이터 유형을 처리하기 위해 [커스텀 JSON 직렬화](./initialize-modules/custom-serialization.md)를 구현할 수 있습니다.

## NuGet 패키지 사용##use-nuget-packages

Cloud Code 모듈은 .NET 생태계에 속한 C# 라이브러리 프로젝트이므로 [NuGet 패키지 관리자](https://learn.microsoft.com/en-us/nuget/)를 사용하여 종속성을 설치합니다. 즉, Cloud Code 모듈에서 외부 NuGet 패키지를 사용할 수 있습니다.

사용 가능한 NuGet 패키지를 확인하려면 [NuGet 패키지 라이브러리](https://www.nuget.org/)를 참고하십시오.

## 외부 API 호출##call-out-to-external-apis

외부 API를 호출할 수도 있습니다. 아래 샘플은 [Cat Facts API](https://catfact.ninja/#/facts/getrandomfact)를 호출하여 고양이에 관한 무작위 정보를 가져옵니다.

1. API 호출을 처리할 `CatFactsApi` 클래스를 선언합니다.

   ```csharp
   using Newtonsoft.Json;
   using RestSharp;
   using Unity.Services.CloudCode.Core;
   using Unity.Services.CloudCode.Shared;

   namespace CatFacts;

   public interface ICatFactsApi
   {
       public Task<CatFactsApiResponse?> GetCatFact();
   }

   public class CatFactsApiResponse
   {
       public string fact { get; set; }
       public int length { get; set; }
   }

   public class CatFactsApi : ICatFactsApi
   {
       private readonly RestClient _httpClient;

       public CatFactsApi()
       {
           // It's important to only create one RestClient per service in order to avoid creating and destroying too many network connections which could hurt performance
           _httpClient = new RestClient("https://catfact.ninja/fact");
       }

       public async Task<CatFactsApiResponse?> GetCatFact()
       {
           var request = new RestRequest();

           try
           {
               var res = await _httpClient.ExecuteGetAsync(request);
               return JsonConvert.DeserializeObject<CatFactsApiResponse?>(res.Content);
           }
           catch (ApiException e)
           {
               throw new Exception($"Failed to get cat fact: {e.Message}");
           }
       }
   }
   ```

2. `ModuleConfig` 클래스에서 `CatFactsApi` 클래스를 싱글톤으로 선언합니다.

   ```csharp
       public class ModuleConfig : ICloudCodeSetup
       {
           public void Setup(ICloudCodeConfig config)
           {
               config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi());
           }
       }
   ```

3. `CatFactsApi` 클래스의 `GetCatFact` 메서드를 호출하는 `GetCatFact` 함수를 선언합니다.

   ```csharp
   using Microsoft.Extensions.DependencyInjection;
   using Microsoft.Extensions.Logging;
   using Unity.Services.CloudCode.Core;
   using Unity.Services.CloudCode.Shared;

   namespace CatFacts;

   public class CatFactsSample
   {
       private static ILogger<CatFactsSample> _logger;
       public CatFactsSample(ILogger<CatFactsSample> logger)
       {
           _logger = logger;
       }

       [CloudCodeFunction("GetCatFact")]
       public async Task<CatFactsApiResponse?> GetCatFact(ICatFactsApi catFactsApi)
       {
           try
           {
               var fact = await catFactsApi.GetCatFact();
               _logger.LogInformation("Cat fact: {fact}", fact?.fact);

               return fact;

           }
           catch (ApiException e)
           {
               _logger.LogError("Failed to get cat fact. Error: {Error}", e.Message);
               throw new Exception($"Failed to get cat fact: {e.Message}");
           }
       }

       public class ModuleConfig : ICloudCodeSetup
       {
           public void Setup(ICloudCodeConfig config)
           {
               config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi());
           }
       }
   }
   ```

4. 게임 클라이언트에서 `GetCatFact` 함수를 호출합니다. 이 함수는 고양이에 관한 무작위 정보를 반환합니다.

   ```json
   {
       "output": {
           "fact": "The Amur leopard is one of the most endangered animals in the world.",
           "length": 68
       }
   }
   ```

Unity 서비스와 연동하는 방법에 대한 자세한 내용은 [다른 Unity 서비스와 연동](./unity-services-integration.md)을 참고하십시오.
