handle method

Dispatches an incoming request to the matching registered contract binding.

Matches HTTP verb and path template, extracts path parameters, decodes input, executes the handler, and returns a BloomRpcServerResponse.

final response = await rpcRouter.handle(serverRequest);

Implementation

Future<BloomRpcServerResponse> handle(BloomRpcServerRequest request) async {
  for (final binding in _bindings) {
    if (binding.contract.method.value.toUpperCase() !=
        request.method.toUpperCase()) {
      continue;
    }

    final pathParams = binding.contract.matchPath(request.path);
    if (pathParams == null) continue;

    final serverContext = BloomRpcServerContext(
      contract: binding.contract,
      pathParams: pathParams,
      queryParams: request.queryParams,
      headers: request.headers,
      request: request,
      context: request.context,
    );

    dynamic rawInput;
    if (binding.contract.method == BloomHttpMethod.get ||
        binding.contract.method == BloomHttpMethod.head ||
        binding.contract.method == BloomHttpMethod.options) {
      rawInput = {...request.queryParams, ...pathParams};
    } else {
      rawInput = request.body;
    }

    return binding.execute(serverContext, rawInput);
  }

  return BloomRpcServerResponse(
    statusCode: 404,
    body: {
      'error':
          'No RPC handler found for ${request.method} ${request.path}',
      'statusCode': 404,
    },
  );
}