-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
79 lines (61 loc) · 2.48 KB
/
Program.cs
File metadata and controls
79 lines (61 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using DbUp;
using MyServer.Models;
using MyServer.Repositories;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
var connectionString = builder.Configuration.GetConnectionString("Postgres")
?? throw new InvalidOperationException("Connection string 'Postgres' not found.");
builder.Services.AddSingleton<IContactRepository>(_ => new ContactRepository(connectionString));
var app = builder.Build();
// Run migrations on startup
var upgrader = DeployChanges.To
.PostgresqlDatabase(connectionString)
.WithScriptsEmbeddedInAssembly(typeof(Program).Assembly)
.WithTransactionPerScript()
.LogToConsole()
.Build();
var result = upgrader.PerformUpgrade();
if (!result.Successful)
throw new Exception("Database migration failed", result.Error);
if (app.Environment.IsDevelopment())
app.MapOpenApi();
// app.UseHttpsRedirection();
// GET /contacts
app.MapGet("/contacts", async (IContactRepository repo) =>
Results.Ok(await repo.GetAllAsync()));
// GET /contacts/search?q=
app.MapGet("/contacts/search", async (string q, IContactRepository repo) =>
Results.Ok(await repo.SearchAsync(q)));
// GET /contacts/{id}
app.MapGet("/contacts/{id:int}", async (int id, IContactRepository repo) =>
{
var contact = await repo.GetByIdAsync(id);
return contact is null ? Results.NotFound() : Results.Ok(contact);
});
// POST /contacts
app.MapPost("/contacts", async (ContactRequest request, IContactRepository repo) =>
{
var created = await repo.CreateAsync(request);
Console.WriteLine(value: $"Created contact with ID {created.Id}");
return Results.Created($"/contacts/{created.Id}", created);
});
// PUT /contacts/{id}
app.MapPut("/contacts/{id:int}", async (int id, ContactRequest request, IContactRepository repo) =>
{
var updated = await repo.UpdateAsync(id, request);
return updated is null ? Results.NotFound() : Results.Ok(updated);
});
// DELETE /contacts/{id}
app.MapDelete("/contacts/{id:int}", async (int id, IContactRepository repo) =>
{
var deleted = await repo.DeleteAsync(id);
return deleted ? Results.NoContent() : Results.NotFound();
});
// POST /contacts/upsert?id= (calls the upsert_contact stored procedure)
// Omit ?id to insert; provide ?id to update an existing contact (falls back to insert if not found)
app.MapPost("/contacts/upsert", async (ContactRequest request, IContactRepository repo, int? id = null) =>
{
var contact = await repo.UpsertAsync(id, request);
return Results.Ok(contact);
});
app.Run();