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

feat(dart): add algolia_chopper_requester package #3291

Open
wants to merge 46 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 39 commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
d19989b
feat(dart): export AlgoliaAgent from algolia_client_core package
techouse Jul 1, 2024
1a8bcf3
feat(dart): add algolia_chopper_requester package
techouse Jul 1, 2024
47ef5f6
feat(dart): add algolia_chopper_requester package
techouse Jul 1, 2024
f7ad718
feat(dart): remove chopper_requester/CHANGELOG.md
techouse Jul 1, 2024
f47674e
feat(dart): update chopper_requester/README.md
techouse Jul 1, 2024
0e3c6ec
feat(dart): remove chopper_requester/analysis_options.yaml
techouse Jul 1, 2024
28cd141
feat(dart): remove chopper_requester/LICENSE
techouse Jul 1, 2024
aab0906
feat(dart): sync chopper_requester/lib/src/version.dart
techouse Jul 1, 2024
d812167
feat(dart): add license generation
techouse Jul 1, 2024
c5fd54c
feat(dart): add option to pass custom JsonConverter to ChopperRequest…
techouse Jul 1, 2024
40cf261
feat(dart): fix docs
techouse Jul 1, 2024
5a6598d
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 1, 2024
82f7bca
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 2, 2024
84a7bb5
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 3, 2024
baa53ff
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 5, 2024
6d35059
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 8, 2024
33d1431
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 8, 2024
5ba830c
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 8, 2024
1e0e7da
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 8, 2024
812b937
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 8, 2024
f0a6e4f
feat(dart): fix URL construction
techouse Jul 9, 2024
57dcfa0
feat(dart): explicitly set empty Uri as baseUri
techouse Jul 9, 2024
37585fc
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 10, 2024
8b2a51d
feat(dart): bump algolia_client_core
techouse Jul 10, 2024
a9083e9
Merge remote-tracking branch 'origin/feat/add-chopper-requester-packa…
techouse Jul 10, 2024
00ba8c4
feat(dart): downgrade test
techouse Jul 10, 2024
59329cd
feat(dart): bump version
techouse Jul 10, 2024
cdbaf2e
feat(dart): fix requestUri
techouse Jul 10, 2024
2148ec0
feat(dart): add example
techouse Jul 10, 2024
9d25176
feat(dart): update example
techouse Jul 10, 2024
5e627e2
feat(dart): update example
techouse Jul 10, 2024
581cee8
feat(dart): update example
techouse Jul 10, 2024
14fc833
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 11, 2024
7c53cd3
Merge branch 'main' into feat/add-chopper-requester-package
shortcuts Jul 16, 2024
95f4e19
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 19, 2024
b2cc8f6
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 28, 2024
23a57ae
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 30, 2024
039a207
Merge branch 'main' into feat/add-chopper-requester-package
techouse Jul 30, 2024
7bd6833
Merge branch 'main' into feat/add-chopper-requester-package
techouse Aug 5, 2024
17e3cd9
Merge branch 'main' into feat/add-chopper-requester-package
techouse Aug 24, 2024
1d55178
Merge branch 'main' into feat/add-chopper-requester-package
techouse Aug 27, 2024
f853813
Merge remote-tracking branch 'origin/main' into feat/add-chopper-requ…
techouse Sep 9, 2024
1cb13bf
Merge branch 'main' into feat/add-chopper-requester-package
techouse Sep 9, 2024
ebc76f9
feat(dart): implement setClientApiKey
techouse Sep 9, 2024
fbe6121
Merge branch 'main' into feat/add-chopper-requester-package
techouse Oct 24, 2024
a97061a
Merge branch 'main' into feat/add-chopper-requester-package
techouse Nov 5, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/
techouse marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<!-- centered logo -->
<p align="center">
<a href="https://www.algolia.com">
<img alt="Algolia for Dart" src="https://raw.githubusercontent.com/algolia/algoliasearch-client-common/master/banners/dart.png" >
</a>
</p>

<!-- centered badges -->
<p align="center">
<a href="https://pub.dartlang.org/packages/algolia_chopper_client"><img src="https://img.shields.io/pub/v/algolia_chopper_client.svg" alt="Latest version"></a>
<a href="https://pub.dev/packages/algolia_chopper_client/publisher"><img src="https://img.shields.io/pub/publisher/algolia_chopper_client.svg" alt="Publisher"></a>
</p>

<h3 align="center">
<strong>Algolia API Chopper Requester</strong>
</h3>

<p align="center">
Use the Chopper Requester to send requests to the Algolia API with the Algolia Search Client for Dart. This package provides a custom Requester for the Algolia Search Client, allowing users to send requests to the Algolia API using the Chopper HTTP client.
</p>

## 💡 Installation

Add Chopper Requester as a dependency in your project directly from pub.dev:

#### For Dart projects:

```shell
dart pub add algolia_chopper_requester
```

#### For Flutter projects:

```shell
flutter pub add algolia_chopper_requester
```

### Basic Usage

```dart
final String appId = 'latency';
final String apiKey = '6be0576ff61c053d5f9a3225e2a90f76';

final SearchClient _client = SearchClient(
appId: appId,
apiKey: apiKey,
options: ClientOptions(
requester: ChopperRequester(
appId: appId,
apiKey: apiKey,
)
),
);

Future<SearchResponse> search(String query) => _client.searchIndex(
request: SearchForHits(
indexName: 'flutter',
query: query,
hitsPerPage: 5,
),
);
```

You can configure the `ChopperRequester` with the following parameters:

### Configuration

```dart
final requester = ChopperRequester({
/// Your Algolia Application ID
required String appId,
/// Your Algolia Search-Only API Key
required String apiKey,
/// Additional headers to send with the request
Map<String, dynamic>? headers,
/// The segments to include in the `User-Agent` header
Iterable<AgentSegment>? clientSegments,
/// The logger to use for debugging
Logger? logger,
/// The Chopper Interceptors to use for modifying the request
Iterable<Interceptor>? interceptors,
/// The HTTP client to use for sending requests
Client? client,
/// A custom JSON converter to use for serializing and deserializing JSON
JsonConverter? converter,
});
```

### Advanced Usage

To set the connect timeout one has to do that directly on the `Client`, i.e.

```dart
final requester = ChopperRequester(
appId: appId,
apiKey: apiKey,
client: http.IOClient(
HttpClient()..connectionTimeout = const Duration(seconds: 60),
),
);
```

#### Custom Interceptors

For interceptors please see the [Chopper documentation](https://hadrien-lejard.gitbook.io/chopper/interceptors).

#### Custom Clients

Via the `client` option users can use platform specific HTTP clients such:
- [cronet_http](https://pub.dev/packages/cronet_http) on Android
```dart
final requester = ChopperRequester(
appId: appId,
apiKey: apiKey,
client: CronetClient.fromCronetEngine(
CronetEngine.build(
cacheMode: CacheMode.memory,
cacheMaxSize: 50 * 1024 * 1024,
),
closeEngine: true,
),
);
```
- [cupertino_http](https://pub.dev/packages/cupertino_http) on iOS/macOS
```dart
final requester = ChopperRequester(
appId: appId,
apiKey: apiKey,
client: CupertinoClient.fromSessionConfiguration(
(URLSessionConfiguration.defaultSessionConfiguration()
..timeoutIntervalForRequest = const Duration(seconds: 30)),
),
);
```

#### Parsing JSON in the background using Isolates

Parsing JSON in the background is a good idea if you don't want to block the main thread.
Please see the [Chopper documentation](https://hadrien-lejard.gitbook.io/chopper/faq#decoding-json-using-isolates) on Decoding JSON using Isolate worker pools.

## License

Chopper Requester for Algolia Search Client is an open-sourced software licensed under the [MIT license](LICENSE).
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'dart:io' show HttpClient;

import 'package:algolia_chopper_requester/algolia_chopper_requester.dart';
import 'package:algolia_client_core/algolia_client_core.dart';
import 'package:http/http.dart' as http show Client;
import 'package:http/io_client.dart' show IOClient;

void main() async {
const String appId = 'latency';
const String apiKey = '6be0576ff61c053d5f9a3225e2a90f76';

// Create a custom http [Client] with a connection timeout of 30 seconds
final http.Client client = IOClient(
HttpClient()..connectionTimeout = const Duration(seconds: 30),
);

// Creating an instance of the RetryStrategy with necessary parameters.
// This will retry the failed requests with a backoff strategy.
final RetryStrategy requester = RetryStrategy.create(
segment: AgentSegment(value: 'CustomClient'),
appId: appId,
apiKey: apiKey,
defaultHosts: () => [
Host(url: 'latency-dsn.algolia.net'),
Host(url: 'latency-1.algolianet.com'),
],
options: ClientOptions(
requester: ChopperRequester(
appId: appId,
apiKey: apiKey,
// Optionally, pass a custom http [Client] to the ChopperRequester.
// NOTE: The [Client] must be manually disposed of after use.
client: client,
),
),
);

// Executing a GET request on the '/1/indexes/instant_search' endpoint.
final Map<String, dynamic> response = await requester.execute(
request: ApiRequest(
method: RequestMethod.get,
path: '/1/indexes/instant_search',
queryParams: {'query': 'a', 'hitsPerPage': '5'},
),
);

// Printing json response.
print(response);

// Dispose of the requester to clean up its resources.
requester.dispose();

// Disposing a custom [Client] has to be done manually.
client.close();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
library algolia_chopper_requester;

export 'package:chopper/chopper.dart' show Interceptor;
export 'src/chopper_requester.dart';
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'dart:async' show FutureOr;

import 'package:algolia_client_core/algolia_client_core.dart' show AlgoliaAgent;
import 'package:chopper/chopper.dart';
import 'package:algolia_chopper_requester/src/platform/platform.dart';

/// Interceptor that attaches the Algolia agent to outgoing requests.
///
/// This interceptor modifies the query parameters of each request to include the
/// formatted representation of the Algolia agent.
class AgentInterceptor implements Interceptor {
/// The Algolia agent to be attached to outgoing requests.
final AlgoliaAgent agent;

/// Constructs an [AgentInterceptor] with the provided Algolia agent.
const AgentInterceptor({required this.agent});

@override
FutureOr<Response<BodyType>> intercept<BodyType>(Chain<BodyType> chain) =>
chain.proceed(Platform.algoliaAgent<BodyType>(chain, agent.formatted()));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'dart:async' show FutureOr;

import 'package:chopper/chopper.dart';

/// Interceptor that attaches the application id and API key to outgoing requests.
///
/// This interceptor modifies the headers of each request to include the
/// application id and API key for Algolia authentication.
class AuthInterceptor implements Interceptor {
/// The application id used for Algolia authentication.
final String appId;

/// The API key used for Algolia authentication.
final String apiKey;

/// Constructs an [AuthInterceptor] with the provided application id and API key.
const AuthInterceptor({
required this.appId,
required this.apiKey,
});

@override
FutureOr<Response<BodyType>> intercept<BodyType>(Chain<BodyType> chain) =>
chain.proceed(
applyHeaders(
chain.request,
{
'x-algolia-application-id': appId,
'x-algolia-api-key': apiKey,
},
),
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import 'dart:async' show TimeoutException;

import 'package:algolia_client_core/algolia_client_core.dart';
import 'package:chopper/chopper.dart';
import 'package:algolia_chopper_requester/src/agent_interceptor.dart';
import 'package:algolia_chopper_requester/src/auth_interceptor.dart';
import 'package:algolia_chopper_requester/src/platform/platform.dart';
import 'package:algolia_chopper_requester/src/version.dart';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart' show Logger;

/// A [Requester] implementation using the Chopper library.
///
/// This class sends HTTP requests using the Chopper library and handles
/// response conversion and error handling.
class ChopperRequester implements Requester {
/// The underlying Chopper client.
final ChopperClient _client;

/// Constructs a [ChopperClient] with the given [appId] and [apiKey].
ChopperRequester({
required String appId,
required String apiKey,
Map<String, dynamic>? headers,
Iterable<AgentSegment>? clientSegments,
Logger? logger,
Iterable<Interceptor>? interceptors,
http.Client? client,
JsonConverter? converter,
}) : _client = ChopperClient(
client: client,
converter: converter ?? JsonConverter(),
interceptors: [
AuthInterceptor(
appId: appId,
apiKey: apiKey,
),
AgentInterceptor(
agent: AlgoliaAgent(packageVersion)
..addAll([
...?clientSegments,
...Platform.agentSegments(),
]),
),
if (logger != null)
HttpLoggingInterceptor(
level: Level.body,
onlyErrors: false,
logger: logger,
),
...?interceptors,
],
);

@override
Future<HttpResponse> perform(HttpRequest request) async {
try {
final Response<Map<String, dynamic>> response = await execute(request);

if (response.isSuccessful) {
return HttpResponse(
response.statusCode,
response.body,
);
} else {
throw AlgoliaApiException(
response.statusCode,
response.error ?? response.body,
);
}
} on TimeoutException catch (e) {
throw AlgoliaTimeoutException(e);
} on http.ClientException catch (e) {
throw AlgoliaIOException(e);
}
}

/// Executes the [request] and returns the response as an [HttpResponse].
Future<Response<Map<String, dynamic>>> execute(HttpRequest request) async {
final Request chopperRequest = Request(
request.method,
requestUri(request),
Uri(),
body: request.body,
headers: {
for (final MapEntry<String, dynamic> entry
in request.headers?.entries ?? const {})
entry.key: entry.value.toString(),
if (request.body != null) 'content-type': 'application/json',
},
);

return switch (options.timeout) {
null => await _client
.send<Map<String, dynamic>, Map<String, dynamic>>(chopperRequest),
_ => await _client
.send<Map<String, dynamic>, Map<String, dynamic>>(chopperRequest)
.timeout(options.timeout!),
};
}

/// Constructs the request URI from the [request] details.
Uri requestUri(HttpRequest request) => Uri(
scheme: request.host.scheme,
host: request.host.url,
port: request.host.port,
path: request.path,
query: request.queryParameters.isNotEmpty
? request.queryParameters.entries
.map((e) => "${e.key}=${e.value}")
.join("&")
: null,
);

@override
void close() => _client.dispose();
}
Loading
Loading