본문으로 건너뛰기

클라우드코드 실행

서버에 등록된 클라우드코드 함수를 실행합니다.

URL 확인

이 API는 service-api.playnanoo.com 도메인을 사용합니다.

API 정보​

  • URL: https://service-api.playnanoo.com/cloudcode/v20210901/run
  • Method: PUT
  • 인증 필요: 예
DeviceInfo 상속

이 API의 Req 클래스는 DeviceInfo를 상속받습니다. DeviceInfo의 모든 속성이 자동으로 포함됩니다.

요청 파라미터​

파라미터타입필수설명
table_codestring필수클라우드코드 테이블 코드
function_namestring필수실행할 함수 이름
function_argumentsstring필수함수 인자 (JSON 문자열)

응답 데이터​

Res 클래스​

필드타입설명
FunctionFunctionModel실행된 함수 정보
LogsList<LogModel>함수 실행 로그
ResultResultModel함수 실행 결과
Errorstring에러 메시지 (에러 발생 시)
RunTimeMilliSecondsint실행 시간 (밀리초)

FunctionModel 클래스​

필드타입설명
Namestring함수 이름
Versionstring함수 버전

LogModel 클래스​

필드타입설명
levelstring로그 레벨
messagestring로그 메시지

ResultModel 클래스​

필드타입설명
messagestring결과 메시지

Unity C# 구현​

BaseResponse 클래스​

모든 API 응답의 기본 클래스입니다.

public class BaseResponse
{
public string ErrorCode;
public string Message;
public string WithdrawalKey;
public string BlockKey;
}

필드 설명:

  • ErrorCode: 에러 코드
  • Message: 에러 메시지
  • WithdrawalKey: 탈퇴 유예 상태인 경우 복구에 필요한 키 (탈퇴 유예 중인 계정만 제공)
  • BlockKey: 차단된 계정인 경우 제공되는 키 (차단된 계정만 제공)

클라우드코드 실행 클래스​

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class CloudCodeExecution
{
static string path = "https://service-api.playnanoo.com/cloudcode/v20210901/run";

[Serializable]
public class Req : DeviceInfo
{
public string table_code;
public string function_name;
public string function_arguments;

public IEnumerator Send(CloudCodeParameters param, Action<Res> onSuccess, Action<BaseResponse> onError)
{
this.table_code = param.table_code;
this.function_name = param.function_name;
this.function_arguments = JsonUtility.ToJson(param.function_arguments);

yield return HttpClient.Send<Req, Res>(
UnityWebRequest.kHttpVerbPUT,
path,
requireToken: true,
body: this,
onSuccess: onSuccess,
onError: onError
);
}
}

[Serializable]
public class Res : BaseResponse
{
public FunctionModel Function;
public List<LogModel> Logs = new List<LogModel>();
public ResultModel Result;
public string Error;
public int RunTimeMilliSeconds;
}

[Serializable]
public class FunctionModel
{
public string Name;
public string Version;
}

[Serializable]
public class LogModel
{
public string level;
public string message;
}

[Serializable]
public class ResultModel
{
public string message;
}

[Serializable]
public class CloudCodeParameters
{
public string table_code;
public string function_name;
public object function_arguments;
}

[Serializable]
public class FunctionArguments
{
public string InputValue1;
public string InputValue2;
public string InputValue3;
}
}

사용 예제​

기본 사용법​

using PlayNANOO;

public class PlayNANOOExample : MonoBehaviour
{
void ExecuteCloudCode()
{
CloudCodeExecution.Req req = new CloudCodeExecution.Req();

// 함수 인자 설정
CloudCodeExecution.FunctionArguments args = new CloudCodeExecution.FunctionArguments
{
InputValue1 = "value1",
InputValue2 = "value2",
InputValue3 = "value3"
};

// 파라미터 설정
CloudCodeExecution.CloudCodeParameters param = new CloudCodeExecution.CloudCodeParameters
{
table_code = "cloudcode_table",
function_name = "MyFunction",
function_arguments = args
};

StartCoroutine(req.Send(
param: param,
onSuccess: res =>
{
Debug.Log($"함수 실행 성공: {res.Function.Name} v{res.Function.Version}");
Debug.Log($"실행 시간: {res.RunTimeMilliSeconds}ms");
Debug.Log($"결과: {res.Result.message}");

// 로그 출력
foreach (var log in res.Logs)
{
Debug.Log($"[{log.level}] {log.message}");
}
},
onError: (error) =>
{
Debug.LogError($"클라우드코드 실행 실패: [{error.ErrorCode}] [{error.Message}]");
}
));
}
}

서버 로직 실행​

using PlayNANOO;
using UnityEngine;

public class ServerLogicExample : MonoBehaviour
{
void CalculateReward(int level, int score)
{
CloudCodeExecution.Req req = new CloudCodeExecution.Req();

// 보상 계산을 위한 인자
var args = new
{
PlayerLevel = level,
GameScore = score,
BonusMultiplier = 1.5f
};

CloudCodeExecution.CloudCodeParameters param = new CloudCodeExecution.CloudCodeParameters
{
table_code = "game_logic",
function_name = "CalculateReward",
function_arguments = args
};

StartCoroutine(req.Send(
param: param,
onSuccess: res =>
{
if (string.IsNullOrEmpty(res.Error))
{
Debug.Log($"보상 계산 완료: {res.Result.message}");
Debug.Log($"실행 시간: {res.RunTimeMilliSeconds}ms");
}
else
{
Debug.LogError($"서버 로직 에러: {res.Error}");
}
},
onError: (error) =>
{
Debug.LogError($"API 호출 실패: {error.Message}");
}
));
}
}

데이터 검증​

using PlayNANOO;
using UnityEngine;

public class DataValidationExample : MonoBehaviour
{
void ValidateGameData(string userId, int itemId, int quantity)
{
CloudCodeExecution.Req req = new CloudCodeExecution.Req();

var args = new
{
UserId = userId,
ItemId = itemId,
Quantity = quantity
};

CloudCodeExecution.CloudCodeParameters param = new CloudCodeExecution.CloudCodeParameters
{
table_code = "validation",
function_name = "ValidateItemPurchase",
function_arguments = args
};

StartCoroutine(req.Send(
param: param,
onSuccess: res =>
{
if (string.IsNullOrEmpty(res.Error))
{
Debug.Log("데이터 검증 통과");

// 로그 확인
foreach (var log in res.Logs)
{
if (log.level == "error")
{
Debug.LogWarning($"경고: {log.message}");
}
}

// 구매 처리 계속 진행
ProcessPurchase();
}
else
{
Debug.LogError($"데이터 검증 실패: {res.Error}");
ShowErrorMessage("구매할 수 없는 아이템입니다.");
}
},
onError: (error) =>
{
Debug.LogError($"검증 API 실패: {error.Message}");
}
));
}

void ProcessPurchase()
{
// 구매 처리 로직
}

void ShowErrorMessage(string message)
{
// UI 에러 메시지 표시
Debug.Log(message);
}
}
클라우드코드 활용

클라우드코드를 사용하면 게임 로직을 서버에서 실행하여 클라이언트 조작을 방지하고, 복잡한 계산이나 데이터 검증을 안전하게 처리할 수 있습니다.

함수 인자

function_arguments는 object 타입으로, 익명 객체나 직렬화 가능한 클래스를 전달할 수 있습니다. 내부적으로 JSON 문자열로 변환됩니다.

실행 시간

클라우드코드 함수의 실행 시간이 너무 길면 타임아웃이 발생할 수 있습니다. 효율적인 코드 작성을 권장합니다.

로그 활용

함수 실행 중 발생한 로그를 Logs 필드를 통해 확인할 수 있습니다. 디버깅과 모니터링에 활용하세요.