# 与外部服务集成

> 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 Package Manager](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) 来获取随机的 cat fact。

1. 声明一个 `CatFactsApi` 类来处理 API 调用。

   ```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. 将这个 `CatFactsApi` 类声明为 `ModuleConfig` 类中的单例。

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

3. 声明一个 `GetCatFact` 函数来调用 `CatFactsApi` 类的 `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` 函数。此函数返回一个随机的 cat fact：

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

如需有关如何与 Unity 服务集成的信息，请参阅[与其他 Unity 服务集成](./unity-services-integration.md)。
