Skip to content

Commit

Permalink
http request example
Browse files Browse the repository at this point in the history
  • Loading branch information
SandroMaglione committed Mar 18, 2024
1 parent bea6930 commit bda3934
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 0 deletions.
30 changes: 30 additions & 0 deletions examples/fpdart_http/lib/api.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import 'package:fpdart/fpdart.dart';
import 'package:http/http.dart' as http;

import 'http_error.dart';

/// 1️⃣ Define dependencies, errors, response
Effect<http.Client, HttpError, http.Response> get(
Uri url, {
Map<String, String>? headers,
}) =>

/// 2️⃣ Use the Do notation with the `gen` constructor
Effect.gen((_) async {
/// 3️⃣ Extract the dependency using `env` (environment)
final client = await _(Effect.env());

/// 4️⃣ Perform a request, catch errors, extract the response
final response = await _(Effect.tryCatch(
execute: () => client.get(url, headers: headers),
onError: (_, __) => const RequestError(),
));

/// 5️⃣ Use plain dart code to check for valid status
if (response.statusCode != 200) {
return await _(Effect.fail(const ResponseError()));
}

/// 6️⃣ Return extracted/valid response
return response;
});
11 changes: 11 additions & 0 deletions examples/fpdart_http/lib/http_error.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
sealed class HttpError {
const HttpError();
}

final class RequestError extends HttpError {
const RequestError();
}

final class ResponseError extends HttpError {
const ResponseError();
}
18 changes: 18 additions & 0 deletions examples/fpdart_http/lib/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'package:fpdart/fpdart.dart';
import 'package:http/http.dart' as http;

import 'api.dart';

void main() async {
final main = await get(
Uri.https("pokeapi.co", "/api/v2/pokemon/10"),
)
.tap(
(response) => Effect.function(
() => print(response.body),
),
)
.runFuture(
http.Client(),
);
}
19 changes: 19 additions & 0 deletions examples/fpdart_http/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: fpdart_http
description: >
Example of using fpdart with http.
version: 2.0.0
homepage: https://www.sandromaglione.com/
repository: https://github.com/SandroMaglione/fpdart
publish_to: "none"

environment:
sdk: ">=3.3.0 <4.0.0"

dependencies:
http: ^1.2.1
fpdart:
path: ../../packages/fpdart

dev_dependencies:
lints: ^2.0.1
test: ^1.23.1

0 comments on commit bda3934

Please sign in to comment.