Skip to content

Commit

Permalink
Added smart network response & refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
SergeShkurko committed Mar 1, 2019
1 parent dca5d21 commit 2b0c64e
Show file tree
Hide file tree
Showing 17 changed files with 191 additions and 81 deletions.
11 changes: 11 additions & 0 deletions packages/extension/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
[comment]: <> (Changelog bum example)
[comment]: <> (## version)
[comment]: <> (### Breaking Changes or ### New Features)
[comment]: <> (* Change description)

## 0.0.2

### Breaking Changes

* `enumValueByString` now throws `EnumValueNotFoundException` if can't find the value

## 0.0.1

* Initial commit
18 changes: 18 additions & 0 deletions packages/extension/example/enum.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'package:extension/enum.dart';

enum AnyEnum {
one,
two,
three,
}

main() {
final AnyEnum findedvalue = enumValueByString(AnyEnum.values, 'two');
print(findedvalue == AnyEnum.two);

try {
enumValueByString(AnyEnum.values, 'bed value');
} on EnumValueNotFoundException {
print('Im successfuly handled');
}
}
7 changes: 5 additions & 2 deletions packages/extension/lib/enum.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/// Throws if enum value not found
class EnumValueNotFoundException implements Exception {}

/// Returns enum value by string
///
/// ```dart
Expand All @@ -9,7 +12,7 @@
/// enumValueByString(Enum.values, 'one') == Enum.one
/// ```
T enumValueByString<T>(List<T> values, String key) {
if (key == null) return null;
if (values == null || key == null) throw Exception('Invalide params');

for (T item in values) {
// Remove Enum name from enum item
Expand All @@ -20,5 +23,5 @@ T enumValueByString<T>(List<T> values, String key) {
}
}

return null;
throw EnumValueNotFoundException();
}
1 change: 1 addition & 0 deletions packages/extension/lib/extension.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export './enum.dart';
4 changes: 2 additions & 2 deletions packages/extension/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: extension
description: Language extension
version: 0.0.1
description: Plugin including Lot helpers for easy developing on dart language
version: 0.0.2
author: Serge Shkurko <sergeshkurko@outlook.com>
homepage: https://github.com/rbcprolabs/dart_plugins/tree/master/packages/extension

Expand Down
2 changes: 1 addition & 1 deletion packages/extension/test/all.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ import './enum.dart' as _enum;

main() {
_enum.main();
}
}
24 changes: 14 additions & 10 deletions packages/extension/test/enum.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,24 @@ main() {
group('Enum value by string', () {
test('Base', () {
final one = enumValueByString(_TestNormal.values, 'one');
expect(one, allOf([
equals(_TestNormal.one),
isNot(equals(_TestNormal.two)),
isNot(equals(_TestNormal.one1)),
]));
expect(
one,
allOf([
equals(_TestNormal.one),
isNot(equals(_TestNormal.two)),
isNot(equals(_TestNormal.one1)),
]));
});

test('Case intensive', () {
final caseIntensive = enumValueByString(_TestNormal.values, 'OnE');
expect(caseIntensive, allOf([
equals(_TestNormal.one),
isNot(equals(_TestNormal.two)),
isNot(equals(_TestNormal.one1)),
]));
expect(
caseIntensive,
allOf([
equals(_TestNormal.one),
isNot(equals(_TestNormal.two)),
isNot(equals(_TestNormal.one1)),
]));
});

test('Not exist', () {
Expand Down
5 changes: 5 additions & 0 deletions packages/network/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
[comment]: <> (Changelog bum example)
[comment]: <> (## version)
[comment]: <> (### Breaking Changes or ### New Features)
[comment]: <> (* Change description)

## 0.0.1

* Initial release
25 changes: 25 additions & 0 deletions packages/network/example/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import 'package:network/network.dart' as network;

main() async {
final getResponse = await network.get<network.JsonApiResponse>(
'https://jsonplaceholder.typicode.com/todos/1');
print(getResponse.toMap['title']);

// Post request to api
final postResponse = await network.post<network.JsonApiResponse>(
'https://jsonplaceholder.typicode.com/todos',
body: {'title': 'test'});
print(postResponse.toMap['id']);

// Or post binary
// await network.post<network.JsonApiResponse>(
// 'https://jsonplaceholder.typicode.com/todos', body: [0,0,0,0,0],
// jsonBody: false);

/// Handle exceptions
try {
await network.get('https://jsonplaceholder.typicode.com/todos/202');
} on network.NetworkException catch (error) {
print('Network exception called, status code: ${error.code}');
}
}
67 changes: 4 additions & 63 deletions packages/network/lib/network.dart
Original file line number Diff line number Diff line change
@@ -1,63 +1,4 @@
import 'dart:async' show Future;
import 'dart:convert' show Encoding, jsonDecode, jsonEncode, utf8;
import 'dart:typed_data' show Uint8List;
import 'package:http/http.dart' as http show get, post, Response;

class NetworkException<T> implements Exception {
final APIResponse<T> response;
NetworkException(this.response);
}

class APIResponse<T> {
final int statusCode;
final Uint8List bytes;

APIResponse(this.statusCode, this.bytes);

/// Convert json body to map
T get toMap {
final String json = utf8.decode(bytes);

if (json == null) throw Exception('JSON decoding error');

return jsonDecode(json);
}
}

Future<APIResponse<T>> get<T extends dynamic>(String url,
{Map<String, String> headers}) async {
final http.Response response = await http.get(url, headers: headers);

final int statusCode = response.statusCode;

final apiResponse = APIResponse<T>(statusCode, response.bodyBytes);

if (statusCode < 200 || statusCode >= 400)
throw NetworkException<T>(apiResponse);

return apiResponse;
}

Future<APIResponse<T>> post<T extends dynamic>(
String url, {
Map<String, String> headers,
body = '',
Encoding encoding,
bool jsonBody = true,
}) async {
final http.Response response = await http.post(
url,
body: jsonBody ? jsonEncode(body) : body,
headers: headers,
encoding: encoding,
);

final int statusCode = response.statusCode;

final apiResponse = APIResponse<T>(statusCode, response.bodyBytes);

if (statusCode < 200 || statusCode >= 400)
throw NetworkException<T>(apiResponse);

return apiResponse;
}
export 'src/exception.dart';
export 'src/response.dart';
export 'src/get.dart';
export 'src/post.dart';
Empty file removed packages/network/lib/response.dart
Empty file.
8 changes: 8 additions & 0 deletions packages/network/lib/src/exception.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import 'package:network/src/response.dart';

class NetworkException<T extends BinaryResponse> implements Exception {
final T response;
NetworkException(this.response);

int get code => response.statusCode;
}
22 changes: 22 additions & 0 deletions packages/network/lib/src/get.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import 'dart:async' show Future;
import 'package:http/http.dart' as http show get, Response;
import 'package:network/src/exception.dart';
import 'package:network/src/response.dart';
import 'package:network/src/utils.dart';

Future<T> get<T extends BinaryResponse>(String url,
{Map<String, String> headers}) async {
final http.Response httpResponse = await http.get(url, headers: headers);

final int statusCode = httpResponse.statusCode;

final response = makeResponseByType<T>(statusCode, httpResponse.bodyBytes);

print(response.runtimeType);

if (statusCode < 200 || statusCode >= 400) {
throw NetworkException<T>(response);
}

return response;
}
32 changes: 32 additions & 0 deletions packages/network/lib/src/post.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import 'dart:async';
import 'dart:convert' show Encoding, jsonEncode;

import 'package:http/http.dart' as http show post, Response;
import 'package:network/src/exception.dart';
import 'package:network/src/response.dart';
import 'package:network/src/utils.dart';

Future<T> post<T extends BinaryResponse>(
String url, {
Map<String, String> headers,
body = '',
Encoding encoding,
bool jsonBody = true,
}) async {
final http.Response httpResponse = await http.post(
url,
body: jsonBody ? jsonEncode(body) : body,
headers: headers,
encoding: encoding,
);

final int statusCode = httpResponse.statusCode;

final response = makeResponseByType<T>(statusCode, httpResponse.bodyBytes);

if (statusCode < 200 || statusCode >= 400) {
throw NetworkException<T>(response);
}

return response;
}
27 changes: 27 additions & 0 deletions packages/network/lib/src/response.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import 'dart:convert' show jsonDecode, utf8;
import 'dart:typed_data' show Uint8List;

class BinaryResponse {
/// Response status code
final int statusCode;

/// Response body bytes
final Uint8List bytes;

BinaryResponse(this.statusCode, this.bytes);

BinaryResponse.make(this.statusCode, this.bytes);
}

class JsonApiResponse extends BinaryResponse {
JsonApiResponse(int statusCode, Uint8List bytes) : super(statusCode, bytes);

/// Convert json body to map
Map<String, dynamic> get toMap {
final String json = utf8.decode(bytes);

if (json == null) throw Exception('JSON decoding error');

return jsonDecode(json);
}
}
13 changes: 13 additions & 0 deletions packages/network/lib/src/utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import 'dart:typed_data' show Uint8List;

import 'package:network/network.dart';

T makeResponseByType<T>(int statusCode, Uint8List bytes) {
switch (T) {
case JsonApiResponse:
return JsonApiResponse(statusCode, bytes) as T;
case BinaryResponse:
default:
return BinaryResponse(statusCode, bytes) as T;
}
}
6 changes: 3 additions & 3 deletions packages/network/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
name: network
description: http hooks for easy works
description: Plugin including hooks for easy works with http package in dart
version: 0.0.1
author: Serge Shkurko <sergeshkurko@outlook.com>
homepage: https://github.com/rbcprolabs/dart_plugins/tree/master/packages/network

environment:
sdk: ">=2.1.0 <3.0.0"
sdk: ">=2.0.0 <3.0.0"

dependencies:
http: 0.12.0+1
http: ^0.12.0+1

dev_dependencies:
test: ^1.5.3

0 comments on commit 2b0c64e

Please sign in to comment.