Skip to content

Code Generation

AQaddora edited this page May 3, 2025 · 2 revisions

Code Generation Guide

This guide explains the code generation options and features available in REST Express.

Table of Contents

Basic Configuration

Script Settings

// Basic settings
ScriptName = "ApiClient"           // Generated class name
OutputPath = "Assets/GeneratedScripts"  // Where to save generated files

Class Structure

// Generated code structure
public class ApiClient : MonoBehaviour
{
    private static ApiClient instance;
    public static ApiClient Instance { get; }
    
    private void Awake() { }
    
    // Collection Variables
    private const string baseUrl = "http://localhost:3000";
    private const string userId = "0001";
    private const string levelId = "1";
    
    // API Methods
    #region User_Management
    // User management methods
    #endregion
    
    #region Game_Progress
    // Game progress methods
    #endregion
}

Method Generation

Basic Method Structure

public void MethodName(
    string param1 = "default1",
    string param2 = "default2",
    Action<string> onSuccess = null,
    Action<string> onError = null)
{
    string requestUrl = $"{baseUrl}/endpoint";
    var form = new WWWForm();
    form.AddField("param1", param1);
    form.AddField("param2", param2);
    SendFormRequest(requestUrl, "POST", onSuccess, onError, form, null);
}

GET Request

public void GetResource(
    string resourceId,
    Action<string> onSuccess = null,
    Action<string> onError = null)
{
    string requestUrl = $"{baseUrl}/resources/{resourceId}";
    SendRequest(requestUrl, "GET", onSuccess, onError, null, null);
}

POST Request with Form Data

public void CreateResource(
    string name,
    string description,
    Action<string> onSuccess = null,
    Action<string> onError = null)
{
    string requestUrl = $"{baseUrl}/resources";
    var form = new WWWForm();
    form.AddField("name", name);
    form.AddField("description", description);
    SendFormRequest(requestUrl, "POST", onSuccess, onError, form, null);
}

Request Types

Form Data Requests

private IEnumerator SendFormRequestCoroutine(
    string url,
    string method,
    Action<string> onSuccess = null,
    Action<string> onError = null,
    WWWForm form = null,
    Dictionary<string, string> headers = null)
{
    using (UnityWebRequest request = new UnityWebRequest(url, method))
    {
        request.downloadHandler = new DownloadHandlerBuffer();
        
        if (form != null)
        {
            request.uploadHandler = new UploadHandlerRaw(form.data);
            request.SetRequestHeader("Content-Type", "multipart/form-data");
        }
        
        yield return request.SendWebRequest();
        
        if (request.result == UnityWebRequest.Result.ConnectionError || 
            request.result == UnityWebRequest.Result.ProtocolError)
        {
            onError?.Invoke($"Status: {request.responseCode}, Error: {request.error}");
        }
        else
        {
            onSuccess?.Invoke(request.downloadHandler.text);
        }
    }
}

File Upload

public void UploadFile(
    string filePath,
    string description,
    Action<string> onSuccess = null,
    Action<string> onError = null)
{
    string requestUrl = $"{baseUrl}/upload";
    var form = new WWWForm();
    form.AddField("description", description);
    
    if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath))
    {
        byte[] fileData = System.IO.File.ReadAllBytes(filePath);
        string fileName = System.IO.Path.GetFileName(filePath);
        form.AddBinaryData("file", fileData, fileName);
    }
    
    SendFormRequest(requestUrl, "POST", onSuccess, onError, form.data, null);
}

Response Handling

Success Callback

ApiClient.Instance.GetResource(
    "123",
    onSuccess: (response) => {
        Debug.Log($"Resource data: {response}");
        // Handle success
    },
    onError: (error) => {
        Debug.LogError($"Error: {error}");
        // Handle error
    }
);

Error Handling

private IEnumerator SendRequestCoroutine(
    string url,
    string method,
    Action<string> onSuccess = null,
    Action<string> onError = null,
    string jsonBody = null,
    Dictionary<string, string> headers = null)
{
    using (UnityWebRequest request = new UnityWebRequest(url, method))
    {
        request.downloadHandler = new DownloadHandlerBuffer();
        
        if (!string.IsNullOrEmpty(jsonBody))
        {
            var bodyRaw = Encoding.UTF8.GetBytes(jsonBody);
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.SetRequestHeader("Content-Type", "application/json");
        }
        
        yield return request.SendWebRequest();
        
        if (request.result == UnityWebRequest.Result.ConnectionError || 
            request.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.LogError($"Request error ({request.responseCode}): {request.error}");
            onError?.Invoke($"Status: {request.responseCode}, Error: {request.error}");
        }
        else
        {
            Debug.Log($"Request successful: {method} {url}");
            onSuccess?.Invoke(request.downloadHandler.text);
        }
    }
}

Best Practices

  1. Method Organization

    #region User_Management
    public void CreateUser() { }
    public void GetUserProfile() { }
    #endregion
    
    #region Game_Progress
    public void SaveProgress() { }
    public void LoadProgress() { }
    #endregion
  2. Error Handling

    ApiClient.Instance.CreateUser(
        onSuccess: (response) => {
            // Handle success
        },
        onError: (error) => {
            Debug.LogError($"Error: {error}");
            // Show error to user
        }
    );
  3. File Uploads

    public void UploadProfilePicture(
        string imagePath,
        Action<string> onSuccess = null,
        Action<string> onError = null)
    {
        if (!System.IO.File.Exists(imagePath))
        {
            onError?.Invoke("File not found");
            return;
        }
        
        // Continue with upload
    }

For more examples and best practices, check the Examples guide.

Clone this wiki locally