Skip to content

Commit

Permalink
refactor(client): pollInterval is now a Duration
Browse files Browse the repository at this point in the history
  • Loading branch information
micimize committed Sep 24, 2020
1 parent d37e81c commit fe02bb8
Show file tree
Hide file tree
Showing 7 changed files with 34 additions and 33 deletions.
7 changes: 4 additions & 3 deletions changelog-v3-v4.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ v4 aims to solve a number of sore spots, particularly with caching, largely by l
- There is now only a single `GraphQLCache`, which leverages [normalize](https://pub.dev/packages/normalize),
Giving us a much more `apollo`ish API.
- [`typePolicies`]
- [direct cache access] via `readQuery`, `writeQuery`, `readFragment`, and `writeFragment`
All of which can which can be used for [local state management]
- [direct cache access] via `readQuery`, `writeQuery`, `readFragment`, and `writeFragment`
All of which can which can be used for [local state management]
- `LazyCacheMap` has been deleted
- `GraphQLCache` marks itself for rebroadcasting (should fix some related issues)
- **`Store`** is now a seperate concern:
Expand Down Expand Up @@ -97,6 +97,7 @@ Subscription(

## Minor changes

- `pollInterval`, which used to be an `int` of `seconds`, is now a `Duration`
- As mentioned before, `documentNode: gql(...)` is now `document: gql(...)`.
- The exported `gql` utility adds `__typename` automatically.
\*\*If you define your own, make sure to include `AddTypenameVisitor`,
Expand Down Expand Up @@ -145,5 +146,5 @@ class MyQuery {
```

[local state management]: https://www.apollographql.com/docs/tutorial/local-state/#update-local-data
[`typePolicies`]: https://www.apollographql.com/docs/react/caching/cache-configuration/#the-typepolicy-type
[`typepolicies`]: https://www.apollographql.com/docs/react/caching/cache-configuration/#the-typepolicy-type
[direct cache access]: https://www.apollographql.com/docs/react/caching/cache-interaction/
2 changes: 1 addition & 1 deletion examples/flutter_bloc/lib/repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class GithubRepository {
variables: <String, dynamic>{
'nRepositories': numOfRepositories,
},
pollInterval: 4,
pollInterval: Duration(seconds: 4),
fetchResults: true,
);

Expand Down
4 changes: 2 additions & 2 deletions packages/graphql/lib/src/core/observable_query.dart
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ class ObservableQuery {
? QueryLifecycle.sideEffectsPending
: QueryLifecycle.pending;

if (options.pollInterval != null && options.pollInterval > 0) {
if (options.pollInterval != null && options.pollInterval > Duration.zero) {
startPolling(options.pollInterval);
}

Expand Down Expand Up @@ -303,7 +303,7 @@ class ObservableQuery {
/// Poll the server periodically for results.
///
/// Will be called by [fetchResults] automatically if [options.pollInterval] is set
void startPolling(int pollInterval) {
void startPolling(Duration pollInterval) {
if (options.fetchPolicy == FetchPolicy.cacheFirst ||
options.fetchPolicy == FetchPolicy.cacheOnly) {
throw Exception(
Expand Down
4 changes: 2 additions & 2 deletions packages/graphql/lib/src/core/query_options.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class QueryOptions extends BaseOptions {

/// The time interval (in milliseconds) on which this query should be
/// re-fetched from the server.
int pollInterval;
Duration pollInterval;

@override
List<Object> get properties => [...super.properties, pollInterval];
Expand Down Expand Up @@ -88,7 +88,7 @@ class WatchQueryOptions extends QueryOptions {
FetchPolicy fetchPolicy,
ErrorPolicy errorPolicy,
Object optimisticResult,
int pollInterval,
Duration pollInterval,
this.fetchResults = false,
bool eagerlyFetchResults,
Context context,
Expand Down
37 changes: 19 additions & 18 deletions packages/graphql/lib/src/links/websocket_link/websocket_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class SocketClientConfig {
}
}

enum SocketConnectionState { NOT_CONNECTED, CONNECTING, CONNECTED }
enum SocketConnectionState { notConnected, connecting, connected }

/// Wraps a standard web socket instance to marshal and un-marshal the server /
/// client payloads into dart object representation.
Expand Down Expand Up @@ -130,7 +130,8 @@ class SocketClient {
bool _connectionWasLost = false;

Timer _reconnectTimer;
WebSocket _socket;
@visibleForTesting
WebSocket socket;

Stream<GraphQLSocketMessage> _messageStream;

Expand All @@ -152,20 +153,20 @@ class SocketClient {
return;
}

_connectionStateController.value = SocketConnectionState.CONNECTING;
_connectionStateController.value = SocketConnectionState.connecting;
print('Connecting to websocket: $url...');

try {
_socket = await WebSocket.connect(
socket = await WebSocket.connect(
url,
protocols: protocols,
);
_connectionStateController.value = SocketConnectionState.CONNECTED;
_connectionStateController.value = SocketConnectionState.connected;
print('Connected to websocket.');
_write(initOperation);

_messageStream =
_socket.stream.map<GraphQLSocketMessage>(_parseSocketMessage);
socket.stream.map<GraphQLSocketMessage>(_parseSocketMessage);

if (config.inactivityTimeout != null) {
_keepAliveSubscription = _messagesOfType<ConnectionKeepAlive>().timeout(
Expand All @@ -174,9 +175,9 @@ class SocketClient {
print(
"Haven't received keep alive message for ${config.inactivityTimeout.inSeconds} seconds. Disconnecting..");
event.close();
_socket.close(WebSocketStatus.goingAway);
socket.close(WebSocketStatus.goingAway);
_connectionStateController.value =
SocketConnectionState.NOT_CONNECTED;
SocketConnectionState.notConnected;
},
).listen(null);
}
Expand All @@ -203,7 +204,7 @@ class SocketClient {
}

if (config.onConnectOrReconnect != null) {
config.onConnectOrReconnect(_socket);
config.onConnectOrReconnect(socket);
}
} catch (e) {
onConnectionLost(e);
Expand All @@ -227,8 +228,8 @@ class SocketClient {
_subscriptionInitializers.values.forEach((s) => s.hasBeenTriggered = false);

if (_connectionStateController.value !=
SocketConnectionState.NOT_CONNECTED) {
_connectionStateController.value = SocketConnectionState.NOT_CONNECTED;
SocketConnectionState.notConnected) {
_connectionStateController.value = SocketConnectionState.notConnected;
}

if (config.autoReconnect && !_connectionStateController.isClosed) {
Expand Down Expand Up @@ -258,7 +259,7 @@ class SocketClient {
print('Disposing socket client..');
_reconnectTimer?.cancel();
await Future.wait([
_socket?.close(),
socket?.close(),
_keepAliveSubscription?.cancel(),
_messageSubscription?.cancel(),
_connectionStateController?.close(),
Expand Down Expand Up @@ -293,8 +294,8 @@ class SocketClient {
}

void _write(final GraphQLSocketMessage message) {
if (_connectionStateController.value == SocketConnectionState.CONNECTED) {
_socket.add(
if (_connectionStateController.value == SocketConnectionState.connected) {
socket.add(
json.encode(
message,
toEncodable: (dynamic m) => m.toJson(),
Expand Down Expand Up @@ -325,9 +326,9 @@ class SocketClient {
final Stream<SocketConnectionState> waitForConnectedStateWithoutTimeout =
_connectionStateController
.startWith(
waitForConnection ? null : SocketConnectionState.CONNECTED)
waitForConnection ? null : SocketConnectionState.connected)
.where((SocketConnectionState state) =>
state == SocketConnectionState.CONNECTED)
state == SocketConnectionState.connected)
.take(1);

final Stream<SocketConnectionState> waitForConnectedState = addTimeout
Expand Down Expand Up @@ -419,8 +420,8 @@ class SocketClient {
_subscriptionInitializers.remove(id);

sub?.cancel();
if (_connectionStateController.value == SocketConnectionState.CONNECTED &&
_socket != null) {
if (_connectionStateController.value == SocketConnectionState.connected &&
socket != null) {
_write(StopOperation(id));
}
};
Expand Down
11 changes: 5 additions & 6 deletions packages/graphql/lib/src/scheduler/scheduler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ class QueryScheduler {
return false;
}

final Duration pollInterval =
Duration(seconds: registeredQueries[queryId].pollInterval);
final Duration pollInterval = registeredQueries[queryId].pollInterval;

return registeredQueries.containsKey(queryId) &&
pollInterval == interval;
Expand All @@ -65,13 +64,13 @@ class QueryScheduler {
WatchQueryOptions options,
String queryId,
) {
assert(options.pollInterval != null && options.pollInterval > 0);
assert(
options.pollInterval != null && options.pollInterval > Duration.zero,
);

registeredQueries[queryId] = options;

final Duration interval = Duration(
seconds: options.pollInterval,
);
final interval = options.pollInterval;

if (intervalQueries.containsKey(interval)) {
intervalQueries[interval].add(queryId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class Bloc {
variables: <String, dynamic>{
'nRepositories': nRepositories,
},
pollInterval: 4,
pollInterval: Duration(seconds: 4),
fetchResults: true,
);

Expand Down

0 comments on commit fe02bb8

Please sign in to comment.