Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Remove and Replace parameter functions to DefaultParameters #2047

Merged
merged 1 commit into from
Apr 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 38 additions & 2 deletions src/RestSharp/Parameters/DefaultParameters.cs
Expand Up @@ -22,22 +22,58 @@ public sealed class DefaultParameters : ParametersCollection {

public DefaultParameters(ReadOnlyRestClientOptions options) => _options = options;

public void AddParameter(Parameter parameter) {
/// <summary>
/// Safely add a default parameter to the collection.
/// </summary>
/// <param name="parameter">Parameter to add</param>
/// <returns></returns>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ArgumentException"></exception>
public DefaultParameters AddParameter(Parameter parameter) {
lock (_lock) {
if (parameter.Type == ParameterType.RequestBody)
throw new NotSupportedException(
"Cannot set request body using default parameters. Use Request.AddBody() instead."
);

if (!_options.AllowMultipleDefaultParametersWithSameName &&
!MultiParameterTypes.Contains(parameter.Type) &&
!MultiParameterTypes.Contains(parameter.Type) &&
this.Any(x => x.Name == parameter.Name)) {
throw new ArgumentException("A default parameters with the same name has already been added", nameof(parameter));
}

Parameters.Add(parameter);
}

return this;
}

/// <summary>
/// Safely removes all the default parameters with the given name and type.
/// </summary>
/// <param name="name">Parameter name</param>
/// <param name="type">Parameter type</param>
/// <returns></returns>
[PublicAPI]
public DefaultParameters RemoveParameter(string name, ParameterType type) {
lock (_lock) {
Parameters.RemoveAll(x => x.Name == name && x.Type == type);
}

return this;
}

/// <summary>
/// Replace a default parameter with the same name and type.
/// </summary>
/// <param name="parameter">Parameter instance</param>
/// <returns></returns>
[PublicAPI]
public DefaultParameters ReplaceParameter(Parameter parameter)
=>
// ReSharper disable once NotResolvedInText
RemoveParameter(Ensure.NotEmptyString(parameter.Name, "Parameter name"), parameter.Type)
.AddParameter(parameter);

static readonly ParameterType[] MultiParameterTypes = { ParameterType.QueryString, ParameterType.GetOrPost };
}