feat: add set database endpoints

This commit is contained in:
Polianin Nikita 2024-05-29 03:38:21 +03:00
parent e7ed69169c
commit ba8ccf8b7e
2 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace Mirea.Api.Dto.Requests.Configuration;
public class DatabaseRequest
{
[Required]
public required string Server { get; set; }
[Required]
public int Port { get; set; }
[Required]
public required string Database { get; set; }
[Required]
public required string User { get; set; }
[Required]
public bool Ssl { get; set; }
public string? Password { get; set; }
}

View File

@ -84,5 +84,57 @@ public class SetupController(ISetupToken setupToken, IMaintenanceModeNotConfigur
} }
} }
[HttpPost("SetPsql")]
[TokenAuthentication]
[BadRequestResponse]
public ActionResult<bool> SetPsql([FromBody] DatabaseRequest request)
{
string connectionString = $"Host={request.Server}:{request.Port};Username={request.User};Database={request.Database}";
if (request.Password != null)
connectionString += $";Password={request.Password}";
if (request.Ssl)
connectionString += ";SSL Mode=Require;";
return SetDatabase<NpgsqlConnection, NpgsqlException>(connectionString, DbSettings.DatabaseEnum.PostgresSql);
}
[HttpPost("SetMysql")]
[TokenAuthentication]
[BadRequestResponse]
public ActionResult<bool> SetMysql([FromBody] DatabaseRequest request)
{
string connectionString = $"Server={request.Server}:{request.Port};Uid={request.User};Database={request.Database}";
if (request.Password != null)
connectionString += $";Pwd={request.Password}";
if (request.Ssl)
connectionString += ";SslMode=Require;";
return SetDatabase<MySqlConnection, MySqlException>(connectionString, DbSettings.DatabaseEnum.Mysql);
}
[HttpPost("SetSqlite")]
[TokenAuthentication]
public ActionResult<bool> SetSqlite([FromQuery] string? path)
{
if (string.IsNullOrEmpty(path)) path = "database";
path = PathBuilder.Combine(path);
if (!Directory.Exists(path))
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
Directory.CreateDirectory(path);
else
Directory.CreateDirectory(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
else
throw new ControllerArgumentException("Such a folder exists. Enter a different name");
string connectionString = $"Data Source={PathBuilder.Combine(path, "database.db3")}";
return SetDatabase<SqliteConnection, SqliteException>(connectionString, DbSettings.DatabaseEnum.Sqlite);
}
}
} }