Home > OS >  Retrieve ID created by Firebase Post
Retrieve ID created by Firebase Post

Time:01-16

I am using Firebase API for Unity and I am pushing some data to the realtime database using the Post request Right after using that Post request I need the created ID for the new node to do something else but I am not sure how to retrieve that ID.

Firebase.Instance.Post(uri, new Dictionary<string, string>() { { "name", name } },
     delegate { Debug.Log("Name has been added successfully!");  //here is where i need the new ID to do something else },
     delegate { Debug.Log("Something Wrong! .. Please try again later"); });

The post function:

public void Post<T, K>(URI uri, T body, System.Action<K> onSuccess, System.Action<string> onFail)
        {
            RequestHelper currentRequest = new RequestHelper
            {
                Uri = uri.Path,
                BodyString = JsonConvert.SerializeObject(body),

                IgnoreHttpException = true
            };
            Debug.Log("BODY_post: "   currentRequest.BodyString);
            RestClient.Post(currentRequest, (exception, res) => ResolveResponse(exception, res, onSuccess, onFail));
        }

void ResolveResponse<T>(RequestException exception, ResponseHelper res, System.Action<T> onSuccess, System.Action<string> onFail)
        {
            string returnedText = res.Text;
            AuthError authError = null;

            try
            {
                authError = JsonConvert.DeserializeObject<AuthError>(returnedText);
            }
            catch (System.Exception ex)
            {
                Debug.Log(ex);
            }
            finally
            {
                if (authError != null && authError.error != null && authError.error.message != null)
                {
                    onFail(BeautifyMessage(authError.error.message));
                }
                else if (exception != null && (exception.IsHttpError || exception.IsNetworkError))
                {
                    onFail(BeautifyMessage(exception.Message));
                }
                else if (typeof(T) == typeof(string))
                {
                    onSuccess((T)(object)returnedText);
                }
                else
                {
                    onSuccess(JsonConvert.DeserializeObject<T>(returnedText));
                }
            }
        }

And it calls to the rest api's library post function.

CodePudding user response:

You are wrapping the Firebase REST API, where calling POST returns the key in the response:

A successful request is indicated by a 200 OK HTTP status code. The response contains the child name of the new data specified in the POST request.

{ "name": "-INOQPH-aV_psbk3ZXEX" }

So your response handler will need to parse that result, and return the "-IN...." key back to the caller.

  •  Tags:  
  • Related