query method
Future<ChannelState>
query({
- bool state = true,
- bool watch = false,
- bool presence = false,
- PaginationParams? messagesPagination,
- PaginationParams? membersPagination,
- PaginationParams? watchersPagination,
- bool preferOffline = false,
Query the API, get messages, members or other channel fields.
Set preferOffline to true to avoid the API call if the data is already
in the offline storage.
Implementation
Future<ChannelState> query({
bool state = true,
bool watch = false,
bool presence = false,
PaginationParams? messagesPagination,
PaginationParams? membersPagination,
PaginationParams? watchersPagination,
bool preferOffline = false,
}) async {
ChannelState? channelState;
try {
// If we prefer offline, we first try to get the channel state from the
// offline storage.
if (preferOffline && !watch && cid != null) {
final persistenceClient = _client.chatPersistenceClient;
if (persistenceClient != null) {
final cachedState = await persistenceClient.getChannelStateByCid(
cid!,
messagePagination: messagesPagination,
);
// If the cached state contains messages, we can use it.
if (cachedState.messages?.isNotEmpty == true) {
channelState = cachedState;
}
}
}
// If we still don't have the channelState, we try to get it from the API.
channelState ??= await _client.queryChannel(
type,
channelId: id,
channelData: _extraData,
state: state,
watch: watch,
presence: presence,
messagesPagination: messagesPagination,
membersPagination: membersPagination,
watchersPagination: watchersPagination,
);
if (_id == null) {
_id = channelState.channel!.id;
_cid = channelState.channel!.cid;
}
// Initialize the channel state if it's not initialized yet.
if (this.state == null) {
_initState(channelState);
} else {
// Otherwise, we update the existing state with the new channel state.
//
// But, before updating the state, we check if we are querying around a
// message, If we are, we have to truncate the state to avoid potential
// gaps in the message sequence.
final isQueryingAround = switch (messagesPagination) {
PaginationParams(idAround: _?) => true,
PaginationParams(createdAtAround: _?) => true,
_ => false,
};
if (isQueryingAround) this.state?.truncate();
this.state?.updateChannelState(channelState);
}
// Submit for delivery reporting only when fetching the latest messages.
// This happens when no pagination params are provided (initial query).
if (messagesPagination == null) {
_client.channelDeliveryReporter.submitForDelivery([this]);
}
return channelState;
} catch (e, stk) {
// If we failed to get the channel state from the API and we were not
// supposed to watch the channel, we will try to get the channel state
// from the offline storage.
if (watch == false) {
if (_client.persistenceEnabled) {
return _client.chatPersistenceClient!.getChannelStateByCid(
cid!,
messagePagination: messagesPagination,
);
}
}
// Otherwise, we will just rethrow the error.
_initializedCompleter.safeCompleteError(e, stk);
rethrow;
}
}