Skip to content

Commit

Permalink
Merge branch 'm0a0k0s-ApiLimits'
Browse files Browse the repository at this point in the history
  • Loading branch information
giacomelli committed Sep 24, 2020
2 parents 676c134 + 729edd1 commit 1703e61
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/SalesforceSharp.FunctionalTests/SalesforceClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,8 @@ public void GetRawBytes_ValidRecord()
Assert.IsNotNull(actual);
Assert.That(actual.Contains(string.Format("\"FirstName\":\"{0}\"", record.FirstName)));
Assert.That(actual.Contains(string.Format("\"LastName\":\"{0}\"", record.LastName)));
Assert.AreNotEqual(target.ApiCallsUsed, 0);
Assert.AreEqual(target.ApiCallsLimit, 15000);
}
#endregion

Expand Down
33 changes: 33 additions & 0 deletions src/SalesforceSharp/SalesforceClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using HelperSharp;
using Newtonsoft.Json.Linq;
using RestSharp;
Expand All @@ -23,6 +24,7 @@ public class SalesforceClient
private IRestClient m_restClient;
private GenericJsonDeserializer genericJsonDeserializer;
private GenericJsonSerializer updateJsonSerializer;
private static readonly Regex apiUsageRegexp = new Regex(@"api-usage=(\d+)/(\d+)", RegexOptions.Compiled);
#endregion

#region Constructors
Expand Down Expand Up @@ -75,6 +77,22 @@ protected internal SalesforceClient(IRestClient restClient)
/// The instance URL.
/// </value>
public string InstanceUrl { get; private set; }

/// <summary>
/// Get current API calls number
/// </summary>
/// <value>
/// current API calls number
/// </value>
public int ApiCallsUsed { get; private set; }

/// <summary>
/// Get total API calls limit
/// </summary>
/// <value>
/// API calls limit
/// </value>
public int ApiCallsLimit { get; private set; }
#endregion

#region Methods
Expand Down Expand Up @@ -461,6 +479,7 @@ protected IRestResponse RequestRaw(string baseUrl, string objectName = null, obj

var response = m_restClient.Execute(request);
CheckApiException(response);
ExtractLimitsInfo(response);

return response;
}
Expand Down Expand Up @@ -522,6 +541,20 @@ private void CheckApiException(IRestResponse response)
throw ex;
}
}

private void ExtractLimitsInfo(IRestResponse response)
{
var limitHeader = response.Headers?.FirstOrDefault(h => h.Name == "Sforce-Limit-Info");
if (limitHeader?.Value != null)
{
var match = apiUsageRegexp.Match(limitHeader.Value.ToString());
if (match.Success)
{
ApiCallsUsed = int.Parse(match.Groups[1].Value);
ApiCallsLimit = int.Parse(match.Groups[2].Value);
}
}
}
#endregion

#region Helpers
Expand Down

0 comments on commit 1703e61

Please sign in to comment.