sendRequest method

Future<JRpcResponse> sendRequest(
  1. JRpcRequest request
)

Helper function for constructing, validating and handling various HTTP requests for capture.

Implementation

Future<JRpcResponse> sendRequest(JRpcRequest request) async {
  final String uriString = host ?? '';
  final Uri uri = Uri.parse(uriString);
  final Map<String, String> headers = <String, String>{
    'Content-Type': 'application/json'
  };

  // ignore: prefer_function_declarations_over_variables
  Future<JRpcResponse> helper(JRpcRequest jsonRpc) async {
    try {
      final String jsonRpcString = json.encode(jsonRpc.toJson());
      logger?.log('${jsonRpc.method} =>', jsonRpcString);
      final Response res =
          await post(uri, headers: headers, body: jsonRpcString);
      final Map<String, dynamic> jsonResponse =
          json.decode(res.body) as Map<String, dynamic>;
      final JRpcResponse jrpcResponse = JRpcResponse.fromJson(jsonResponse);
      final JRpcError? error = jrpcResponse.error;
      if (error != null) {
        throw CaptureException(error.code, error.message);
      } else {
        return jrpcResponse;
      }
      // ignore: unused_catch_clause
    } on CaptureException catch (err) {
      rethrow;
    } catch (err) {
      throw CaptureException(SktErrors.ESKT_COMMUNICATIONERROR,
          'There was an error during communication.', err.toString());
    }
  }

  final JRpcResponse response = await helper(request);

  logger?.log('${request.method} <=', json.encode(response.toString()));

  if (request.method == 'openclient') {
    /// we want to start the web service here if we can
    openWebSocket((dynamic event) {
      /// send a waitForEvent
      final CaptureResult? result = response.captureResult;
      if (result == null) {
        throw Exception('Unexpected response');
      }
      final Map<String, dynamic> waitForEvent = JRpcRequest(
              id: '1',
              method: 'waitforcaptureevent',
              params: Params(handle: result.handle))
          .toJson();
      final String waitForEventString = json.encode(waitForEvent);
      //use sink.add to send data to server
      websocket!.sink.add(waitForEventString);
      return;
    });
  }
  return response;
}