handleRest method

Handle regular REST requests

Implementation

HttpResponse handleRest(HttpRequest request, Map<SupabaseRequest, SupabaseResponse> responses) {
  final url = request.uri.toString();

  final matchingRequest = responses.entries.firstWhereOrNull((r) {
    if (r.key.realtime) return false;
    final matchesRequestMethod =
        r.key.requestMethod == request.method || r.key.requestMethod == null;
    final matchesPath = request.uri.path == r.key.toUri(modelDictionary).path;
    var matchesQuery = true;
    for (final param in r.key.toUri(modelDictionary).queryParameters.entries) {
      if (!request.uri.queryParameters.containsKey(param.key) ||
          param.value != request.uri.queryParameters[param.key]) {
        matchesQuery = false;
        break;
      }
    }
    return r.key.toUri(modelDictionary).toString() == url ||
        (matchesRequestMethod && matchesPath && matchesQuery);
  });

  if (matchingRequest == null) {
    return request.response..statusCode = HttpStatus.notImplemented;
  }

  final resp = request.response
    ..statusCode = HttpStatus.ok
    ..headers.contentType = ContentType.json;
  if (matchingRequest.value.headers != null) {
    matchingRequest.value.headers!.forEach(resp.headers.set);
  }

  if (matchingRequest.value.data is List) {
    resp.write(jsonEncode(matchingRequest.value.data));
    // Handle realtime responses with an empty payload
    // so that initial subscribes will not start with a hydrate
  } else if (matchingRequest.value.data is Map) {
    final asMap = Map<String, dynamic>.from(matchingRequest.value.data);
    if (asMap.containsKey('payload') && asMap['payload'] != null) {
      resp.write(jsonEncode([]));
    } else {
      resp.write(jsonEncode(matchingRequest.value.data));
    }
  }
  return resp;
}