-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
194 lines (163 loc) · 5.52 KB
/
Program.cs
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
using Microsoft.OpenApi.Models;
using Microsoft.EntityFrameworkCore;
using PokeLikeAPI.Data;
using PokeLikeAPI.Models;
using PokeLikeAPI.Dtos;
using BCrypt.Net;
using Microsoft.AspNetCore.Http.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Cors;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigins", policy =>
{
policy.WithOrigins(
"http://pokelike.s3-website.eu-west-2.amazonaws.com",
"http://localhost:5137"
)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddDbContextPool<PokeLikeDbContext>(opt =>
opt.UseNpgsql(builder.Configuration.GetConnectionString("PokeLikeDbContext") ??
Environment.GetEnvironmentVariable("DB_CONNECTION_STRING"))
.UseSnakeCaseNamingConvention());
if (builder.Environment.IsDevelopment())
{
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "PokeLike",
Description = "Keep track of what pokemon you think are cute 🥰",
Version = "v1"
});
});
}
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
var app = builder.Build();
async Task MigrateDatabase(IServiceProvider serviceProvider)
{
using var scope = serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<PokeLikeDbContext>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
var retryCount = 0;
const int maxRetries = 5;
while (retryCount < maxRetries)
{
try
{
await context.Database.MigrateAsync();
// If seeding is needed
await PokemonSeeder.SeedPokemonsAsync(context);
await ThemesSeeder.SeedThemesAsync(context);
logger.LogInformation("Database migration completed");
break;
}
catch (Exception ex)
{
retryCount++;
logger.LogError(ex, $"Migration attempt {retryCount} of {maxRetries} failed");
if (retryCount < maxRetries)
{
logger.LogInformation($"Waiting 5 seconds before retry...");
await Task.Delay(5000); // Wait 5 seconds before retry
}
else
{
throw; // If we've exhausted all retries, rethrow the exception
}
}
}
}
try
{
await MigrateDatabase(app.Services);
}
catch (Exception ex)
{
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
throw;
}
app.UseCors("AllowSpecificOrigins");
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "PokeLike V1");
});
}
app.MapGet("/", () => "Welcome to the PokeLike API!");
app.MapGet("/themes", async (PokeLikeDbContext db) =>
await db.Themes
.OrderBy(theme => theme.Id)
.ToListAsync());
app.MapGet("/pokemon", async (PokeLikeDbContext db) =>
await db.Pokemon
.OrderBy(poke => poke.Id)
.ToListAsync());
app.MapPost("/pokemon", async (PokeLikeDbContext db, Pokemon pokemon) =>
{
await db.Pokemon.AddAsync(pokemon);
await db.SaveChangesAsync();
return Results.Created($"/pokemon/{pokemon.Id}", pokemon);
});
app.MapPatch("/pokemon/{id}", async (PokeLikeDbContext db, int id, HttpRequest request) =>
{
var pokemon = await db.Pokemon.FindAsync(id);
if (pokemon == null)
{
return Results.NotFound();
}
var updateData = await request.ReadFromJsonAsync<UpdatePokemonDto>();
if (updateData == null || updateData.Likes == null)
{
return Results.BadRequest(new { message = "Invalid request payload." });
}
pokemon.Likes = updateData.Likes.Value;
await db.SaveChangesAsync();
return Results.Ok(pokemon);
});
app.MapGet("/collections", async (PokeLikeDbContext db) =>
await db.Collections
.Include(c => c.PokemonCollections)
.ThenInclude(pc => pc.Pokemon)
.OrderBy(collection => collection.Id)
.ToListAsync());
app.MapPost("/collections", async (PokeLikeDbContext db, CreateCollectionDto dto) =>
{
var passwordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
var collection = new Collection
{
Name = dto.Name,
ThemeId = dto.ThemeId.ToString(),
Likes = dto.Likes,
PasswordHash = passwordHash
};
await db.Collections.AddAsync(collection);
await db.SaveChangesAsync();
foreach (var pokemonId in dto.PokemonIds)
{
var pokemonCollection = new PokemonCollections
{
CollectionId = collection.Id,
Collection = collection,
PokemonId = pokemonId,
Pokemon = await db.Pokemon.FindAsync(pokemonId) ?? throw new InvalidOperationException($"Pokemon with ID {pokemonId} not found.")
};
await db.PokemonCollections.AddAsync(pokemonCollection);
}
await db.SaveChangesAsync();
return Results.Created($"/collections/{collection.Id}", collection);
});
app.MapGet("/health", () => Results.Ok("Healthy"));
app.Run();
// builder.Services.AddCors(options => { });