insight/src/Api/Insight.Api/Controllers/InventoryController.cs

68 lines
2.2 KiB
C#
Raw Normal View History

2023-09-21 18:58:32 +02:00
using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Models;
2023-12-18 16:31:00 +01:00
using Insight.Infrastructure.Web;
2023-09-21 18:58:32 +02:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
2023-09-22 22:16:56 +02:00
namespace Insight.Api.Controllers;
[ApiController, Route("api/inventory")]
2023-12-18 16:31:00 +01:00
public class InventoryController(IServiceScopeFactory scopeFactory) : ControllerBase
2023-09-21 18:58:32 +02:00
{
2023-12-18 16:31:00 +01:00
private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
[HttpGet, Authorize]
public async Task<IActionResult> Get([FromQuery] HostApplicationEntity request, [FromQuery] PagedDataRequest meta, CancellationToken cancellationToken)
{
2023-12-18 16:31:00 +01:00
using var scope = _scopeFactory.CreateScope();
var collection = scope.ServiceProvider.GetRequiredService<IMongoDatabase>().HostApplication();
2023-09-22 22:16:56 +02:00
try
2023-09-21 18:58:32 +02:00
{
2023-09-22 22:16:56 +02:00
var filter = Builders<HostApplicationEntity>.Filter.Empty;
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
if (request.Id is not null)
filter &= Builders<HostApplicationEntity>.Filter.Eq(p => p.Id, request.Id);
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
if (request.Host is not null)
filter &= Builders<HostApplicationEntity>.Filter.Eq(p => p.Host, request.Host);
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
if (request.Name is not null)
filter &= Builders<HostApplicationEntity>.Filter.Regex(p => p.Name, new BsonRegularExpression(new Regex(request.Name, RegexOptions.IgnoreCase)));
2023-09-21 18:58:32 +02:00
2023-12-18 16:31:00 +01:00
var result = await collection.GetPagedAsync(
2023-09-22 22:16:56 +02:00
filter: filter,
offset: meta.Offset,
limit: meta.Limit,
request: Request,
response: Response,
cancellationToken: cancellationToken).ConfigureAwait(false);
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
return Ok(result);
2023-09-21 18:58:32 +02:00
}
2023-09-22 22:16:56 +02:00
catch (UnauthorizedAccessException ex)
2023-09-21 18:58:32 +02:00
{
2023-09-22 22:16:56 +02:00
return Unauthorized(ex.ToString());
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
public class ApplicationRequest
{
[JsonPropertyName("id")]
public string? Id { get; set; }
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
[JsonPropertyName("host")]
public string? Host { get; set; }
[JsonPropertyName("name")]
public string? Name { get; set; }
2023-09-21 18:58:32 +02:00
}
}