Files
chris 4ee8b9101d added a notes file for important running stuff
Create working for tenant and added in efcore and data layer
2026-04-02 09:05:53 +10:30

59 lines
2.1 KiB
C#

using Emergence.api.Models;
using Emergence.models;
using Emergence.services.Interface;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;
namespace Emergence.api.Controllers;
[ApiController]
[Route("[controller]")]
public class TenantController : ControllerBase
{
private readonly ITenantService _tenantService;
public TenantController(ITenantService tenantService)
{
_tenantService = tenantService;
}
[HttpGet(Name = "GetTenants")]
public async Task<Results<Ok<IEnumerable<TenantModel>>, NotFound>> GetTenants()
{
var tenants = await _tenantService.GetAllAsync();
if (tenants is null)
{
return TypedResults.NotFound();
}
return TypedResults.Ok(tenants);
}
[HttpGet("{id}", Name = "GetTenantById")]
public async Task<Results<Ok<TenantModel>, NotFound, BadRequest>> GetTenantById(Guid id)
{
var tenant = await _tenantService.GetByIdAsync(id);
if (tenant is null)
{
return TypedResults.NotFound();
}
return TypedResults.Ok(tenant);
}
[HttpPost(Name = "CreateTenant")]
public async Task<Results<Created<TenantModel>, Conflict<ErrorDetailResults>, BadRequest<ValidationProblemResult>, UnprocessableEntity<ErrorDetailResults>>> Create(TenantModel tenant)
{
if (tenant == null || !ModelState.IsValid)
return TypedResults.BadRequest<ValidationProblemResult>(new ValidationProblemResult(ModelState));
if (tenant.Id.HasValue && tenant.Id.Value != Guid.Empty && _tenantService.GetByIdAsync(tenant.Id.Value).Result != null)
return TypedResults.Conflict(new ErrorDetailResults($"Tenant already exists", $"Tenant with the id: {tenant.Id} already exists"));
var newTenant = await _tenantService.CreateAsync(tenant);
if (newTenant is null)
{
return TypedResults.UnprocessableEntity(new ErrorDetailResults($"Tenant failed to create", $"The new tenant failed to create. Please try again."));
}
return TypedResults.Created($"/tenant/{newTenant.Id}", newTenant);
}
}