Skip to content

Instantly share code, notes, and snippets.

@mariopepe
Created January 23, 2022 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariopepe/d29ff1e17d6af5722efef45a7b459945 to your computer and use it in GitHub Desktop.
Save mariopepe/d29ff1e17d6af5722efef45a7b459945 to your computer and use it in GitHub Desktop.
json_placeholder_v1.dart
import 'dart:convert';
import 'package:functional_error_handling/core/error_handling/error_handling.dart';
import 'package:functional_error_handling/features/post/data/models/post_model.dart';
import 'package:http/http.dart' as http;
class JsonPlaceholderV1 {
JsonPlaceholderV1({
required this.httpClient,
});
final http.Client httpClient;
Future<List<PostModel>> fetchPosts() async {
try {
final response = await httpClient.get(
Uri.https('jsonplaceholder.typicode.com', '/posts'),
);
if (response.statusCode == 200) {
try {
final List<PostModel> posts = [];
final data = json.decode(utf8.decode(response.bodyBytes)) as List;
for (int i = 0; i < data.length; i++) {
posts.add(PostModel.fromJson(data[i]));
}
return posts;
} on Exception {
throw DataParsingException();
}
} else {
throw ServerException();
}
} catch (e) {
if ((e is ServerException) || (e is DataParsingException)) {
rethrow;
} else {
throw NoConnectionException();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment