run<T> method

Future<T> run<T>(
  1. LemmyApiQuery<T> query
)

Run a given query

Implementation

Future<T> run<T>(LemmyApiQuery<T> query) async {
  // get a future based on http method

  if (host.contains('localhost')) {
    return _runLocalhost(query);
  }

  final res = await () {
    switch (query.httpMethod) {
      case HttpMethod.get:
        return http.get(
            Uri.https(
              host,
              '$extraPath${query.path}',
              <String, String>{
                for (final entry in query.toJson().entries)
                  entry.key: entry.value.toString()
              },
            ),
            headers: {
              'Authorization': query.toJson().containsKey('auth')
                  ? 'Bearer ${query.toJson()['auth']}'
                  : ''
            });
      case HttpMethod.post:
        return http.post(
          Uri.https(host, '$extraPath${query.path}'),
          body: jsonEncode(query.toJson()),
          headers: {
            'Content-Type': 'application/json',
            'Authorization': query.toJson().containsKey('auth')
                ? 'Bearer ${query.toJson()['auth']}'
                : ''
          },
        );
      case HttpMethod.put:
        return http.put(
          Uri.https(host, '$extraPath${query.path}'),
          body: jsonEncode(query.toJson()),
          headers: {
            'Content-Type': 'application/json',
            'Authorization': query.toJson().containsKey('auth')
                ? 'Bearer ${query.toJson()['auth']}'
                : ''
          },
        );
    }
  }();

  // if status code is not \in [200; 300) then throw an exception with a correct message
  if (!res.ok) {
    final String errorMessage = () {
      try {
        final Map<String, dynamic> json = jsonDecode(res.body);
        return json['error'];
      } on FormatException {
        return res.body;
      }
    }();

    throw LemmyApiException(errorMessage);
  }

  // augment responses with `instance_host`
  final Map<String, dynamic> json = jsonDecode(utf8.decode(res.bodyBytes));
  _augmentInstanceHost(host, json);

  return query.responseFactory(json);
}