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

Client refactor with new api names for JSON format #266

Closed
wants to merge 2 commits into from
Closed
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
8 changes: 4 additions & 4 deletions .code-samples.meilisearch.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ getting_started_add_documents_md: |-
var movies = JsonSerializer.Deserialize<IEnumerable<Movie>>(jsonString, options);

var index = client.Index("movies");
await index.AddDocumentsAsync<Movie>(movies);
await index.AddDocumentsJsonAsync<Movie>(movies);
}
}
}
Expand Down Expand Up @@ -164,7 +164,7 @@ getting_started_add_meteorites: |-
var meteorites = JsonSerializer.Deserialize<IEnumerable<Meteorite>>(jsonString, options);

var index = client.Index("meteorites");
await index.AddDocumentsAsync<Meteorite>(meteorites);
await index.AddDocumentsJsonAsync<Meteorite>(meteorites);
getting_started_update_rankingRules: |-
await client.Index("movies").UpdateRankingRulesAsync(new string[] {
"exactness",
Expand Down Expand Up @@ -256,7 +256,7 @@ landing_getting_started_1: |-
new Movie { Id = "6", Title = "Philadelphia" }
};

var task = await client.Index("movies").AddDocumentsAsync<Movie>(documents);
var task = await client.Index("movies").AddDocumentsJsonAsync<Movie>(documents);
post_dump_1: |-
get_dump_status_1: |-
phrase_search_1: |-
Expand Down Expand Up @@ -304,7 +304,7 @@ geosearch_guide_sort_usage_2: |-
document_guide_create_index_primary_key: |-
TaskInfo task = await client.CreateIndexAsync("movies", "reference_number");
document_guide_add_document_primary_key: |-
await index.AddDocumentsAsync(
await index.AddDocumentsJsonAsync(
new[] {
new Movie {
ReferenceNumber: 287947,
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ namespace GettingStarted
};

// If the index 'movies' does not exist, Meilisearch creates it when you first add the documents.
var task = await index.AddDocumentsAsync<Movie>(documents); // # => { "uid": 0 }
var task = await index.AddDocumentsJsonAsync<Movie>(documents); // # => { "uid": 0 }
}
}
}
Expand Down Expand Up @@ -222,8 +222,8 @@ var index = await client.GetIndexAsync("movies");
#### Add or Update Documents <!-- omit in toc -->

```c#
var task = await index.AddDocumentsAsync(new Movie[] { new Movie { Id = "1", Title = "Carol" } } );
var task = await index.UpdateDocumentsAsync(new Movie[] { new Movie { Id = "1", Title = "Carol" } } );
var task = await index.AddDocumentsJsonAsync(new Movie[] { new Movie { Id = "1", Title = "Carol" } } );
var task = await index.UpdateDocumentsJsonAsync(new Movie[] { new Movie { Id = "1", Title = "Carol" } } );
```

The returned `task` is a `TaskInfo` that can access to `Uid` to get the status of the task.
Expand Down
32 changes: 0 additions & 32 deletions src/Meilisearch/Extensions/HttpExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,6 @@ namespace Meilisearch.Extensions
/// </summary>
public static class HttpExtensions
{
/// <summary>
/// Sends JSON payload using POST without "charset-utf-8" as Content-Type.
/// </summary>
/// <param name="client">HttpClient.</param>
/// <param name="uri">Endpoint.</param>
/// <param name="body">Body sent.</param>
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type of the body to send.</typeparam>
/// <returns>Returns the HTTP response from the Meilisearch server.</returns>
public static async Task<HttpResponseMessage> PostJsonCustomAsync<T>(this HttpClient client, string uri, T body, CancellationToken cancellationToken = default)
{
var payload = PrepareJsonPayload(body);

return await client.PostAsync(uri, payload, cancellationToken).ConfigureAwait(false);
}

/// <summary>
/// Sends JSON payload using POST without "charset-utf-8" as Content-Type and using JSON serializer options.
/// </summary>
Expand All @@ -45,22 +29,6 @@ public static async Task<HttpResponseMessage> PostJsonCustomAsync<T>(this HttpCl
return await client.PostAsync(uri, payload, cancellationToken).ConfigureAwait(false);
}

/// <summary>
/// Sends JSON payload using PUT without "charset-utf-8" as Content-Type.
/// </summary>
/// <param name="client">HttpClient.</param>
/// <param name="uri">Endpoint.</param>
/// <param name="body">Body sent.</param>
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type of the body to send.</typeparam>
/// <returns>Returns the HTTP response from the Meilisearch server.</returns>
public static async Task<HttpResponseMessage> PutJsonCustomAsync<T>(this HttpClient client, string uri, T body, CancellationToken cancellationToken = default)
{
var payload = PrepareJsonPayload(body);

return await client.PutAsync(uri, payload, cancellationToken).ConfigureAwait(false);
}

/// <summary>
/// Add the API Key to the Authorization header.
/// </summary>
Expand Down
51 changes: 51 additions & 0 deletions src/Meilisearch/HttpContents/JsonHttpContent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

namespace Meilisearch.HttpContents
{
/// <summary>
/// Send and receive HTTP content as JSON.
/// </summary>
internal class JsonHttpContent : HttpContent
{
private readonly JsonSerializerOptions jsonSerializerOptions;
private readonly object values;

/// <summary>
/// Initializes a new instance of the <see cref="JsonHttpContent"/> class.
/// </summary>
/// <param name="values">Values to be serialized.</param>
/// <param name="jsonSerializerOptions">Override default JsonSerializerOptions.</param>
/// <exception cref="ArgumentNullException">Thrown if values is null.</exception>
public JsonHttpContent(object values, JsonSerializerOptions jsonSerializerOptions = null)
{
if (values is null)
{
throw new ArgumentNullException(nameof(values));
}

this.values = values;

this.jsonSerializerOptions = jsonSerializerOptions ?? Constants.JsonSerializerOptionsWriteNulls;
this.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}

/// <inheritdoc/>
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
await JsonSerializer.SerializeAsync(stream, this.values, this.jsonSerializerOptions).ConfigureAwait(false);
}

/// <inheritdoc/>
protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}
}
23 changes: 11 additions & 12 deletions src/Meilisearch/Index.Documents.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;

using Meilisearch.Extensions;
using Meilisearch.HttpContents;

namespace Meilisearch
{
Expand All @@ -19,17 +19,17 @@ public partial class Index
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type of the document. Even though documents are schemaless in Meilisearch, making it typed helps in compile time.</typeparam>
/// <returns>Returns the task info.</returns>
public async Task<TaskInfo> AddDocumentsAsync<T>(IEnumerable<T> documents, string primaryKey = default, CancellationToken cancellationToken = default)
public async Task<TaskInfo> AddDocumentsJsonAsync<T>(IEnumerable<T> documents, string primaryKey = default, CancellationToken cancellationToken = default)
{
HttpResponseMessage responseMessage;
var uri = $"indexes/{Uid}/documents";

if (primaryKey != default)
{
uri = $"{uri}?{new { primaryKey = primaryKey }.ToQueryString()}";
}

responseMessage = await _http.PostJsonCustomAsync(uri, documents, cancellationToken: cancellationToken).ConfigureAwait(false);
var content = new JsonHttpContent(documents);
var responseMessage = await _http.PostAsync(uri, content, cancellationToken).ConfigureAwait(false);
return await responseMessage.Content.ReadFromJsonAsync<TaskInfo>(cancellationToken: cancellationToken).ConfigureAwait(false);
}

Expand All @@ -42,12 +42,12 @@ public async Task<TaskInfo> AddDocumentsAsync<T>(IEnumerable<T> documents, strin
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type of the document. Even though documents are schemaless in Meilisearch, making it typed helps in compile time.</typeparam>
/// <returns>Returns the task list.</returns>
public async Task<IEnumerable<TaskInfo>> AddDocumentsInBatchesAsync<T>(IEnumerable<T> documents, int batchSize = 1000, string primaryKey = default, CancellationToken cancellationToken = default)
public async Task<IEnumerable<TaskInfo>> AddDocumentsJsonInBatchesAsync<T>(IEnumerable<T> documents, int batchSize = 1000, string primaryKey = default, CancellationToken cancellationToken = default)
{
var tasks = new List<TaskInfo>();
foreach (var chunk in documents.GetChunks(batchSize))
{
tasks.Add(await AddDocumentsAsync(chunk, primaryKey, cancellationToken).ConfigureAwait(false));
tasks.Add(await AddDocumentsJsonAsync(chunk, primaryKey, cancellationToken).ConfigureAwait(false));
}

return tasks;
Expand All @@ -61,18 +61,17 @@ public async Task<IEnumerable<TaskInfo>> AddDocumentsInBatchesAsync<T>(IEnumerab
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type of document. Even though documents are schemaless in Meilisearch, making it typed helps in compile time.</typeparam>
/// <returns>Returns the task list.</returns>
public async Task<TaskInfo> UpdateDocumentsAsync<T>(IEnumerable<T> documents, string primaryKey = default, CancellationToken cancellationToken = default)
public async Task<TaskInfo> UpdateDocumentsJsonAsync<T>(IEnumerable<T> documents, string primaryKey = default, CancellationToken cancellationToken = default)
{
HttpResponseMessage responseMessage;
var uri = $"indexes/{Uid}/documents";

if (primaryKey != default)
{
uri = $"{uri}?{new { primaryKey = primaryKey }.ToQueryString()}";
}

responseMessage = await _http.PutJsonCustomAsync(uri, documents, cancellationToken).ConfigureAwait(false);

var content = new JsonHttpContent(documents);
var responseMessage = await _http.PutAsync(uri, content, cancellationToken).ConfigureAwait(false);
return await responseMessage.Content.ReadFromJsonAsync<TaskInfo>(cancellationToken: cancellationToken).ConfigureAwait(false);
}

Expand All @@ -85,12 +84,12 @@ public async Task<TaskInfo> UpdateDocumentsAsync<T>(IEnumerable<T> documents, st
/// <param name="cancellationToken">The cancellation token for this call.</param>
/// <typeparam name="T">Type of the document. Even though documents are schemaless in Meilisearch, making it typed helps in compile time.</typeparam>
/// <returns>Returns the task list.</returns>
public async Task<IEnumerable<TaskInfo>> UpdateDocumentsInBatchesAsync<T>(IEnumerable<T> documents, int batchSize = 1000, string primaryKey = default, CancellationToken cancellationToken = default)
public async Task<IEnumerable<TaskInfo>> UpdateDocumentsJsonInBatchesAsync<T>(IEnumerable<T> documents, int batchSize = 1000, string primaryKey = default, CancellationToken cancellationToken = default)
{
var tasks = new List<TaskInfo>();
foreach (var chunk in documents.GetChunks(batchSize))
{
tasks.Add(await UpdateDocumentsAsync(chunk, primaryKey, cancellationToken).ConfigureAwait(false));
tasks.Add(await UpdateDocumentsJsonAsync(chunk, primaryKey, cancellationToken).ConfigureAwait(false));
}

return tasks;
Expand Down
Loading