| | | 1 | | using Anichron.Infrastructure.Data; |
| | | 2 | | using Microsoft.Extensions.Configuration; |
| | | 3 | | using Npgsql; |
| | | 4 | | using System.IO.Abstractions; |
| | | 5 | | |
| | | 6 | | namespace Anichron.Infrastructure.Configuration; |
| | | 7 | | |
| | | 8 | | public static class DatabaseConfiguration |
| | | 9 | | { |
| | | 10 | | public static string GetConnectionString(IConfiguration configuration, IFileSystem fileSystem) |
| | 10 | 11 | | { |
| | | 12 | | const string sectionName = "POSTGRES_CONNECTION"; |
| | 10 | 13 | | var section = configuration.GetSection(sectionName); |
| | | 14 | | |
| | 10 | 15 | | var builder = new NpgsqlConnectionStringBuilder |
| | 10 | 16 | | { |
| | 10 | 17 | | Host = section["HOST"] ?? throw new InvalidOperationException("Postgres Host missing"), |
| | 10 | 18 | | Database = section["DBNAME"] ?? throw new InvalidOperationException("Postgres Database name missing"), |
| | 10 | 19 | | Port = int.TryParse(section["PORT"], out var p) ? p : PostgresConstants.DefaultPort, |
| | 10 | 20 | | Username = GetSecretOrConfig(section, "USER_FILE", "USER", fileSystem), |
| | 10 | 21 | | Password = GetSecretOrConfig(section, "PASSWORD_FILE", "PASSWORD", fileSystem), |
| | 10 | 22 | | Pooling = true, |
| | 10 | 23 | | }; |
| | | 24 | | |
| | 7 | 25 | | return builder.ToString(); |
| | 7 | 26 | | } |
| | | 27 | | |
| | | 28 | | private static string GetSecretOrConfig( |
| | | 29 | | IConfigurationSection section, string fileKey, string configKey, IFileSystem fileSystem) |
| | 15 | 30 | | { |
| | 15 | 31 | | var filePath = section[fileKey]; |
| | 15 | 32 | | return !string.IsNullOrEmpty(filePath) && fileSystem.File.Exists(filePath) |
| | 15 | 33 | | ? fileSystem.File.ReadAllText(filePath).Trim() |
| | 15 | 34 | | : section[configKey] |
| | 15 | 35 | | ?? throw new InvalidOperationException( |
| | 15 | 36 | | $"Configuration value for {configKey} or secret file {fileKey} not found."); |
| | 14 | 37 | | } |
| | | 38 | | } |