getRecentSearches method

Future<List<Suggestion>> getRecentSearches (
  1. {RecentSearchOptions queryOptions,
  2. Options options}
)

to get recent searches

Implementation

Future<List<Suggestion>> getRecentSearches(
    {RecentSearchOptions queryOptions, Options options}) async {
  String queryString = '';
  if (queryOptions == null) {
    queryOptions = RecentSearchOptions();
  }
  void addParam(String key, String value) {
    if (queryString != "") {
      queryString += "&${key}=${value}";
    } else {
      queryString += "${key}=${value}";
    }
  }

  if (this.appbaseSettings != null && this.appbaseSettings.userId != null) {
    addParam('user_id', this.appbaseSettings.userId);
  }
  if (queryOptions.size != null) {
    addParam('size', queryOptions.size.toString());
  }
  if (queryOptions.minChars != null) {
    addParam('min_chars', queryOptions.minChars.toString());
  }
  if (queryOptions.from != null) {
    addParam('from', queryOptions.from);
  }
  if (queryOptions.to != null) {
    addParam('to', queryOptions.to);
  }
  if (queryOptions.customEvents != null) {
    queryOptions.customEvents.keys.forEach((key) {
      addParam(key, queryOptions.customEvents[key]);
    });
  }
  final String url =
      "${this.url}/_analytics/${this.index}/recent-searches?${queryString}";
  try {
    final res = await http.get(url, headers: this.headers);
    if (res.statusCode >= 500) {
      return Future.error(res);
    }
    if (res.statusCode >= 400) {
      return Future.error(res);
    }
    final recentSearches = jsonDecode(res.body);
    final prev = this.recentSearches;
    // Populate the recent searches
    this.recentSearches = ((recentSearches as List).map((searchObject) =>
        Suggestion(searchObject['key'], searchObject['key']))).toList();
    this._applyOptions(new Options(stateChanges: options?.stateChanges),
        'recentSearches', prev, this.recentSearches);
    return Future.value(this.recentSearches);
  } catch (e) {
    return Future.error(e);
  }
}