Skip to content

Commit

Permalink
feat: "Implemented Call Adapter (#729)" (#730) (#731)
Browse files Browse the repository at this point in the history
* feat: "Implemented Call Adapter (#729)" (#730)

This reverts commit e8bdb48.

* fix: version issue

* fix: fix test

* fix: remove deps overrides
  • Loading branch information
trevorwang authored Dec 30, 2024
1 parent dccfb6c commit 241695b
Show file tree
Hide file tree
Showing 10 changed files with 496 additions and 82 deletions.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,40 @@ dio.options.baseUrl = 'https://5d42a6e2bc64f90014a56ca0.mockapi.io/api/v1';
final client = RestClient(dio);
```

### Call Adapter

This feature allows you to adapt the return type of a network call from one type to another.

For example:
Future<User> → Future<Result<User>>

This feature provides flexibility in handling API responses, enabling better integration with custom response wrappers or error handling libraries.

The CallAdapter takes the original return type R and transforms it into a new type T. This is particularly useful when working with response wrappers like Either, Result, or ApiResponse.

Below is an example using a custom CallAdapter with a Result wrapper:
```dart
class MyCallAdapter<T> extends CallAdapter<Future<T>, Future<Result<T>>> {
@override
Future<Result<T>> adapt(Future<T> Function() call) async {
try {
final response = await call();
return Result<T>.ok(response);
} catch (e) {
return Result.err(e.toString());
}
}
}
@RestApi(callAdapter: MyCallAdapter)
abstract class RestClient {
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
@GET('/')
Future<Result<User>> getUser();
}
```

### Multiple endpoints support

If you want to use multiple endpoints to your `RestClient`, you should pass your base url when you initiate `RestClient`. Any value defined in `RestApi` will be ignored.
Expand Down
32 changes: 32 additions & 0 deletions generator/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,35 @@

## 9.1.7

- Introduced CallAdapters, This feature allows adaptation of a Call with return type R into the type of T.
e.g. Future<User> to Future<Result<User>>

Code Example:

```dart
class MyCallAdapter<T> extends CallAdapter<Future<T>, Future<Either<ApiError, T>>> {
@override
Future<Either<ApiError, T>> adapt(Future<T> Function() call) async {
try {
final response = await call();
return Either.right(response);
}
catch (e) {
return Either.left(ApiError(e))
}
}
}
@RestApi()
abstract class RestClient {
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
@UseCallAdapter(MyCallAdapter)
@GET('/')
Future<User> getTasks();
}
```

## 9.1.6

- Update `analyzer`, `dart_style` and `source_gen` dependencies to allow upper versions
Expand Down
Loading

0 comments on commit 241695b

Please sign in to comment.