Skip to content

Commit

Permalink
format dart code and remove unnecessary new keyword
Browse files Browse the repository at this point in the history
  • Loading branch information
tanutapi committed Nov 20, 2019
1 parent 33030f9 commit da7924e
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 42 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
## 1.0.5
## 1.0.5 - 1.0.6

- Pin rxdart version to 0.22.6

Expand Down
21 changes: 14 additions & 7 deletions lib/src/ddp_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ class DdpClient {

void reconnect() {
print('reconnect... ${_connectionStatus}');
if (_connectionStatus.status != DdpConnectionStatusValues.connected && _connectionStatus.status != DdpConnectionStatusValues.connecting) {
if (_connectionStatus.status != DdpConnectionStatusValues.connected &&
_connectionStatus.status != DdpConnectionStatusValues.connecting) {
if (_scheduleReconnectTimer != null) {
if (_scheduleReconnectTimer.isActive) {
_scheduleReconnectTimer.cancel();
Expand Down Expand Up @@ -203,13 +204,15 @@ class DdpClient {
}

void _connect() async {
if (_connectionStatus.status != DdpConnectionStatusValues.connected && _connectionStatus.status != DdpConnectionStatusValues.connecting) {
if (_connectionStatus.status != DdpConnectionStatusValues.connected &&
_connectionStatus.status != DdpConnectionStatusValues.connecting) {
_isTryToReconnect = true;
_connectionStatus.status = DdpConnectionStatusValues.connecting;
_connectionStatus.reason = null;
_statusStreamController.sink.add(_connectionStatus);
try {
WebSocket socket = await WebSocket.connect(_url).timeout(Duration(seconds: 5));
WebSocket socket =
await WebSocket.connect(_url).timeout(Duration(seconds: 5));
_connectionStatus.retryCount = 0;
_connectionStatus.retryTime = Duration(seconds: 1);
_socket = socket;
Expand All @@ -221,14 +224,17 @@ class DdpClient {
_connectionStatus.reason = err.toString();
_statusStreamController.sink.add(_connectionStatus);
_socket = null;
printDebug('ScheduleReconnect due to websocket exception while trying to connect');
printDebug(
'ScheduleReconnect due to websocket exception while trying to connect');
_scheduleReconnect();
};
}
;
}
}

void _scheduleReconnect() {
if (_connectionStatus.status == DdpConnectionStatusValues.offline || _connectionStatus.status == DdpConnectionStatusValues.failed) {
if (_connectionStatus.status == DdpConnectionStatusValues.offline ||
_connectionStatus.status == DdpConnectionStatusValues.failed) {
_connectionStatus.retryCount++;
if (_connectionStatus.retryCount <= _maxRetryCount) {
_connectionStatus.connected = false;
Expand Down Expand Up @@ -287,7 +293,8 @@ class DdpClient {
printDebug('Disconnect due to not receive PONG');
printDebug('PING was sent since $sentTime');
printDebug('Current time is ${DateTime.now()}');
printDebug('Diff since PING sent is ${DateTime.now().difference(sentTime)}');
printDebug(
'Diff since PING sent is ${DateTime.now().difference(sentTime)}');
disconnect();
}
});
Expand Down
80 changes: 47 additions & 33 deletions lib/src/meteor_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,15 @@ class MeteorError extends Error {
MeteorError.parse(Map<String, dynamic> object) {
try {
details = object['details']?.toString();
error = object['error'] is String ? int.parse(object['error']) : object['error'];
error = object['error'] is String
? int.parse(object['error'])
: object['error'];
errorType = object['errorType']?.toString();
isClientSafe = object['isClientSafe'] == true;
message = object['message']?.toString();
reason = object['reason']?.toString();
stack = object['stack']?.toString();
} catch (_) {
}
} catch (_) {}
}

@override
Expand All @@ -52,10 +53,10 @@ class MeteorClient {

BehaviorSubject<DdpConnectionStatus> _statusSubject = BehaviorSubject();
Observable<DdpConnectionStatus> _statusStream;

BehaviorSubject<bool> _loggingInSubject = BehaviorSubject();
Observable<bool> _loggingInStream;

BehaviorSubject<String> _userIdSubject = BehaviorSubject();
Observable<String> _userIdStream;

Expand All @@ -75,20 +76,22 @@ class MeteorClient {
Map<String, Observable<Map<String, dynamic>>> collections = {};

MeteorClient.connect({String url}) {
url = url.replaceFirst(new RegExp(r'^http'), 'ws');
url = url.replaceFirst(RegExp(r'^http'), 'ws');
if (!url.endsWith('websocket')) {
url = url.replaceFirst(new RegExp(r'/$'), '') + '/websocket';
url = url.replaceFirst(RegExp(r'/$'), '') + '/websocket';
}
print('connecting to $url');
connection = DdpClient(url: url);

connection.status().listen((ddpStatus) {
_statusSubject.add(ddpStatus);
})..onError((dynamic error) {
_statusSubject.addError(error);
})..onDone(() {
_statusSubject.close();
});
})
..onError((dynamic error) {
_statusSubject.addError(error);
})
..onDone(() {
_statusSubject.close();
});
_statusStream = _statusSubject.stream;

_loggingInStream = _loggingInSubject.stream;
Expand All @@ -104,11 +107,13 @@ class MeteorClient {
if (fields != null) {
fields['_id'] = id;
}

if (_collections[collectionName] == null) {
_collections[collectionName] = {};
_collectionsSubject[collectionName] = BehaviorSubject<Map<String, dynamic>>();
collections[collectionName] = _collectionsSubject[collectionName].stream;
_collectionsSubject[collectionName] =
BehaviorSubject<Map<String, dynamic>>();
collections[collectionName] =
_collectionsSubject[collectionName].stream;
}

if (data['msg'] == 'removed') {
Expand All @@ -120,13 +125,15 @@ class MeteorClient {
} else if (data['msg'] == 'changed') {
if (fields != null) {
fields.forEach((k, v) {
if (_collections[collectionName][id] != null && _collections[collectionName][id] is Map) {
if (_collections[collectionName][id] != null &&
_collections[collectionName][id] is Map) {
_collections[collectionName][id][k] = v;
}
});
} else if (data['cleared'] != null && data['cleared'] is List) {
List<dynamic> clearList = data['cleared'];
if (_collections[collectionName][id] != null && _collections[collectionName][id] is Map) {
if (_collections[collectionName][id] != null &&
_collections[collectionName][id] is Map) {
clearList.forEach((k) {
_collections[collectionName][id].remove(k);
});
Expand Down Expand Up @@ -229,16 +236,17 @@ class MeteorClient {
// Publish and subscribe

/// Subscribe to a record set. Returns a SubscriptionHandler that provides stop() and ready() methods.
///
///
/// `name`
/// Name of the subscription. Matches the name of the server's publish() call.
///
///
/// `params`
/// Arguments passed to publisher function on server.
SubscriptionHandler subscribe(String name, List<dynamic> params,
{Function onStop(dynamic error), Function onReady}) {
// TODO: not subscribe with same name and params.
SubscriptionHandler handler = connection.subscribe(name, params, onStop: onStop, onReady: onReady);
SubscriptionHandler handler =
connection.subscribe(name, params, onStop: onStop, onReady: onReady);
if (_subscriptions[name] != null) {
_subscriptions[name].stop();
}
Expand All @@ -250,27 +258,27 @@ class MeteorClient {
// Methods

/// Invoke a method passing an array of arguments.
///
///
/// `name` Name of method to invoke
///
///
/// `args` List of method arguments
Future<dynamic> call(String name, List<dynamic> args) async {
try {
return await connection.call(name, args);
} catch(e) {
} catch (e) {
throw MeteorError.parse(e);
}
}

/// Invoke a method passing an array of arguments.
///
///
/// `name` Name of method to invoke
///
///
/// `args` List of method arguments
Future<dynamic> apply(String name, List<dynamic> args) async {
try {
return await connection.apply(name, args);
} catch(e) {
} catch (e) {
throw MeteorError.parse(e);
}
}
Expand Down Expand Up @@ -375,11 +383,13 @@ class MeteorClient {
/// Either a string interpreted as a username or an email; or an object with a single key: email, username or id. Username or email match in a case insensitive manner.
///
/// [password] password
///
///
/// [delayOnLoginErrorSecond]
/// If login errors, delay for specificed second before throw an error.
/// The user's password.
Future<MeteorClientLoginResult> loginWithPassword(String user, String password, { int delayOnLoginErrorSecond = 0 }) {
Future<MeteorClientLoginResult> loginWithPassword(
String user, String password,
{int delayOnLoginErrorSecond = 0}) {
Completer<MeteorClientLoginResult> completer = Completer();
_loggingIn = true;
_loggingInSubject.add(_loggingIn);
Expand Down Expand Up @@ -418,7 +428,8 @@ class MeteorClient {
return completer.future;
}

Future<MeteorClientLoginResult> loginWithToken({String token, DateTime tokenExpires}) {
Future<MeteorClientLoginResult> loginWithToken(
{String token, DateTime tokenExpires}) {
_token = token;
if (tokenExpires == null) {
_tokenExpires = DateTime.now().add(Duration(hours: 1));
Expand All @@ -435,19 +446,22 @@ class MeteorClient {
if (_tokenExpires != null) {
print('Token expires ${_tokenExpires.toString()}');
print('now is ${DateTime.now()}');
print('Token expires is after now ${_tokenExpires.isAfter(DateTime.now())}');
print(
'Token expires is after now ${_tokenExpires.isAfter(DateTime.now())}');
}

if (_token != null && _tokenExpires != null && _tokenExpires.isAfter(DateTime.now())) {
if (_token != null &&
_tokenExpires != null &&
_tokenExpires.isAfter(DateTime.now())) {
_loggingIn = true;
_loggingInSubject.add(_loggingIn);
call('login', [
{'resume': _token}
]).then((result) {
_userId = result['id'];
_token = result['token'];
_tokenExpires =
DateTime.fromMillisecondsSinceEpoch(result['tokenExpires']['\$date']);
_tokenExpires = DateTime.fromMillisecondsSinceEpoch(
result['tokenExpires']['\$date']);
_loggingIn = false;
_loggingInSubject.add(_loggingIn);
_userIdSubject.add(_userId);
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: dart_meteor
description: This library make connection between meteor backend and flutter app easily. Design to work seamlessly with StreamBuilder and FutureBuilder.
version: 1.0.5
version: 1.0.6
homepage: https://github.com/tanutapi/dart_meteor
author: Tanut Apiwong <[email protected]>

Expand Down

0 comments on commit da7924e

Please sign in to comment.