Skip to content

Commit 3100e0b

Browse files
refactor: Change async methods to return Task directly in API controllers and integration tests
1 parent e17777a commit 3100e0b

File tree

5 files changed

+62
-54
lines changed

5 files changed

+62
-54
lines changed

src/MX.Api.IntegrationTests/DummyApis/ProductApi/Controllers/ProductsController.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -53,17 +53,17 @@ public async Task<IActionResult> GetProduct(int id)
5353
/// </summary>
5454
/// <param name="cancellationToken">Cancellation token</param>
5555
/// <returns>Collection of products</returns>
56-
async Task<ApiResult<CollectionModel<Product>>> IProductApiV1.GetProductsAsync(CancellationToken cancellationToken)
56+
Task<ApiResult<CollectionModel<Product>>> IProductApiV1.GetProductsAsync(CancellationToken cancellationToken)
5757
{
5858
// Check for authentication header
5959
var authHeader = Request.Headers.Authorization.FirstOrDefault();
6060
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer test-product-key"))
6161
{
62-
return new ApiResponse<CollectionModel<Product>>(
62+
return Task.FromResult(new ApiResponse<CollectionModel<Product>>(
6363
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
6464
ApiErrorConstants.ErrorMessages.InvalidOrMissingAuthentication,
6565
ApiErrorConstants.ErrorDetails.BearerTokenRequired)
66-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
66+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
6767
}
6868

6969
var collection = new CollectionModel<Product>
@@ -73,7 +73,7 @@ async Task<ApiResult<CollectionModel<Product>>> IProductApiV1.GetProductsAsync(C
7373
FilteredCount = Products.Count
7474
};
7575

76-
return new ApiResponse<CollectionModel<Product>>(collection).ToApiResult();
76+
return Task.FromResult(new ApiResponse<CollectionModel<Product>>(collection).ToApiResult());
7777
}
7878

7979
/// <summary>
@@ -82,29 +82,29 @@ async Task<ApiResult<CollectionModel<Product>>> IProductApiV1.GetProductsAsync(C
8282
/// <param name="id">Product ID</param>
8383
/// <param name="cancellationToken">Cancellation token</param>
8484
/// <returns>Product or error</returns>
85-
async Task<ApiResult<Product>> IProductApiV1.GetProductAsync(int id, CancellationToken cancellationToken)
85+
Task<ApiResult<Product>> IProductApiV1.GetProductAsync(int id, CancellationToken cancellationToken)
8686
{
8787
// Check for authentication header
8888
var authHeader = Request.Headers.Authorization.FirstOrDefault();
8989
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer test-product-key"))
9090
{
91-
return new ApiResponse<Product>(
91+
return Task.FromResult(new ApiResponse<Product>(
9292
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
9393
ApiErrorConstants.ErrorMessages.InvalidOrMissingAuthentication,
9494
ApiErrorConstants.ErrorDetails.BearerTokenRequired)
95-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
95+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
9696
}
9797

9898
var product = Products.FirstOrDefault(p => p.Id == id);
9999
if (product == null)
100100
{
101-
return new ApiResponse<Product>(
101+
return Task.FromResult(new ApiResponse<Product>(
102102
new ApiError(ApiErrorConstants.ErrorCodes.NotFound,
103103
string.Format(ApiErrorConstants.ErrorMessages.ResourceNotFound, "Product", id),
104104
string.Format(ApiErrorConstants.ErrorDetails.ResourceDoesNotExist, "product"))
105-
).ToApiResult(System.Net.HttpStatusCode.NotFound);
105+
).ToApiResult(System.Net.HttpStatusCode.NotFound));
106106
}
107107

108-
return new ApiResponse<Product>(product).ToApiResult();
108+
return Task.FromResult(new ApiResponse<Product>(product).ToApiResult());
109109
}
110110
}

src/MX.Api.IntegrationTests/DummyApis/UserApi/Controllers/UsersController.cs

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -104,26 +104,26 @@ public ActionResult<ApiResponse<string>> HealthCheck()
104104
/// <param name="pageSize">Page size</param>
105105
/// <param name="cancellationToken">Cancellation token</param>
106106
/// <returns>Paginated users</returns>
107-
async Task<ApiResult<CollectionModel<User>>> IUserApiV1.GetUsersAsync(int page, int pageSize, CancellationToken cancellationToken)
107+
Task<ApiResult<CollectionModel<User>>> IUserApiV1.GetUsersAsync(int page, int pageSize, CancellationToken cancellationToken)
108108
{
109109
// Bearer token validation
110110
if (!Request.Headers.ContainsKey("Authorization"))
111111
{
112-
return new ApiResponse<CollectionModel<User>>(
112+
return Task.FromResult(new ApiResponse<CollectionModel<User>>(
113113
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
114114
ApiErrorConstants.ErrorMessages.AuthorizationHeaderRequired,
115115
ApiErrorConstants.ErrorDetails.BearerTokenMissing)
116-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
116+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
117117
}
118118

119119
var authHeader = Request.Headers["Authorization"].ToString();
120120
if (!authHeader.StartsWith("Bearer ") || authHeader != "Bearer user-test-token")
121121
{
122-
return new ApiResponse<CollectionModel<User>>(
122+
return Task.FromResult(new ApiResponse<CollectionModel<User>>(
123123
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
124124
ApiErrorConstants.ErrorMessages.InvalidOrMissingAuthentication,
125125
ApiErrorConstants.ErrorDetails.InvalidBearerToken)
126-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
126+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
127127
}
128128

129129
_logger.LogInformation("Getting users page {Page} with size {PageSize}", page, pageSize);
@@ -141,7 +141,7 @@ async Task<ApiResult<CollectionModel<User>>> IUserApiV1.GetUsersAsync(int page,
141141
FilteredCount = totalCount // For simplicity, no filtering in this demo
142142
};
143143

144-
return new ApiResponse<CollectionModel<User>>(collection).ToApiResult();
144+
return Task.FromResult(new ApiResponse<CollectionModel<User>>(collection).ToApiResult());
145145
}
146146

147147
/// <summary>
@@ -150,41 +150,41 @@ async Task<ApiResult<CollectionModel<User>>> IUserApiV1.GetUsersAsync(int page,
150150
/// <param name="userId">User ID</param>
151151
/// <param name="cancellationToken">Cancellation token</param>
152152
/// <returns>User</returns>
153-
async Task<ApiResult<User>> IUserApiV1.GetUserByIdAsync(int userId, CancellationToken cancellationToken)
153+
Task<ApiResult<User>> IUserApiV1.GetUserByIdAsync(int userId, CancellationToken cancellationToken)
154154
{
155155
// Bearer token validation
156156
if (!Request.Headers.ContainsKey("Authorization"))
157157
{
158-
return new ApiResponse<User>(
158+
return Task.FromResult(new ApiResponse<User>(
159159
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
160160
ApiErrorConstants.ErrorMessages.AuthorizationHeaderRequired,
161161
ApiErrorConstants.ErrorDetails.BearerTokenMissing)
162-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
162+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
163163
}
164164

165165
var authHeader = Request.Headers["Authorization"].ToString();
166166
if (!authHeader.StartsWith("Bearer ") || authHeader != "Bearer user-test-token")
167167
{
168-
return new ApiResponse<User>(
168+
return Task.FromResult(new ApiResponse<User>(
169169
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
170170
ApiErrorConstants.ErrorMessages.InvalidOrMissingAuthentication,
171171
ApiErrorConstants.ErrorDetails.InvalidBearerToken)
172-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
172+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
173173
}
174174

175175
_logger.LogInformation("Getting user {UserId}", userId);
176176

177177
var user = _users.FirstOrDefault(u => u.Id == userId);
178178
if (user == null)
179179
{
180-
return new ApiResponse<User>(
180+
return Task.FromResult(new ApiResponse<User>(
181181
new ApiError(ApiErrorConstants.ErrorCodes.NotFound,
182182
string.Format(ApiErrorConstants.ErrorMessages.ResourceNotFound, "User", userId),
183183
string.Format(ApiErrorConstants.ErrorDetails.ResourceDoesNotExist, "user"))
184-
).ToApiResult(System.Net.HttpStatusCode.NotFound);
184+
).ToApiResult(System.Net.HttpStatusCode.NotFound));
185185
}
186186

187-
return new ApiResponse<User>(user).ToApiResult();
187+
return Task.FromResult(new ApiResponse<User>(user).ToApiResult());
188188
}
189189

190190
/// <summary>
@@ -193,38 +193,38 @@ async Task<ApiResult<User>> IUserApiV1.GetUserByIdAsync(int userId, Cancellation
193193
/// <param name="user">User to create</param>
194194
/// <param name="cancellationToken">Cancellation token</param>
195195
/// <returns>Created user</returns>
196-
async Task<ApiResult<User>> IUserApiV1.CreateUserAsync(User user, CancellationToken cancellationToken)
196+
Task<ApiResult<User>> IUserApiV1.CreateUserAsync(User user, CancellationToken cancellationToken)
197197
{
198198
// Bearer token validation
199199
if (!Request.Headers.ContainsKey("Authorization"))
200200
{
201-
return new ApiResponse<User>(
201+
return Task.FromResult(new ApiResponse<User>(
202202
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
203203
ApiErrorConstants.ErrorMessages.AuthorizationHeaderRequired,
204204
ApiErrorConstants.ErrorDetails.BearerTokenMissing)
205-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
205+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
206206
}
207207

208208
var authHeader = Request.Headers["Authorization"].ToString();
209209
if (!authHeader.StartsWith("Bearer ") || authHeader != "Bearer user-test-token")
210210
{
211-
return new ApiResponse<User>(
211+
return Task.FromResult(new ApiResponse<User>(
212212
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
213213
ApiErrorConstants.ErrorMessages.InvalidOrMissingAuthentication,
214214
ApiErrorConstants.ErrorDetails.InvalidBearerToken)
215-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
215+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
216216
}
217217

218218
_logger.LogInformation("Creating user {Username}", user.Username);
219219

220220
// Check if username already exists
221221
if (_users.Any(u => u.Username == user.Username))
222222
{
223-
return new ApiResponse<User>(
223+
return Task.FromResult(new ApiResponse<User>(
224224
new ApiError(ApiErrorConstants.ErrorCodes.ResourceExists,
225225
string.Format(ApiErrorConstants.ErrorMessages.ResourceAlreadyExists, "User", "username", user.Username),
226226
string.Format(ApiErrorConstants.ErrorDetails.ResourceAlreadyExistsDetail, "user", "username"))
227-
).ToApiResult(System.Net.HttpStatusCode.BadRequest);
227+
).ToApiResult(System.Net.HttpStatusCode.BadRequest));
228228
}
229229

230230
// Set the ID and creation timestamp
@@ -233,7 +233,7 @@ async Task<ApiResult<User>> IUserApiV1.CreateUserAsync(User user, CancellationTo
233233

234234
_users.Add(user);
235235

236-
return new ApiResponse<User>(user).ToApiResult(System.Net.HttpStatusCode.Created);
236+
return Task.FromResult(new ApiResponse<User>(user).ToApiResult(System.Net.HttpStatusCode.Created));
237237
}
238238

239239
/// <summary>
@@ -242,42 +242,42 @@ async Task<ApiResult<User>> IUserApiV1.CreateUserAsync(User user, CancellationTo
242242
/// <param name="userId">User ID to delete</param>
243243
/// <param name="cancellationToken">Cancellation token</param>
244244
/// <returns>Deletion result</returns>
245-
async Task<ApiResult<string>> IUserApiV1.DeleteUserAsync(int userId, CancellationToken cancellationToken)
245+
Task<ApiResult<string>> IUserApiV1.DeleteUserAsync(int userId, CancellationToken cancellationToken)
246246
{
247247
// Bearer token validation
248248
if (!Request.Headers.ContainsKey("Authorization"))
249249
{
250-
return new ApiResponse<string>(
250+
return Task.FromResult(new ApiResponse<string>(
251251
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
252252
ApiErrorConstants.ErrorMessages.AuthorizationHeaderRequired,
253253
ApiErrorConstants.ErrorDetails.BearerTokenMissing)
254-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
254+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
255255
}
256256

257257
var authHeader = Request.Headers["Authorization"].ToString();
258258
if (!authHeader.StartsWith("Bearer ") || authHeader != "Bearer user-test-token")
259259
{
260-
return new ApiResponse<string>(
260+
return Task.FromResult(new ApiResponse<string>(
261261
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
262262
ApiErrorConstants.ErrorMessages.InvalidOrMissingAuthentication,
263263
ApiErrorConstants.ErrorDetails.InvalidBearerToken)
264-
).ToApiResult(System.Net.HttpStatusCode.Unauthorized);
264+
).ToApiResult(System.Net.HttpStatusCode.Unauthorized));
265265
}
266266

267267
_logger.LogInformation("Deleting user {UserId}", userId);
268268

269269
var user = _users.FirstOrDefault(u => u.Id == userId);
270270
if (user == null)
271271
{
272-
return new ApiResponse<string>(
272+
return Task.FromResult(new ApiResponse<string>(
273273
new ApiError(ApiErrorConstants.ErrorCodes.NotFound,
274274
string.Format(ApiErrorConstants.ErrorMessages.ResourceNotFound, "User", userId),
275275
string.Format(ApiErrorConstants.ErrorDetails.ResourceDoesNotExist, "user"))
276-
).ToApiResult(System.Net.HttpStatusCode.NotFound);
276+
).ToApiResult(System.Net.HttpStatusCode.NotFound));
277277
}
278278

279279
_users.Remove(user);
280280

281-
return new ApiResponse<string>($"User {userId} deleted successfully").ToApiResult();
281+
return Task.FromResult(new ApiResponse<string>($"User {userId} deleted successfully").ToApiResult());
282282
}
283283
}

src/MX.Api.IntegrationTests/DummyApis/WeatherApi/Controllers/WeatherController.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ public async Task<IActionResult> HealthCheck()
7676
/// <param name="days">Number of days to forecast</param>
7777
/// <param name="cancellationToken">Cancellation token</param>
7878
/// <returns>Weather forecasts</returns>
79-
async Task<ApiResult<IEnumerable<WeatherForecast>>> IWeatherApiClient.GetForecastAsync(
79+
Task<ApiResult<IEnumerable<WeatherForecast>>> IWeatherApiClient.GetForecastAsync(
8080
string location,
8181
int days,
8282
CancellationToken cancellationToken)
@@ -88,7 +88,7 @@ async Task<ApiResult<IEnumerable<WeatherForecast>>> IWeatherApiClient.GetForecas
8888
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
8989
ApiErrorConstants.ErrorMessages.ApiKeyRequired,
9090
ApiErrorConstants.ErrorDetails.XApiKeyHeaderMissing));
91-
return unauthorizedResponse.ToApiResult(System.Net.HttpStatusCode.Unauthorized);
91+
return Task.FromResult(unauthorizedResponse.ToApiResult(System.Net.HttpStatusCode.Unauthorized));
9292
}
9393

9494
var apiKey = Request.Headers["X-API-Key"].ToString();
@@ -98,7 +98,7 @@ async Task<ApiResult<IEnumerable<WeatherForecast>>> IWeatherApiClient.GetForecas
9898
new ApiError(ApiErrorConstants.ErrorCodes.InvalidApiKey,
9999
ApiErrorConstants.ErrorMessages.InvalidApiKey,
100100
ApiErrorConstants.ErrorDetails.InvalidApiKeyProvided));
101-
return invalidKeyResponse.ToApiResult(System.Net.HttpStatusCode.Unauthorized);
101+
return Task.FromResult(invalidKeyResponse.ToApiResult(System.Net.HttpStatusCode.Unauthorized));
102102
}
103103

104104
_logger.LogInformation("Getting weather forecast for {Location} for {Days} days", location, days);
@@ -112,7 +112,7 @@ async Task<ApiResult<IEnumerable<WeatherForecast>>> IWeatherApiClient.GetForecas
112112
});
113113

114114
var response = new ApiResponse<IEnumerable<WeatherForecast>>(forecasts);
115-
return response.ToApiResult();
115+
return Task.FromResult(response.ToApiResult());
116116
}
117117

118118
/// <summary>
@@ -121,7 +121,7 @@ async Task<ApiResult<IEnumerable<WeatherForecast>>> IWeatherApiClient.GetForecas
121121
/// <param name="location">The location to get current weather for</param>
122122
/// <param name="cancellationToken">Cancellation token</param>
123123
/// <returns>Current weather</returns>
124-
async Task<ApiResult<WeatherForecast>> IWeatherApiClient.GetCurrentWeatherAsync(
124+
Task<ApiResult<WeatherForecast>> IWeatherApiClient.GetCurrentWeatherAsync(
125125
string location,
126126
CancellationToken cancellationToken)
127127
{
@@ -132,7 +132,7 @@ async Task<ApiResult<WeatherForecast>> IWeatherApiClient.GetCurrentWeatherAsync(
132132
new ApiError(ApiErrorConstants.ErrorCodes.Unauthorized,
133133
ApiErrorConstants.ErrorMessages.ApiKeyRequired,
134134
ApiErrorConstants.ErrorDetails.XApiKeyHeaderMissing));
135-
return unauthorizedResponse.ToApiResult(System.Net.HttpStatusCode.Unauthorized);
135+
return Task.FromResult(unauthorizedResponse.ToApiResult(System.Net.HttpStatusCode.Unauthorized));
136136
}
137137

138138
var apiKey = Request.Headers["X-API-Key"].ToString();
@@ -142,7 +142,7 @@ async Task<ApiResult<WeatherForecast>> IWeatherApiClient.GetCurrentWeatherAsync(
142142
new ApiError(ApiErrorConstants.ErrorCodes.InvalidApiKey,
143143
ApiErrorConstants.ErrorMessages.InvalidApiKey,
144144
ApiErrorConstants.ErrorDetails.InvalidApiKeyProvided));
145-
return invalidKeyResponse.ToApiResult(System.Net.HttpStatusCode.Unauthorized);
145+
return Task.FromResult(invalidKeyResponse.ToApiResult(System.Net.HttpStatusCode.Unauthorized));
146146
}
147147

148148
_logger.LogInformation("Getting current weather for {Location}", location);
@@ -156,18 +156,18 @@ async Task<ApiResult<WeatherForecast>> IWeatherApiClient.GetCurrentWeatherAsync(
156156
};
157157

158158
var response = new ApiResponse<WeatherForecast>(current);
159-
return response.ToApiResult();
159+
return Task.FromResult(response.ToApiResult());
160160
}
161161

162162
/// <summary>
163163
/// Performs a health check
164164
/// </summary>
165165
/// <param name="cancellationToken">Cancellation token</param>
166166
/// <returns>Health status</returns>
167-
async Task<ApiResult<string>> IWeatherApiClient.HealthCheckAsync(CancellationToken cancellationToken)
167+
Task<ApiResult<string>> IWeatherApiClient.HealthCheckAsync(CancellationToken cancellationToken)
168168
{
169169
var response = new ApiResponse<string>("Weather API is healthy");
170-
return response.ToApiResult();
170+
return Task.FromResult(response.ToApiResult());
171171
}
172172

173173
#endregion

0 commit comments

Comments
 (0)