fetch function

Future<Response> fetch(
  1. String url, {
  2. String method = 'GET',
  3. dynamic body,
  4. Map<String, String>? headers,
  5. Signal? signal,
})

Implementation

Future<Response> fetch(
  String url, {
  String method = 'GET',
  dynamic? body,
  Map<String, String>? headers,
  Signal? signal,
}) async {
  var uri = Uri.parse(url);

  if (uri.scheme.isEmpty) {
    uri = Uri(
      scheme: FetchConfig.scheme,
      host: FetchConfig.host,
      port: FetchConfig.port,
      path: uri.path,
      query: uri.query,
    );
  }

  final path = uri.path + (uri.query != null ? '?${uri.query}' : '');

  final req = await _client.open(
    method,
    uri.host,
    uri.port,
    path,
  );

  signal?._onSignal = () => req.abort(AbortError(), StackTrace.current);

  if (headers != null) {
    headers.forEach((key, value) {
      req.headers.add(key, value);
    });
  }

  if (body is String) {
    req.add(c.utf8.encode(body));
    await req.flush();
  } else if (body is List<int>) {
    req.add(body);
  }

  final res = await req.close();

  return Response(req, res);
}