search method

Future<MessageListResult> search(
  1. String server,
  2. SearchCriteria criteria, {
  3. int? page,
  4. int? itemsPerPage,
  5. int? timeout,
  6. int? receivedAfter,
  7. bool errorOnTimeout = true,
  8. String? dir,
})

Implementation

Future<MessageListResult> search(String server, SearchCriteria criteria, {int? page, int? itemsPerPage, int? timeout, int? receivedAfter, bool errorOnTimeout = true, String? dir}) async {
  final url = Uri.parse('${baseUrl}api/messages/search');

  final params = {
    'server': server,
    'page': page?.toString(),
    'itemsPerPage': itemsPerPage?.toString(),
    'receivedAfter': receivedAfter?.toString(),
    'dir': dir
  }..removeWhere((key, value) => value == null);

  if (timeout == null) {
    final response = await client.post(url.replace(queryParameters: params), body: jsonEncode(criteria));

    if (response.statusCode != 200) {
      throw MailosaurError(response);
    }

    return MessageListResult.fromJson(jsonDecode(response.body));
  }

  final stopwatch = Stopwatch()..start();
  while (true) {
    final response = await client.post(url.replace(queryParameters: params), body: jsonEncode(criteria));

    if (response.statusCode != 200) {
      throw MailosaurError(response);
    }

    final result = MessageListResult.fromJson(jsonDecode(response.body));
    if (result.items.isNotEmpty) {
      return result;
    }

    if (stopwatch.elapsedMilliseconds > timeout) {
      if (errorOnTimeout) {
        throw MailosaurError(response);
      }
      return MessageListResult();
    }

    final delay = response.headers['x-ms-delay'];
    final delayDuration = delay != null ? int.tryParse(delay) ?? 1000 : 1000;
    await Future.delayed(Duration(milliseconds: delayDuration));
  }
}