Skip to content

Commit

Permalink
Retrieve multiple contacts in a single API call
Browse files Browse the repository at this point in the history
Resolves #385
  • Loading branch information
Jericho committed Apr 13, 2021
1 parent 6cf2782 commit 752d27a
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ public async Task RunAsync(IClient client, TextWriter log, CancellationToken can

if (contacts.Any())
{
var batch = await client.Contacts.GetMultipleAsync(contacts.Take(10).Select(c => c.Id), cancellationToken).ConfigureAwait(false);
await log.WriteLineAsync($"Retrieved {batch.Length} contacts in a single API call.").ConfigureAwait(false);
foreach (var record in batch)
{
await log.WriteLineAsync($"\t{record.FirstName} {record.LastName}").ConfigureAwait(false);
}

var contact = await client.Contacts.GetAsync(contacts.First().Id).ConfigureAwait(false);
await log.WriteLineAsync($"Retrieved contact {contact.Id}").ConfigureAwait(false);
await log.WriteLineAsync($"\tEmail: {contact.Email}").ConfigureAwait(false);
Expand Down
22 changes: 22 additions & 0 deletions Source/StrongGrid/Resources/Contacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,28 @@ public Task<Contact> GetAsync(string contactId, CancellationToken cancellationTo
.AsObject<Contact>();
}

/// <summary>
/// Retrieve multiple contacts.
/// </summary>
/// <param name="contactIds">An enumeration of contact identifiers.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// An array of <see cref="Contact" />.
/// </returns>
public Task<Contact[]> GetMultipleAsync(IEnumerable<string> contactIds, CancellationToken cancellationToken = default)
{
var data = new JObject()
{
{ "ids", new JArray(contactIds) }
};

return _client
.PostAsync($"{_endpoint}/batch")
.WithJsonBody(data)
.WithCancellationToken(cancellationToken)
.AsObject<Contact[]>("result");
}

/// <summary>
/// Searches for contacts matching the specified conditions.
/// </summary>
Expand Down
10 changes: 10 additions & 0 deletions Source/StrongGrid/Resources/IContacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,16 @@ Task<string> UpsertAsync(
/// </returns>
Task<Contact> GetAsync(string contactId, CancellationToken cancellationToken = default);

/// <summary>
/// Retrieve multiple contacts.
/// </summary>
/// <param name="contactIds">An enumeration of contact identifiers.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// An array of <see cref="Contact" />.
/// </returns>
Task<Contact[]> GetMultipleAsync(IEnumerable<string> contactIds, CancellationToken cancellationToken = default);

/// <summary>
/// Searches for contacts matching the specified conditions.
/// </summary>
Expand Down

0 comments on commit 752d27a

Please sign in to comment.