RestySqlite/WebApi.cs

75 lines
2.4 KiB
C#
Raw Permalink Normal View History

2025-02-09 16:38:49 +03:00
using Microsoft.AspNetCore.Mvc;
2025-02-08 22:41:26 +03:00
namespace RestySqlite
{
public class WebApi
{
2025-02-09 22:05:23 +03:00
2025-02-08 22:41:26 +03:00
public static void Main()
{
2025-02-09 22:05:23 +03:00
string? dbName = Utils.ReadConfig("database", "sql") ?? throw new NullReferenceException("Database name is null!");
2025-02-09 16:38:49 +03:00
if (dbName.Length == 0)
{
Console.WriteLine("You should specify database name in conf.toml!");
return;
}
2025-02-09 16:47:08 +03:00
if (!File.Exists($"{dbName}.db"))
{
Console.WriteLine($"Database {dbName}.db not found in folder!");
2025-02-09 22:05:23 +03:00
Utils.CreateDatabase(dbName);
2025-02-09 16:47:08 +03:00
}
2025-02-09 22:05:23 +03:00
string? handle = Utils.ReadConfig("handle", "api") ?? throw new NullReferenceException("API handle is null!");
2025-02-09 16:38:49 +03:00
int port = Utils.ReadConfig("port", "api");
2025-02-09 22:05:23 +03:00
RunServer(dbName, handle, port);
}
static public void RunServer(string dbName, string handle, int port)
{
2025-02-09 16:38:49 +03:00
var builder = WebApplication.CreateBuilder();
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.Listen(System.Net.IPAddress.Any, port); // Listen on all network interfaces on port 5000
});
var app = builder.Build();
2025-02-08 22:41:26 +03:00
2025-02-09 16:38:49 +03:00
var repo = new DatabaseRepository(new DatabaseWrapper(dbName));
2025-02-08 22:41:26 +03:00
2025-02-09 16:38:49 +03:00
var group = app.MapGroup(handle);
2025-02-08 22:41:26 +03:00
2025-02-09 16:58:07 +03:00
group.MapGet("/", async() => { return await repo.ListTables(); });
2025-02-09 16:38:49 +03:00
group.MapGet("/{tableName}", async(string tableName) =>
{ return await repo.ListColumns(tableName); });
group.MapGet("/{tableName}/{columnName}", async(string tableName, string columnName) =>
{ return await repo.ListColumnValues(tableName, columnName); } );
2025-02-08 22:41:26 +03:00
2025-02-09 16:38:49 +03:00
group.MapGet("/{tableName}/{id:int}", async(string tableName, int id) =>
{ return await repo.FetchValue(tableName, id); });
group.MapPost("/sqlcommand", async(HttpContext context) =>
{
using var reader = new StreamReader(context.Request.Body);
string command = await reader.ReadToEndAsync();
return await repo.ProcessCommand(command);
});
app.Run();
}
2025-02-08 22:41:26 +03:00
}
}