finished implementing characters endpoints

This commit is contained in:
StevanFreeborn
2022-06-24 11:35:33 -05:00
parent 9bc24949b7
commit 15eea06073
7 changed files with 157 additions and 89 deletions
@@ -7,7 +7,7 @@ namespace server.Controllers.v1
{ {
[ApiController] [ApiController]
[ApiVersion("1.0")] [ApiVersion("1.0")]
[Route("/api/episodes")] [Route("/api/characters")]
[Produces("application/json")] [Produces("application/json")]
public class CharactersController : ControllerBase public class CharactersController : ControllerBase
{ {
+12
View File
@@ -12,6 +12,12 @@ namespace server.Models
[BsonRepresentation(BsonType.ObjectId)] [BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; } public string? Id { get; set; }
/// <summary>
/// The character's full name.
/// </summary>
[BsonElement("fullName")]
public string FullName => $"{FirstName} {LastName}";
/// <summary> /// <summary>
/// The character's first name. /// The character's first name.
/// </summary> /// </summary>
@@ -24,6 +30,12 @@ namespace server.Models
[BsonElement("lastName")] [BsonElement("lastName")]
public string? LastName { get; set; } public string? LastName { get; set; }
/// <summary>
/// The full name of the actor who potrayed the character.
/// </summary>
[BsonElement("actorFullName")]
public string ActorFullName => $"{ActorFirstName} {ActorLastName}";
/// <summary> /// <summary>
/// The first name of the actor who potrayed the character. /// The first name of the actor who potrayed the character.
/// </summary> /// </summary>
+14 -1
View File
@@ -8,6 +8,19 @@ namespace server.Models
{ {
public class CharacterFilter public class CharacterFilter
{ {
// TODO: Build character filter model /// <summary>
/// Used to filter characters by their name.
/// </summary>
public string? Name { get; set; } = null;
/// <summary>
/// Used to filter characters by the actor's name.
/// </summary>
public string? ActorName { get; set; } = null;
/// <summary>
/// Used to filter characters by a season.
/// </summary>
public int? Season { get; set; } = null;
} }
} }
@@ -1,19 +1,59 @@
using server.Models; using server.Models;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
namespace server.Persistence.Repositories namespace server.Persistence.Repositories
{ {
public class CharacterRepository : ICharacterRepository public class CharacterRepository : ICharacterRepository
{ {
// TODO: Implement getcharactersasync private readonly IDbContext _context;
public Task<List<Character>> GetCharactersAsync(CharacterFilter filter)
public CharacterRepository(IDbContext context)
{ {
throw new NotImplementedException(); _context = context;
} }
// TODO: Implement getcharacterbyidasync public async Task<List<Character>> GetCharactersAsync(CharacterFilter filter)
public Task<Character> GetCharacterByIdAsync(string id)
{ {
throw new NotImplementedException(); try
{
var query = _context.Characters.AsQueryable();
if (filter?.Name != null)
{
query = query.Where(character => character.FullName.ToLower().Contains(filter.Name.ToLower()));
}
if (filter?.ActorName != null)
{
query = query.Where(character => character.ActorFullName.ToLower().Contains(filter.ActorName.ToLower()));
}
if (filter?.Season != null)
{
query = query.Where(character => character.Seasons.Any(season => season == filter.Season));
}
return await query.ToListAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public async Task<Character> GetCharacterByIdAsync(string id)
{
try
{
return await _context.Characters.Find(character => character.Id == id).SingleOrDefaultAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
} }
} }
} }
+82 -79
View File
@@ -2,13 +2,13 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Versioning; using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using server.Options; using server.SwaggerOptions;
using server.Persistence; using server.Persistence;
using server.Persistence.Repositories; using server.Persistence.Repositories;
using server.Persistence.Seed; using server.Persistence.Seed;
using System.Reflection; using System.Reflection;
using AspNetCoreRateLimit; using AspNetCoreRateLimit;
using server.Options.Filters; using server.SwaggerOptions.Filters;
if (args.Length == 2 && args[0].ToLower() == "seed") if (args.Length == 2 && args[0].ToLower() == "seed")
{ {
@@ -34,99 +34,102 @@ if (args.Length == 2 && args[0].ToLower() == "seed")
await seeder.SeedCharactersAsync(); await seeder.SeedCharactersAsync();
} }
} }
else
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
builder.Services.Configure<IpRateLimitOptions>(
builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.Configure<IpRateLimitPolicies>(
builder.Configuration.GetSection("IpRateLimitPolicies"));
builder.Services.AddInMemoryRateLimiting();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
builder.Services.Configure<DatabaseSettings>(
builder.Configuration.GetSection("MongoDBSettings"));
builder.Services.AddSingleton<IDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<DatabaseSettings>>().Value);
builder.Services.AddSingleton<IDbContext, DbContext>();
builder.Services.AddScoped<ISeasonRepository, SeasonRepository>();
builder.Services.AddScoped<IEpisodeRepository, EpisodeRepository>();
builder.Services.AddScoped<IQuoteRepository, QuoteRepository>();
builder.Services.AddScoped<ICharacterRepository, CharacterRepository>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{ {
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath); var builder = WebApplication.CreateBuilder(args);
options.OperationFilter<ApiVersionOperationFilter>();
});
builder.Services.ConfigureOptions<ConfigureSwaggerOptions>(); builder.Services.AddMemoryCache();
builder.Services.AddApiVersioning(config => builder.Services.Configure<IpRateLimitOptions>(
{ builder.Configuration.GetSection("IpRateLimiting"));
config.DefaultApiVersion = new ApiVersion(1, 0);
config.AssumeDefaultVersionWhenUnspecified = true;
config.ReportApiVersions = true;
config.ApiVersionReader = new HeaderApiVersionReader("x-api-version");
});
builder.Services.AddVersionedApiExplorer(config => builder.Services.Configure<IpRateLimitPolicies>(
{ builder.Configuration.GetSection("IpRateLimitPolicies"));
config.GroupNameFormat = "'v'VVV";
});
var app = builder.Build(); builder.Services.AddInMemoryRateLimiting();
app.UseStaticFiles(); builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
app.UseSwagger(options => builder.Services.Configure<DatabaseSettings>(
{ builder.Configuration.GetSection("MongoDBSettings"));
options.RouteTemplate = "/{documentName}/docs.json";
});
app.UseSwaggerUI(options => builder.Services.AddSingleton<IDatabaseSettings>(sp =>
{ sp.GetRequiredService<IOptions<DatabaseSettings>>().Value);
var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
foreach (var description in provider.ApiVersionDescriptions) builder.Services.AddSingleton<IDbContext, DbContext>();
builder.Services.AddScoped<ISeasonRepository, SeasonRepository>();
builder.Services.AddScoped<IEpisodeRepository, EpisodeRepository>();
builder.Services.AddScoped<IQuoteRepository, QuoteRepository>();
builder.Services.AddScoped<ICharacterRepository, CharacterRepository>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{ {
var url = $"/{description.GroupName}/docs.json"; var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var name = $"criminalmindsapi v{description.ApiVersion}"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.RoutePrefix = String.Empty; options.IncludeXmlComments(xmlPath);
options.SwaggerEndpoint(url, name); options.OperationFilter<ApiVersionOperationFilter>();
options.EnableTryItOutByDefault(); });
options.DisplayRequestDuration();
options.DocumentTitle = "criminalmindsapi";
}
});
app.UseHttpsRedirection(); builder.Services.ConfigureOptions<ConfigureSwaggerOptions>();
app.UseAuthorization(); builder.Services.AddApiVersioning(config =>
{
config.DefaultApiVersion = new ApiVersion(1, 0);
config.AssumeDefaultVersionWhenUnspecified = true;
config.ReportApiVersions = true;
config.ApiVersionReader = new HeaderApiVersionReader("x-api-version");
});
app.MapControllers(); builder.Services.AddVersionedApiExplorer(config =>
{
config.GroupNameFormat = "'v'VVV";
});
app.UseIpRateLimiting(); var app = builder.Build();
app.Run(); app.UseStaticFiles();
app.UseSwagger(options =>
{
options.RouteTemplate = "/{documentName}/docs.json";
});
app.UseSwaggerUI(options =>
{
var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
foreach (var description in provider.ApiVersionDescriptions)
{
var url = $"/{description.GroupName}/docs.json";
var name = $"criminalmindsapi v{description.ApiVersion}";
options.RoutePrefix = String.Empty;
options.SwaggerEndpoint(url, name);
options.EnableTryItOutByDefault();
options.DisplayRequestDuration();
options.DocumentTitle = "criminalmindsapi";
}
});
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseIpRateLimiting();
app.Run();
}
@@ -3,7 +3,7 @@ using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen; using Swashbuckle.AspNetCore.SwaggerGen;
namespace server.Options namespace server.SwaggerOptions
{ {
public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions> public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions>
{ {
@@ -2,7 +2,7 @@
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen; using Swashbuckle.AspNetCore.SwaggerGen;
namespace server.Options.Filters namespace server.SwaggerOptions.Filters
{ {
public class ApiVersionOperationFilter : IOperationFilter public class ApiVersionOperationFilter : IOperationFilter
{ {