getUrlWithParams method

Future<String> getUrlWithParams()

parses the params and makes sure they are either inserted into the path (if used like /user/:var1/:var2/) or if not defined there, they will be added as query params

Implementation

Future<String> getUrlWithParams() async {
  // get the combined params of client and request
  final clientAndRequestParams =
      getEnvironment().getCombinedParams(await getParams(params ?? {}));

  // make sure that our overwrite sticks (it is possible, that the `getParams` method was overwritten,
  // but we still want to have the overwrite at the very end, but also when somebody wants to
  // return the `getParams` method. This is why we have it in there twice.)
  final combinedParams = {...clientAndRequestParams, ...overwriteParams};

  // if no params given -> nothing to do
  if (combinedParams.isEmpty) {
    return getEnvironment().baseUrl + await getUrl();
  }

  // otherwise loop through the combinedParams and try to replace or add the combinedParams
  String retUrl = getEnvironment().baseUrl + await getUrl();
  List<String> queryParams = [];
  for (var paramKey in combinedParams.keys) {
    // if the param value is null -> nothing to add here
    if (combinedParams[paramKey] == null) {
      continue;
    }

    // if the param key is defined within our url -> replace it there
    if (retUrl.contains(':$paramKey')) {
      retUrl = retUrl.replaceAll(':$paramKey', combinedParams[paramKey]!);
      continue;
    }

    // otherwise add it to the query combinedParams
    queryParams.add('$paramKey=${combinedParams[paramKey]!}');
  }

  // if we have query combinedParams -> add them to the url
  if (queryParams.isNotEmpty) {
    retUrl = '$retUrl?${queryParams.join('&')}';
  }

  // return it
  return retUrl;
}