| | | 1 | | using Anichron.Infrastructure.Data; |
| | | 2 | | using Microsoft.Extensions.Configuration; |
| | | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using System.IO.Abstractions; |
| | | 6 | | |
| | | 7 | | namespace Anichron.Infrastructure.Configuration; |
| | | 8 | | |
| | | 9 | | public static class DatabaseConfiguration |
| | | 10 | | { |
| | | 11 | | extension(IServiceCollection services) |
| | | 12 | | { |
| | | 13 | | public IServiceCollection AddDatabaseSettings(IConfiguration configuration) |
| | 26 | 14 | | { |
| | 26 | 15 | | services.AddOptions<DatabaseConnectionSettings>() |
| | 26 | 16 | | .Configure(settings => Bind(configuration, new FileSystem(), settings)) |
| | 26 | 17 | | .ValidateOnStart(); |
| | 26 | 18 | | return services.AddSingleton<IValidateOptions<DatabaseConnectionSettings>, DatabaseSettingsValidator>(); |
| | | 19 | | } |
| | | 20 | | } |
| | | 21 | | |
| | | 22 | | internal static void Bind(IConfiguration configuration, IFileSystem fileSystem, DatabaseConnectionSettings settings) |
| | 30 | 23 | | { |
| | 30 | 24 | | var section = configuration.GetSection("POSTGRES_CONNECTION"); |
| | | 25 | | |
| | 30 | 26 | | settings.Host = section["HOST"]; |
| | 30 | 27 | | settings.Database = section["DBNAME"]; |
| | 30 | 28 | | settings.Port = int.TryParse(section["PORT"], out var port) ? port : PostgresConstants.DefaultPort; |
| | 30 | 29 | | settings.Username = SecretOrConfig(section, "USER_FILE", "USER", fileSystem); |
| | 30 | 30 | | settings.Password = SecretOrConfig(section, "PASSWORD_FILE", "PASSWORD", fileSystem); |
| | 30 | 31 | | } |
| | | 32 | | |
| | | 33 | | private static string? SecretOrConfig( |
| | | 34 | | IConfigurationSection section, string fileKey, string configKey, IFileSystem fileSystem) |
| | 60 | 35 | | { |
| | 60 | 36 | | var filePath = section[fileKey]; |
| | 60 | 37 | | return !string.IsNullOrEmpty(filePath) && fileSystem.File.Exists(filePath) |
| | 60 | 38 | | ? fileSystem.File.ReadAllText(filePath).Trim() |
| | 60 | 39 | | : section[configKey]; |
| | 60 | 40 | | } |
| | | 41 | | } |