Skip to content

Added generics to Query/LiveQuery #336

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 28 additions & 17 deletions lib/src/network/parse_live_query.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@ enum LiveQueryEvent { create, enter, update, leave, delete, error }

const String _printConstLiveQuery = 'LiveQuery: ';

class Subscription {
Subscription(this.query, this.requestId);
QueryBuilder query;
class Subscription<T extends ParseObject> {
Subscription(this.query, this.requestId, {T copyObject}) {
_copyObject = copyObject;
}
QueryBuilder<T> query;
T _copyObject;
int requestId;
bool _enabled = false;
final List<String> _liveQueryEvent = <String>[
Expand All @@ -30,6 +33,10 @@ class Subscription {
void on(LiveQueryEvent op, Function callback) {
eventCallbacks[_liveQueryEvent[op.index]] = callback;
}

T get copyObject {
return _copyObject;
}
}

enum LiveQueryClientEvent { CONNECTED, DISCONNECTED, USER_DISCONNECTED }
Expand All @@ -52,7 +59,6 @@ class LiveQueryReconnectingController with WidgetsBindingObserver {

LiveQueryReconnectingController(
this._reconnect, this._eventStream, this.debug) {

Connectivity().checkConnectivity().then(_connectivityChanged);
Connectivity().onConnectivityChanged.listen(_connectivityChanged);

Expand Down Expand Up @@ -81,7 +87,7 @@ class LiveQueryReconnectingController with WidgetsBindingObserver {
WidgetsBinding.instance.addObserver(this);
}

void _connectivityChanged(ConnectivityResult state){
void _connectivityChanged(ConnectivityResult state) {
if (!_isOnline && state != ConnectivityResult.none) _retryState = 0;
_isOnline = state != ConnectivityResult.none;
if (debug) print('$DEBUG_TAG: $state');
Expand All @@ -107,9 +113,9 @@ class LiveQueryReconnectingController with WidgetsBindingObserver {
retryInterval[_retryState] >= 0) {
_currentTimer =
Timer(Duration(milliseconds: retryInterval[_retryState]), () {
_currentTimer = null;
_reconnect();
});
_currentTimer = null;
_reconnect();
});
if (debug)
print('$DEBUG_TAG: Retrytimer set to ${retryInterval[_retryState]}ms');
if (_retryState < retryInterval.length - 1) _retryState++;
Expand All @@ -128,7 +134,7 @@ class Client {
_client = client ??
ParseHTTPClient(
sendSessionId:
autoSendSessionId ?? ParseCoreData().autoSendSessionId,
autoSendSessionId ?? ParseCoreData().autoSendSessionId,
securityContext: ParseCoreData().securityContext);

_debug = isDebugEnabled(objectLevelDebug: debug);
Expand All @@ -142,7 +148,7 @@ class Client {
}

reconnectingController = LiveQueryReconnectingController(
() => reconnect(userInitialized: false), getClientEventStream, _debug);
() => reconnect(userInitialized: false), getClientEventStream, _debug);
}
static Client get instance => _getInstance();
static Client _instance;
Expand Down Expand Up @@ -206,21 +212,24 @@ class Client {
.add(LiveQueryClientEvent.USER_DISCONNECTED);
}

Future<Subscription> subscribe(QueryBuilder query) async {
Future<Subscription<T>> subscribe<T extends ParseObject>(
QueryBuilder<T> query,
{T copyObject}) async {
if (_webSocket == null) {
await _clientEventStream.any((LiveQueryClientEvent event) =>
event == LiveQueryClientEvent.CONNECTED);
event == LiveQueryClientEvent.CONNECTED);
}
final int requestId = _requestIdGenerator();
final Subscription subscription = Subscription(query, requestId);
final Subscription<T> subscription =
Subscription<T>(query, requestId, copyObject: copyObject);
_requestSubScription[requestId] = subscription;
//After a client connects to the LiveQuery server,
//it can send a subscribe message to subscribe a ParseQuery.
_subscribeLiveQuery(subscription);
return subscription;
}

void unSubscribe(Subscription subscription) {
void unSubscribe<T extends ParseObject>(Subscription<T> subscription) {
//Mount message for Unsubscribe
final Map<String, dynamic> unsubscribeMessage = <String, dynamic>{
'op': 'unsubscribe',
Expand Down Expand Up @@ -382,10 +391,12 @@ class Client {
final String className = map['className'];
if (className == '_User') {
subscription.eventCallbacks[actionData['op']](
ParseUser(null, null, null).fromJson(map));
(subscription.copyObject ?? ParseUser(null, null, null))
.fromJson(map));
} else {
subscription.eventCallbacks[actionData['op']](
ParseObject(className).fromJson(map));
(subscription.copyObject ?? ParseObject(className))
.fromJson(map));
}
} else {
subscription.eventCallbacks[actionData['op']](actionData);
Expand All @@ -399,7 +410,7 @@ class LiveQuery {
_client = client ??
ParseHTTPClient(
sendSessionId:
autoSendSessionId ?? ParseCoreData().autoSendSessionId,
autoSendSessionId ?? ParseCoreData().autoSendSessionId,
securityContext: ParseCoreData().securityContext);

_debug = isDebugEnabled(objectLevelDebug: debug);
Expand Down
9 changes: 5 additions & 4 deletions lib/src/network/parse_query.dart
Original file line number Diff line number Diff line change
Expand Up @@ -296,13 +296,14 @@ class QueryBuilder<T extends ParseObject> {
/// Finishes the query and calls the server
///
/// Make sure to call this after defining your queries
Future<ParseResponse> query() async {
return object.query(buildQuery());
Future<ParseResponse> query<T extends ParseObject>() async {
return object.query<T>(buildQuery());
}

Future<ParseResponse> distinct(String className) async {
Future<ParseResponse> distinct<T extends ParseObject>(
String className) async {
final String queryString = 'distinct=$className';
return object.distinct(queryString);
return object.distinct<T>(queryString);
}

///Counts the number of objects that match this query
Expand Down
26 changes: 13 additions & 13 deletions lib/src/objects/parse_object.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ class ParseObject extends ParseBase implements ParseCloneable {
final Uri url = getSanitisedUri(_client, '$_path/$objectId');
final String body = json.encode(toJson(forApiRQ: true));
_saveChanges();
final Map<String, String> headers = {keyHeaderContentType:keyHeaderContentTypeJson};
final Map<String, String> headers = {
keyHeaderContentType: keyHeaderContentTypeJson
};
final Response result =
await _client.put(url, body: body, headers: headers);
return handleResponse<ParseObject>(
Expand Down Expand Up @@ -483,8 +485,7 @@ class ParseObject extends ParseBase implements ParseCloneable {
_savingChanges.remove(key);

if (offlineOnly) {
return ParseResponse()
..success = true;
return ParseResponse()..success = true;
}

try {
Expand All @@ -499,8 +500,7 @@ class ParseObject extends ParseBase implements ParseCloneable {
_unsavedChanges[key] = object;
_savingChanges[key] = object;
} else {
return ParseResponse()
..success = true;
return ParseResponse()..success = true;
}
}
} on Exception {
Expand All @@ -509,41 +509,41 @@ class ParseObject extends ParseBase implements ParseCloneable {
_savingChanges[key] = object;
}

return ParseResponse()
..success = false;
return ParseResponse()..success = false;
}

/// Can be used to create custom queries
Future<ParseResponse> query(String query) async {
Future<ParseResponse> query<T extends ParseObject>(String query) async {
try {
final Uri url = getSanitisedUri(_client, '$_path', query: query);
final Response result = await _client.get(url);
return handleResponse<ParseObject>(
return handleResponse<T>(
this, result, ParseApiRQ.query, _debug, parseClassName);
} on Exception catch (e) {
return handleException(e, ParseApiRQ.query, _debug, parseClassName);
}
}

Future<ParseResponse> distinct(String query) async {
Future<ParseResponse> distinct<T extends ParseObject>(String query) async {
try {
final Uri url = getSanitisedUri(_client, '$_aggregatepath', query: query);
final Response result = await _client.get(url);
return handleResponse<ParseObject>(
return handleResponse<T>(
this, result, ParseApiRQ.query, _debug, parseClassName);
} on Exception catch (e) {
return handleException(e, ParseApiRQ.query, _debug, parseClassName);
}
}

/// Deletes the current object locally and online
Future<ParseResponse> delete({String id, String path}) async {
Future<ParseResponse> delete<T extends ParseObject>(
{String id, String path}) async {
try {
path ??= _path;
id ??= objectId;
final Uri url = getSanitisedUri(_client, '$_path/$id');
final Response result = await _client.delete(url);
return handleResponse<ParseObject>(
return handleResponse<T>(
this, result, ParseApiRQ.delete, _debug, parseClassName);
} on Exception catch (e) {
return handleException(e, ParseApiRQ.delete, _debug, parseClassName);
Expand Down
11 changes: 6 additions & 5 deletions lib/src/utils/parse_live_list.dart
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class ParseLiveList<T extends ParseObject> {
query.keysToReturn(List<String>());
}

return await query.query();
return await query.query<T>();
}

Future<void> _init() async {
Expand All @@ -96,8 +96,9 @@ class ParseLiveList<T extends ParseObject> {

LiveQuery()
.client
.subscribe(QueryBuilder<T>.copy(_query))
.then((Subscription subscription) {
.subscribe<T>(QueryBuilder<T>.copy(_query),
copyObject: _query.object.clone(_query.object.toJson()))
.then((Subscription<T> subscription) {
_liveQuerySubscription = subscription;
subscription.on(LiveQueryEvent.create, _objectAdded);
subscription.on(LiveQueryEvent.update, _objectUpdated);
Expand Down Expand Up @@ -131,7 +132,7 @@ class ParseLiveList<T extends ParseObject> {
.isAfter(currentObject.get<DateTime>(keyVarUpdatedAt))) {
QueryBuilder<T> queryBuilder = QueryBuilder<T>.copy(_query)
..whereEqualTo(keyVarObjectId, currentObjectId);
queryBuilder.query().then((ParseResponse result) {
queryBuilder.query<T>().then((ParseResponse result) {
if (result.success) {
_objectUpdated(result.results.first);
}
Expand Down Expand Up @@ -206,7 +207,7 @@ class ParseLiveList<T extends ParseObject> {
..whereEqualTo(
keyVarObjectId, _list[index].object.get<String>(keyVarObjectId))
..setLimit(1);
final ParseResponse response = await queryBuilder.query();
final ParseResponse response = await queryBuilder.query<T>();
if (response.success && response.results != null) {
_list[index].object = response.results.first;
} else {
Expand Down