Open1

[Unity] API

gonCgonC
API
using UnityEngine;
using UnityEngine.Networking;
using Cysharp.Threading.Tasks;
using System;
namespace Test
{
  /// <summary>
  /// Responseベース
  /// </summary>
  [Serializable]
  public class BaseResponse
  {
    public bool ok;
    public string error;
  }
  [Serializable]
  public class MapInfoResponse : BaseResponse
  {
    public POIData[] poi;
    public Node[] node;
    public string weather;
  }
  [Serializable]
  public class POIData
  {
    public long id;
    public long s2_l17_id;
    public string name;
    public Geometry geometry;
  }
  [Serializable]
  public class Node
  {
    public long id;
    public long s2_l17_id;
    public Geometry geometry;
  }
  [Serializable]
  public class Geometry
  {
    public double latitude;
    public double longitude;
    public DateTime available_at;
  }
  public class MapInfoRequest
  {
    public double latitude;
    public double longitude;
  }
  public class Test : MonoBehaviour
  {
    /// <summary>
    /// Map情報取得
    /// </summary>
    /// <param name="lat"></param>
    /// <param name="lng"></param>
    /// <returns></returns>
    public static async UniTask<string> ConnectMapInfo(double lat, double lng)
    {
      MapInfoRequest postData = new MapInfoRequest();
      postData.latitude = lat;
      postData.longitude = lng;
      return await ConnectLamdaPostAPI(API.API_MAP_INFO, JsonUtility.ToJson(postData));
    }
    public static MapInfoResponse GetMapInfo()
    {
      return GetResponseAPI<MapInfoResponse>(API.API_MAP_INFO);
    }
    //////////////////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Get
    /// </summary>
    public static async UniTask<string> ConnectGetAPI(string api, string data)
    {
      string endpoint = API.BASE_URL + api;
      if (data.Length > 0) endpoint += "?" + data;
      using var request = UnityWebRequest.Get(endpoint);
      request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      return await ConnectAPI(request, api);
    }
    /// <summary>
    /// POST
    /// </summary>
    public static async UniTask<string> ConnectPostAPI(string api, WWWForm formData)
    {
      string endpoint = API.BASE_URL + api;
      UnityWebRequest request = UnityWebRequest.Post(endpoint, formData);
      request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      return await ConnectAPI(request, api);
    }
    /// <summary>
    /// Lamda Get
    /// </summary>
    public static async UniTask<string> ConnectLamdaGetAPI(string api, string data)
    {
      string endpoint = API.BASE_URL_LAMDA + api + "?" + data;
      Debug.Log(endpoint);
      using var request = UnityWebRequest.Get(endpoint);
      //var data = System.Text.Encoding.UTF8.GetBytes(jsonData);
      request.SetRequestHeader("content-type", "application/json");
      //request.uploadHandler = new UploadHandlerRaw(data);
      request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
      return await ConnectAPI(request, api);
    }
    /// <summary>
    /// Lamda POST
    /// </summary>
    public static async UniTask<string> ConnectLamdaPostAPI(string api, string jsonData)
    {
      string endpoint = API.BASE_URL_LAMDA + api;
      var data = System.Text.Encoding.UTF8.GetBytes(jsonData);
      using var request = new UnityWebRequest(endpoint, UnityWebRequest.kHttpVerbPOST)
      {
        uploadHandler = new UploadHandlerRaw(data),
        downloadHandler = new DownloadHandlerBuffer()
      };
      request.SetRequestHeader("content-type", "application/json");
      return await ConnectAPI(request, api);
    }
    /// <summary>
    /// API疎通
    /// </summary>
    private static async UniTask<string> ConnectAPI(UnityWebRequest request, string api)
    {
      Debug.Log($"[API] {api}");
      //string token = PlayerPrefs.GetString(ACCESS_TOKEN, "");
      string token = "t8s_test_token";
      if (!string.IsNullOrEmpty(token))
      {
        request.SetRequestHeader("Authorization", $"Bearer {token}");
      }
      request.SetRequestHeader("Accept", "application/json");
      request.SetRequestHeader("user-agent", UnityWebRequest.EscapeURL(GetUserAgent()));
      request.timeout = 10;
      try
      {
        await request.SendWebRequest();
      }
      catch (UnityWebRequestException ex)
      {
        Debug.LogError(ex.Error);
        if (ex.Error == "Request timeout")
        {
          return ErrorMessage.TIMEOUT;
        }
        return ErrorMessage.NETWORK;
      }
      // レスポンスを取得
      string json = request.downloadHandler.text;
      request.Dispose();
      Debug.Log($"[API] response: {json}");
      BaseResponse responseObject = JsonUtility.FromJson<BaseResponse>(json);
      if (!responseObject.ok)
      {
        Debug.Log(responseObject.error);
        return responseObject.error;
      }
      //PlayerPrefsにJSONを格納
      PlayerPrefs.SetString(api, json);
      return "";
    }
    /// <summary>
    /// PlayerPrefsからjsonデータを取得する
    /// </summary>
    /// <typeparam name = "Type" ></ typeparam >
    /// < param name="key"></param>
    /// <returns></returns>
    private static Type GetResponseAPI<Type>(string key)
    {
      string json = PlayerPrefs.GetString(key, "");
      return JsonUtility.FromJson<Type>(json);
    }
    private static string GetUserAgent()
    {
      return Application.productName + "/" + Application.version + " " + SystemInfo.operatingSystem;
    }
  }
}