Backend Provider: Custom

The Venly Gaming Toolkit is built with extensibility in mind, and offers a way to relay and format the API calls to fit your custom Backend Solution.

The following steps are required to create a Custom Backend Provider

  1. Create a class that derives from VyProviderBase (with optional Extension Support)
  2. Register the Provider with the Venly SDK

Each provider that you create is identified by a unique name (providerType). You can create and register as many custom providers as you want as long as the providerType does not exist already.

Creating a Backend Provider implementation

In order to create an implementation for a Custom Backend Solution, you'll have to create a class that inherits from the VyProviderBase baseclass. This class will allow you to implement your custom backend communication logic.

Example DevMode: VyProvider_DevMode.cs

The code below gives you a good starting point to define a Custom Provider. The snippet is a provider that communicates with a local Node Server.

using System;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
using VenlySDK;
using VenlySDK.Backends;
using VenlySDK.Core;
using VenlySDK.Utils;

public class MyCustomProvider : VyProviderBase
{
    //The 'providerType' can be anything you want
    //as long as it is unique amongst other providers
    public MyCustomProvider() : base("NodeJS_Backend")
    {
    }

    //This function will register the Provider once Unity Loaded all Assemblies
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    static void Register()
    {
        Venly.RegisterProvider(new MyCustomProvider());
    }

    //This function is called whenever an API call is made
    //Here you want to sent the information (VyRequestData) to your backend
    public override VyTask<T> MakeRequest<T>(VyRequestData requestData)
    {
        //Create Task
        var taskNotifier = VyTask<T>.Create();

        //Check if we need to start another Thread
        if (Thread.CurrentThread.IsBackground) HttpRequestAction();
        else Task.Run(HttpRequestAction);

        async void HttpRequestAction()
        {
            try
            {
                //Execute Request
                //-------------

                //Create Request
                var requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5000/execute");
                requestMessage.Content = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8,
                    "application/json");

                //Send Request to Backend & Process Response
                using HttpClient client = new();
                var response = await client.SendAsync(requestMessage);
                var result = VenlyUtils.ProcessHttpResponse<T>(response, requestData);

                //Done
                taskNotifier.Notify(result);
            }
            catch (Exception ex)
            {
                taskNotifier.NotifyFail(ex);
            }
        }

        return taskNotifier.Task;
    }
}

📘

The MakeRequest function is called each time an API call is made from your client. The requestData parameter contains all the information you need to relay the request to your Backend. The easiest strategy is to execute the corresponding API call on your Backend and send the response back without further processing.

📘

The Backend Libraries can also be used to automatically process these requests on your backend. Additionally, the Client SDK contains helper functions to process raw Venly API responses into usable SDK objects. More info about processing requests later in this guide.

Passing External Data to your Requester

It is possible that your requester requires some external data in order to be able to make a request to your Backend (a temporary User Token for instance) - to facilitate this the requester has an internal key-value storage system which you can easily query using the GetData<T>(...) function. Of course, you'll have to make sure that the data is set before trying to query for a specific key.

Example DevMode: VyProvider_PlayFab.cs

//Outside your Custom Requester
//-----------------------------
//Somewhere outside the CustomRequester class,
//could be after the user logged in and you received a UserToken
//to interact with your backend
Venly.SetRequesterData("user-token", tokenValue);

//Inside your Custom Requester
//----------------------------
//Inside the CustomRequester class you can access these key-value pairs
public override VyTask<T> MakeRequest<T>(VyRequestData requestData)
{
    var taskNotifier = VyTask<T>.Create();

    var userToken = GetData<string>("user-token");
    //Your Backend Interaction Logic
    //...

    return taskNotifier.Task;
}

//Optionally, you can also override the OnSetData function
//to preprocess keys that are set through the API
protected override void OnSetData(string key, object data)
{
    if(key.Equals("user-token")
    {
        //...
    }
}

Now you can select your custom provider with the SDK Manager (Settings > Backend = 'Custom' / set 'providerType').

👍

All Venly API calls will now run through your custom implementation!

Request Processing

The API contains some helper function to process responses coming from the Venly API endpoints. Examples of how to parse the data can be found in the built-in provider source code

Processing a Venly API Endpoint Response (string)

If the response from one of the Venly API Endpoints returns a Response wrapped payload (= {success:... , result:... , errors: ..., ...}, you can use the VenlyUtils.ProcessApiResponse<T> function. (The RequestData object is required)

//Some Pseudocode
//Make call to Venly Endpoint
var response = httpClient.GetResponse();
var body = response.body;
var statusCode = response.statusCode

//The following function parses the Venly Enpoind Response, T would be the payload type
VyTaskResult<T> result = VenlyUtils.ProcessApiResponse<T>(body, statusCode, requestData);