From e6c4b5249c7055fe323896041044bd7d515490ca Mon Sep 17 00:00:00 2001 From: crupest Date: Sat, 26 Nov 2022 20:47:11 +0800 Subject: Complete crupest-api. --- docker/crupest-api/CrupestApi/Program.cs | 181 +++++++++++++++---------------- 1 file changed, 89 insertions(+), 92 deletions(-) (limited to 'docker/crupest-api/CrupestApi/Program.cs') diff --git a/docker/crupest-api/CrupestApi/Program.cs b/docker/crupest-api/CrupestApi/Program.cs index c62bf4d..7fd6675 100644 --- a/docker/crupest-api/CrupestApi/Program.cs +++ b/docker/crupest-api/CrupestApi/Program.cs @@ -9,47 +9,40 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Console; using Microsoft.AspNetCore.Http; using CrupestApi.Config; -public class TodoItem +namespace CrupestApi { - public string Status { get; set; } = default!; - public string Title { get; set; } = default!; -} + public class TodoItem + { + public string Status { get; set; } = default!; + public string Title { get; set; } = default!; + public bool Closed { get; set; } + public string color { get; set; } = default!; + } -internal class Program -{ - private static void Main(string[] args) + internal class Program { - using var httpClient = new HttpClient(); + private static void Main(string[] args) + { + using var httpClient = new HttpClient(); - var builder = WebApplication.CreateBuilder(args); + var builder = WebApplication.CreateBuilder(args); - string configFilePath = Environment.GetEnvironmentVariable("CRUPEST_API_CONFIG_FILE") ?? "/config.json"; + string configFilePath = Environment.GetEnvironmentVariable("CRUPEST_API_CONFIG_FILE") ?? "/config.json"; - builder.Configuration.AddJsonFile(configFilePath, optional: false, reloadOnChange: true); + builder.Configuration.AddJsonFile(configFilePath, optional: false, reloadOnChange: true); - string? logFilePath = Environment.GetEnvironmentVariable("CRUPEST_API_LOG_FILE"); - if (logFilePath is not null) - { - // TODO: Log to file. - builder.Logging.AddSimpleConsole(logger => - { - logger.ColorBehavior = LoggerColorBehavior.Disabled; - }); - } + var app = builder.Build(); - var app = builder.Build(); - - app.MapGet("/api/todos", async ([FromServices] IConfiguration configuration, [FromServices] ILoggerFactory loggerFactory) => - { - var logger = loggerFactory.CreateLogger("CrupestApi.Todos"); - - static string CreateGraphQLQuery(TodoConfiguration todoConfiguration) + app.MapGet("/api/todos", async ([FromServices] IConfiguration configuration, [FromServices] ILoggerFactory loggerFactory) => { - return $$""" + var logger = loggerFactory.CreateLogger("CrupestApi.Todos"); + + static string CreateGraphQLQuery(TodoConfiguration todoConfiguration) + { + return $$""" { user(login: "{{todoConfiguration.Username}}") { projectV2(number: {{todoConfiguration.ProjectNumber}}) { @@ -76,85 +69,89 @@ internal class Program } } """; - } + } - var todoConfiguration = configuration.GetSection("Todos").Get(); - if (todoConfiguration is null) - { - throw new Exception("Fail to get todos configuration."); - } + var todoConfiguration = configuration.GetSection("Todos").Get(); + if (todoConfiguration is null) + { + throw new Exception("Fail to get todos configuration."); + } - using var requestContent = new StringContent(JsonSerializer.Serialize(new - { - query = CreateGraphQLQuery(todoConfiguration) - })); - requestContent.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Application.Json, Encoding.UTF8.WebName); + using var requestContent = new StringContent(JsonSerializer.Serialize(new + { + query = CreateGraphQLQuery(todoConfiguration) + })); + requestContent.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Application.Json, Encoding.UTF8.WebName); - using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.github.com/graphql"); - request.Content = requestContent; - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", todoConfiguration.Token); + using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.github.com/graphql"); + request.Content = requestContent; + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", todoConfiguration.Token); + request.Headers.TryAddWithoutValidation("User-Agent", "crupest"); - using var response = await httpClient.SendAsync(request); - var responseBody = await response.Content.ReadAsStringAsync(); - logger.LogInformation(response.StatusCode.ToString()); - logger.LogInformation(responseBody); + using var response = await httpClient.SendAsync(request); + var responseBody = await response.Content.ReadAsStringAsync(); + logger.LogInformation(response.StatusCode.ToString()); + logger.LogInformation(responseBody); - if (response.IsSuccessStatusCode) - { - using var responseJson = JsonSerializer.Deserialize(responseBody); - if (responseJson is null) + if (response.IsSuccessStatusCode) { - throw new Exception("Fail to deserialize response body."); - } + using var responseJson = JsonSerializer.Deserialize(responseBody); + if (responseJson is null) + { + throw new Exception("Fail to deserialize response body."); + } - var nodes = responseJson.RootElement.GetProperty("data").GetProperty("user").GetProperty("projectV2").GetProperty("items").GetProperty("nodes").EnumerateArray(); + var nodes = responseJson.RootElement.GetProperty("data").GetProperty("user").GetProperty("projectV2").GetProperty("items").GetProperty("nodes").EnumerateArray(); - var result = new List(); + var result = new List(); - foreach (var node in nodes) - { - var content = node.GetProperty("content"); - var title = content.GetProperty("title").GetString(); - if (title is null) - { - throw new Exception("Fail to get title."); - } - JsonElement closedElement; - bool closed; - if (content.TryGetProperty("closed", out closedElement)) - { - closed = closedElement.GetBoolean(); - } - else + foreach (var node in nodes) { - closed = false; + var content = node.GetProperty("content"); + var title = content.GetProperty("title").GetString(); + if (title is null) + { + throw new Exception("Fail to get title."); + } + JsonElement closedElement; + bool closed; + if (content.TryGetProperty("closed", out closedElement)) + { + closed = closedElement.GetBoolean(); + } + else + { + closed = false; + } + + result.Add(new TodoItem + { + Title = title, + Status = closed ? "Done" : "Todo", + Closed = closed, + color = closed ? "green" : "blue" + }); } - result.Add(new TodoItem + return Results.Json(result, new JsonSerializerOptions { - Title = title, - Status = closed ? "Done" : "Todo" - }); + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }, statusCode: 200); } - - return Results.Json(result, new JsonSerializerOptions + else { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }, statusCode: 200); - } - else - { - const string message = "Fail to get todos from GitHub."; - logger.LogError(message); + const string message = "Fail to get todos from GitHub."; + logger.LogError(message); - return Results.Json(new - { - message - }, statusCode: StatusCodes.Status503ServiceUnavailable); - } - }); + return Results.Json(new + { + message + }, statusCode: StatusCodes.Status503ServiceUnavailable); + } + }); - app.Run(); + app.Run(); + } } -} \ No newline at end of file +} -- cgit v1.2.3