Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Batch Read for Line Items #60

Merged
merged 1 commit into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/Core/HubSpotAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public enum HubSpotAction

DeleteBatch,

UpdateBatch
UpdateBatch,

ReadBatch
}
}
18 changes: 18 additions & 0 deletions src/Core/Requests/RequestSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,24 @@ public virtual T DeserializeGenericEntity<T>(string json)
return converted;
}

/// <summary>
/// Deserialize the given JSON into a dictionary.
/// </summary>
/// <param name="json">The JSON data returned from a batch read request to HubSpot</param>
/// <returns></returns>
public virtual IDictionary<TKey, TEntity> DeserializeDictionaryOfEntities<TKey, TEntity>(string json) where TEntity : IHubSpotEntity, new()
{
var untypedDictionary = JsonConvert.DeserializeObject<IDictionary<TKey, ExpandoObject>>(json);

var convertedDictionary = new Dictionary<TKey, TEntity>();
foreach (var pair in untypedDictionary)
{
convertedDictionary.Add(pair.Key, _requestDataConverter.FromHubSpotResponse<TEntity>(pair.Value));
}

return convertedDictionary;
}

/// <summary>
/// Deserialize the given JSON into a list of <see cref="IHubSpotEntity"/>
/// </summary>
Expand Down
54 changes: 43 additions & 11 deletions src/LineItem/HubSpotLineItemClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Flurl;
using Flurl;
using Microsoft.Extensions.Logging;
using RapidCore.Network;
using Skarp.HubSpotClient.Core;
Expand Down Expand Up @@ -111,16 +111,7 @@ public Task DeleteBatchAsync(ListOfLineItemIds lineItemIds)
var path = PathResolver(new LineItemHubSpotEntity(), HubSpotAction.Get)
.Replace(":lineItemId:", lineItemId.ToString());

opts ??= new LineItemGetRequestOptions();

if (opts.PropertiesToInclude.Any())
{
path = path.SetQueryParam("properties", opts.PropertiesToInclude);
}
if (opts.IncludeDeletes)
{
path = path.SetQueryParam("includeDeletes", "true");
}
path = ApplyGetRequestOptions(path, opts);

return GetAsync<T>(path);
}
Expand All @@ -144,6 +135,25 @@ public Task DeleteBatchAsync(ListOfLineItemIds lineItemIds)
return ListAsync<T>(path);
}

public async Task<IDictionary<long, T>> ReadBatchAsync<T>(ListOfLineItemIds lineItemIds, LineItemGetRequestOptions opts = null) where T : IHubSpotEntity, new()
{
Logger.LogDebug("Line Item Batch Read");
var path = PathResolver(new LineItemHubSpotEntity(), HubSpotAction.ReadBatch);

path = ApplyGetRequestOptions(path, opts);

var request = _serializer.SerializeEntity(lineItemIds);

IDictionary<long, T> result = null;
var success = await SendRequestAsync(path, HttpMethod.Post, request, response =>
{
result = _serializer.DeserializeDictionaryOfEntities<long, T>(response);
return true;
});

return success ? result : new Dictionary<long, T>();
}

public Task<T> UpdateAsync<T>(ILineItemHubSpotEntity entity) where T : IHubSpotEntity, new()
{
Logger.LogDebug("Line Item update w. id: {0}", entity.Id);
Expand Down Expand Up @@ -205,9 +215,31 @@ internal string PathResolver(ILineItemHubSpotEntity entity, HubSpotAction action
return $"{entity.RouteBasePath}/line_items/batch-delete";
case HubSpotAction.UpdateBatch:
return $"{entity.RouteBasePath}/line_items/batch-update";
case HubSpotAction.ReadBatch:
return $"{entity.RouteBasePath}/line_items/batch-read";
default:
throw new ArgumentOutOfRangeException(nameof(action), action, null);
}
}

private string ApplyGetRequestOptions(string path, LineItemGetRequestOptions opts = null)
{
opts ??= new LineItemGetRequestOptions();

if (opts.PropertiesToInclude.Any())
{
path = path.SetQueryParam("properties", opts.PropertiesToInclude);
}
if (opts.PropertiesWithHistoryToInclude.Any())
{
path = path.SetQueryParam("propertiesWithHistory", opts.PropertiesWithHistoryToInclude);
}
if (opts.IncludeDeletes)
{
path = path.SetQueryParam("includeDeletes", "true");
}

return path;
}
}
}
7 changes: 7 additions & 0 deletions src/LineItem/Interfaces/IHubSpotLineItemClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ public interface IHubSpotLineItemClient
/// <returns></returns>
Task<T> ListAsync<T>(LineItemListRequestOptions opts = null) where T : IHubSpotEntity, new();
/// <summary>
/// Read a batch of line items from hubspot
/// </summary>
/// <param name="lineItemIds"></param>
/// <param name="opts"></param>
/// <returns></returns>
Task<IDictionary<long, T>> ReadBatchAsync<T>(ListOfLineItemIds lineItemIds, LineItemGetRequestOptions opts = null) where T : IHubSpotEntity, new();
/// <summary>
/// Update an existing line item in hubspot
/// </summary>
/// <typeparam name="T"></typeparam>
Expand Down
1 change: 1 addition & 0 deletions src/LineItem/Interfaces/LineItemRequestOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ namespace Skarp.HubSpotClient.LineItem
public class LineItemGetRequestOptions
{
public List<string> PropertiesToInclude { get; set; } = new List<string>();
public List<string> PropertiesWithHistoryToInclude { get; set; } = new List<string>();
public bool IncludeDeletes { get; set; }
}
}
19 changes: 17 additions & 2 deletions test/functional/LineItem/HubSpotLineItemClientFunctionalTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Threading.Tasks;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using RapidCore.Network;
using Skarp.HubSpotClient.Core.Requests;
Expand Down Expand Up @@ -28,7 +28,8 @@ public HubSpotLineItemClientFunctionalTest(ITestOutputHelper output)
.AddTestCase(new UpdateLineItemMockTestCase())
.AddTestCase(new UpdateBatchLineItemMockTestCase())
.AddTestCase(new DeleteLineItemMockTestCase())
.AddTestCase(new DeleteBatchLineItemMockTestCase());
.AddTestCase(new DeleteBatchLineItemMockTestCase())
.AddTestCase(new ReadBatchLineItemMockTestCase());

_client = new HubSpotLineItemClient(
mockHttpClient,
Expand Down Expand Up @@ -176,6 +177,20 @@ public async Task LineItemClient_batch_delete_LineItem_works()
await _client.DeleteBatchAsync(request);
}

[Fact]
public async Task LineItemClient_batch_read_LineItem_works()
{
var request = new ListOfLineItemIds();

request.Ids.Add(9867220);
request.Ids.Add(9867221);

var response = await _client.ReadBatchAsync<LineItemHubSpotEntity>(request);

Assert.Equal(2, response.Count());
Assert.Equal("1645342", response[9845651].ProductId);
}

[Fact]
public async Task LineItemClient_batch_update_LineItem_works()
{
Expand Down
27 changes: 27 additions & 0 deletions test/functional/Mocks/LineItem/ReadBatchLineItemMockTestCase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using RapidCore.Network;
using Skarp.HubSpotClient.Core;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace Skarp.HubSpotClient.FunctionalTests.Mocks.LineItem
{
internal class ReadBatchLineItemMockTestCase : IMockRapidHttpClientTestCase
{
public bool IsMatch(HttpRequestMessage request)
{
return request.RequestUri.AbsolutePath.EndsWith("/crm-objects/v1/objects/line_items/batch-read") && request.Method == HttpMethod.Post;
}

public Task<HttpResponseMessage> GetResponseAsync(HttpRequestMessage request)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);

const string jsonResponse = "{'9845651':{'objectType':'LINE_ITEM','portalId':62515,'objectId':9845651,'properties':{'hs_product_id':{'versions':[{'name':'hs_product_id','value':'1645342','sourceVid':[]}],'value':'1645342','timestamp':0,'source':null,'sourceId':null}},'version':1,'isDeleted':false},'9867373':{'objectType':'LINE_ITEM','portalId':62515,'objectId':9867373,'properties':{'hs_product_id':{'versions':[{'name':'hs_product_id','value':'1645187','sourceVid':[]}],'value':'1645187','timestamp':0,'source':null,'sourceId':null}},'version':1,'isDeleted':false}}";
response.Content = new JsonContent(jsonResponse);
response.RequestMessage = request;

return Task.FromResult(response);
}
}
}
10 changes: 10 additions & 0 deletions test/unit/Core/Requests/RequestSerializerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ public void RequestSerializer_deserializes_list_of_entities()
Assert.DoesNotContain(result, x => string.IsNullOrEmpty(x.Name));
}

[Fact]
public void RequestSerializer_deserializes_dictionary_of_entities()
{
var json = "{'9845651':{'objectType':'LINE_ITEM','portalId':62515,'objectId':9845651,'properties':{'hs_product_id':{'versions':[{'name':'hs_product_id','value':'1645342','sourceVid':[]}],'value':'1645342','timestamp':0,'source':null,'sourceId':null}},'version':1,'isDeleted':false},'9867373':{'objectType':'LINE_ITEM','portalId':62515,'objectId':9867373,'properties':{'hs_product_id':{'versions':[{'name':'hs_product_id','value':'1645187','sourceVid':[]}],'value':'1645187','timestamp':0,'source':null,'sourceId':null}},'version':1,'isDeleted':false}}";
var result = _serializer.DeserializeDictionaryOfEntities<long, LineItemHubSpotEntity>(json);

Assert.Equal(2, result.Count());
Assert.Equal("1645342", result[9845651].ProductId);
}

[Fact]
public void RequestSerializer_serializes_entity_to_namevaluelist()
{
Expand Down
3 changes: 2 additions & 1 deletion test/unit/LineItem/HubSpotLineItemClientTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using FakeItEasy;
using FakeItEasy;
using RapidCore.Network;
using Skarp.HubSpotClient.Core;
using Skarp.HubSpotClient.Core.Requests;
Expand Down Expand Up @@ -63,6 +63,7 @@ private HttpResponseMessage CreateNewEmptyOkResponse()
[InlineData(HubSpotAction.UpdateBatch, "/crm-objects/v1/objects/line_items/batch-update")]
[InlineData(HubSpotAction.Delete, "/crm-objects/v1/objects/line_items/:lineItemId:")]
[InlineData(HubSpotAction.DeleteBatch, "/crm-objects/v1/objects/line_items/batch-delete")]
[InlineData(HubSpotAction.ReadBatch, "/crm-objects/v1/objects/line_items/batch-read")]
public void LineItemClient_path_resolver_works(HubSpotAction action, string expectedPath)
{
var resvoledPath = _client.PathResolver(new LineItemHubSpotEntity(), action);
Expand Down