Skip to content

Commit 53ce449

Browse files
committed
Cleaned up the http client code in user manager
1 parent f114f35 commit 53ce449

File tree

2 files changed

+51
-29
lines changed

2 files changed

+51
-29
lines changed

FirebaseAdmin/FirebaseAdmin/Auth/FirebaseUserManager.cs

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -38,24 +38,23 @@ internal class FirebaseUserManager : IDisposable
3838

3939
internal FirebaseUserManager(FirebaseUserManagerArgs args)
4040
{
41+
if (string.IsNullOrEmpty(args.ProjectId))
42+
{
43+
throw new ArgumentException(
44+
"Must initialize FirebaseApp with a project ID to manage users.");
45+
}
46+
4147
this.httpClient = args.ClientFactory.CreateAuthorizedHttpClient(args.Credential);
4248
this.baseUrl = string.Format(IdTooklitUrl, args.ProjectId);
4349
}
4450

4551
public static FirebaseUserManager Create(FirebaseApp app)
4652
{
47-
var projectId = app.GetProjectId();
48-
if (string.IsNullOrEmpty(projectId))
49-
{
50-
throw new ArgumentException(
51-
"Must initialize FirebaseApp with a project ID to manage users.");
52-
}
53-
5453
var args = new FirebaseUserManagerArgs
5554
{
5655
ClientFactory = new HttpClientFactory(),
5756
Credential = app.Options.Credential,
58-
ProjectId = projectId,
57+
ProjectId = app.GetProjectId(),
5958
};
6059

6160
return new FirebaseUserManager(args);
@@ -89,6 +88,11 @@ private async Task<TResult> PostAndDeserializeAsync<TResult>(
8988
string path, object body, CancellationToken cancellationToken)
9089
{
9190
var json = await this.PostAsync(path, body, cancellationToken).ConfigureAwait(false);
91+
return this.SafeDeserialize<TResult>(json);
92+
}
93+
94+
private TResult SafeDeserialize<TResult>(string json)
95+
{
9296
try
9397
{
9498
return NewtonsoftJsonSerializer.Instance.Deserialize<TResult>(json);
@@ -101,34 +105,38 @@ private async Task<TResult> PostAndDeserializeAsync<TResult>(
101105

102106
private async Task<string> PostAsync(
103107
string path, object body, CancellationToken cancellationToken)
108+
{
109+
var request = new HttpRequestMessage()
110+
{
111+
Method = HttpMethod.Post,
112+
RequestUri = new Uri($"{this.baseUrl}/{path}"),
113+
Content = NewtonsoftJsonSerializer.Instance.CreateJsonHttpContent(body),
114+
};
115+
return await this.SendAsync(request, cancellationToken).ConfigureAwait(false);
116+
}
117+
118+
private async Task<string> SendAsync(
119+
HttpRequestMessage request, CancellationToken cancellationToken)
104120
{
105121
try
106122
{
107-
var url = $"{this.baseUrl}/{path}";
108-
return await this.SendRequestAsync(url, body, cancellationToken)
123+
var response = await this.httpClient.SendAsync(request, cancellationToken)
109124
.ConfigureAwait(false);
125+
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
126+
if (!response.IsSuccessStatusCode)
127+
{
128+
var error = "Response status code does not indicate success: "
129+
+ $"{(int)response.StatusCode} ({response.StatusCode})"
130+
+ $"{Environment.NewLine}{json}";
131+
throw new FirebaseException(error);
132+
}
133+
134+
return json;
110135
}
111136
catch (HttpRequestException e)
112137
{
113138
throw new FirebaseException("Error while calling Firebase Auth service", e);
114139
}
115140
}
116-
117-
private async Task<string> SendRequestAsync(
118-
string url, object body, CancellationToken cancellationToken)
119-
{
120-
var response = await this.httpClient.PostJsonAsync(url, body, cancellationToken)
121-
.ConfigureAwait(false);
122-
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
123-
if (!response.IsSuccessStatusCode)
124-
{
125-
var error = "Response status code does not indicate success: "
126-
+ $"{(int)response.StatusCode} ({response.StatusCode})"
127-
+ $"{Environment.NewLine}{json}";
128-
throw new FirebaseException(error);
129-
}
130-
131-
return json;
132-
}
133141
}
134142
}

FirebaseAdmin/FirebaseAdmin/Extensions.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,26 @@ public static ConfigurableHttpClient CreateAuthorizedHttpClient(
9393
public static async Task<HttpResponseMessage> PostJsonAsync<T>(
9494
this HttpClient client, string requestUri, T body, CancellationToken cancellationToken)
9595
{
96-
var payload = NewtonsoftJsonSerializer.Instance.Serialize(body);
97-
var content = new StringContent(payload, Encoding.UTF8, "application/json");
96+
var content = NewtonsoftJsonSerializer.Instance.CreateJsonHttpContent(body);
9897
return await client.PostAsync(requestUri, content, cancellationToken)
9998
.ConfigureAwait(false);
10099
}
101100

101+
/// <summary>
102+
/// Serializes the <paramref name="body"/> into JSON, and wraps the result in an instance
103+
/// of <see cref="HttpContent"/>, which can be included in an outgoing HTTP request.
104+
/// </summary>
105+
/// <returns>An instance of <see cref="HttpContent"/> containing the JSON representation
106+
/// of <paramref name="body"/>.</returns>
107+
/// <param name="serializer">The JSON serializer to serialize the given object.</param>
108+
/// <param name="body">The object that will be serialized into JSON.</param>
109+
public static HttpContent CreateJsonHttpContent(
110+
this NewtonsoftJsonSerializer serializer, object body)
111+
{
112+
var payload = serializer.Serialize(body);
113+
return new StringContent(payload, Encoding.UTF8, "application/json");
114+
}
115+
102116
/// <summary>
103117
/// Returns a Unix-styled timestamp (seconds from epoch) from the <see cref="IClock"/>.
104118
/// </summary>

0 commit comments

Comments
 (0)