call method

Future<GameHttpOutcome> call(
  1. String method,
  2. String path,
  3. Map<String, dynamic>? body
)

Implementation

Future<GameHttpOutcome> call(
    String method, String path, Map<String, dynamic>? body) async {
  if (!isAllowedHttpPath(path)) {
    return GameHttpError(
        GameBridgeError.badRequest, "path '$path' is not allowed");
  }
  final HttpMethod httpMethod;
  switch (method) {
    case 'GET':
      httpMethod = HttpMethod.get;
    case 'POST':
      httpMethod = HttpMethod.post;
    default:
      return const GameHttpError(
          GameBridgeError.badRequest, 'method must be GET or POST');
  }
  final url = DigiaEndpoints.gamificationEndpoint(path);
  final timeout = const Duration(milliseconds: timeoutMs);
  final result = await postGameJson(
    _networkClient,
    url: url,
    // GET carries no body; POST always sends an object, possibly empty.
    body: httpMethod == HttpMethod.post
        ? (body ?? const <String, dynamic>{})
        : null,
    method: httpMethod,
    timeout: timeout,
  );
  if (result is GameTransportFailure) {
    _log.w('Gamification http failed (path=$path) cause=${result.cause}',
        stage: TimelineStage.interaction);
    return GameHttpError(result.code, 'request failed: ${result.cause}');
  }
  final response = (result as GameTransportResponded).response;
  final status = response.statusCode;
  if (status < 200 || status > 499 || (status >= 300 && status <= 399)) {
    _log.w('Gamification http failed (path=$path, status=$status)',
        stage: TimelineStage.interaction);
    final code =
        status >= 500 ? GameBridgeError.server : GameBridgeError.network;
    return GameHttpError(code, 'http status $status', status);
  }
  Map<String, dynamic>? parsed;
  try {
    final decoded = jsonDecode((response.body ?? '').trim());
    if (decoded is Map) parsed = Map<String, dynamic>.from(decoded);
  } catch (_) {
    parsed = null;
  }
  return GameHttpResponse(status, parsed);
}