post<T> method

Future<ApiResult<T>> post<T>({
  1. required String path,
  2. required T decoder(
    1. Response
    ),
  3. Map<String, Object> parameters = const {},
  4. Map<String, String> headers = const {},
  5. required dynamic body,
})

Executes HTTP POST request path - relative to baseUrl path decoder - function which will be called if http request was successful to convert http.Response to T parameters - collection of query parameters headers - collection of headers which should be applied to this request body - http request body which will be encode to JSON

Implementation

Future<ApiResult<T>> post<T>({
  required String path,
  required T Function(http.Response) decoder,
  Map<String, Object> parameters = const {},
  Map<String, String> headers = const {},
  required dynamic body,
}) async {
  final requestUrl = _buildRequestUrl(path, parameters: parameters);
  logger?.info('HTTP POST $requestUrl');

  try {
    final requestHeaders = _buildHeaders(requestHeaders: headers);

    final httpResponse = await http.post(
      Uri.parse(requestUrl),
      headers: requestHeaders,
      body: jsonEncode(body),
    );

    logger?.info('HTTP POST $requestUrl RESPONSE: ${httpResponse.body}');

    if (httpResponse.statusCode != 200) {
      throw Exception('${httpResponse.statusCode} ${httpResponse.body}');
    }

    final data = decoder.call(httpResponse);

    return ApiResult.success(data);
  } on Exception catch (error) {
    logger?.error('HTTP POST FAILED', error);
    return ApiResult.failed(error);
  }
}