Compare commits

...

2 Commits

46 changed files with 1450 additions and 0 deletions

484
WretchedMachinesBackend/.gitignore vendored Normal file
View File

@ -0,0 +1,484 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from `dotnet new gitignore`
# dotenv files
.env
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
.idea
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# Vim temporary swap files
*.swp

View File

@ -0,0 +1,14 @@
namespace Customers.Api.Contracts.Data;
public class CustomerDto
{
public string Id { get; init; } = default!;
public string Username { get; init; } = default!;
public string FullName { get; init; } = default!;
public string Email { get; init; } = default!;
public DateTime DateOfBirth { get; init; }
}

View File

@ -0,0 +1,16 @@
namespace Users.Api.Contracts.Data;
public class UserDto
{
public string Id { get; init; } = default!;
public string Username { get; init; } = default!;
public string Email { get; init; } = default!;
public byte[] PasswordHash { get; init; } = default!;
public DateTime Created { get; init; }
public DateTime Updated { get; init; }
}

View File

@ -0,0 +1,12 @@
namespace Customers.Api.Contracts.Requests;
public class CreateCustomerRequest
{
public string Username { get; init; } = default!;
public string FullName { get; init; } = default!;
public string Email { get; init; } = default!;
public DateTime DateOfBirth { get; init; }
}

View File

@ -0,0 +1,6 @@
namespace Customers.Api.Contracts.Requests;
public class DeleteCustomerRequest
{
public Guid Id { get; init; }
}

View File

@ -0,0 +1,6 @@
namespace Customers.Api.Contracts.Requests;
public class GetCustomerRequest
{
public Guid Id { get; init; }
}

View File

@ -0,0 +1,14 @@
namespace Customers.Api.Contracts.Requests;
public class UpdateCustomerRequest
{
public Guid Id { get; init; }
public string Username { get; init; } = default!;
public string FullName { get; init; } = default!;
public string Email { get; init; } = default!;
public DateTime DateOfBirth { get; init; }
}

View File

@ -0,0 +1,14 @@
namespace Customers.Api.Contracts.Responses;
public class CustomerResponse
{
public Guid Id { get; init; }
public string Username { get; init; } = default!;
public string FullName { get; init; } = default!;
public string Email { get; init; } = default!;
public DateTime DateOfBirth { get; init; }
}

View File

@ -0,0 +1,6 @@
namespace Customers.Api.Contracts.Responses;
public class GetAllCustomersResponse
{
public IEnumerable<CustomerResponse> Customers { get; init; } = Enumerable.Empty<CustomerResponse>();
}

View File

@ -0,0 +1,6 @@
namespace Customers.Api.Contracts.Responses;
public class ValidationFailureResponse
{
public List<string> Errors { get; init; } = new();
}

View File

@ -0,0 +1,24 @@
using Dapper;
namespace Customers.Api.Database;
public class DatabaseInitializer
{
private readonly IDbConnectionFactory _connectionFactory;
public DatabaseInitializer(IDbConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}
public async Task InitializeAsync()
{
using var connection = await _connectionFactory.CreateConnectionAsync();
await connection.ExecuteAsync(@"CREATE TABLE IF NOT EXISTS Customers (
Id CHAR(36) PRIMARY KEY,
Username TEXT NOT NULL,
FullName TEXT NOT NULL,
Email TEXT NOT NULL,
DateOfBirth TEXT NOT NULL)");
}
}

View File

@ -0,0 +1,26 @@
using System.Data;
using Microsoft.Data.Sqlite;
namespace Customers.Api.Database;
public interface IDbConnectionFactory
{
public Task<IDbConnection> CreateConnectionAsync();
}
public class SqliteConnectionFactory : IDbConnectionFactory
{
private readonly string _connectionString;
public SqliteConnectionFactory(string connectionString)
{
_connectionString = connectionString;
}
public async Task<IDbConnection> CreateConnectionAsync()
{
var connection = new SqliteConnection(_connectionString);
await connection.OpenAsync();
return connection;
}
}

View File

@ -0,0 +1,14 @@
using ValueOf;
namespace Customers.Api.Domain.Common;
public class CustomerId : ValueOf<Guid, CustomerId>
{
protected override void Validate()
{
if (Value == Guid.Empty)
{
throw new ArgumentException("Customer Id cannot be empty", nameof(CustomerId));
}
}
}

View File

@ -0,0 +1,20 @@
using FluentValidation;
using FluentValidation.Results;
using ValueOf;
namespace Customers.Api.Domain.Common;
public class DateOfBirth : ValueOf<DateOnly, DateOfBirth>
{
protected override void Validate()
{
if (Value > DateOnly.FromDateTime(DateTime.Now))
{
const string message = "Your date of birth cannot be in the future";
throw new ValidationException(message, new []
{
new ValidationFailure(nameof(DateOfBirth), message)
});
}
}
}

View File

@ -0,0 +1,25 @@
using System.Text.RegularExpressions;
using FluentValidation;
using FluentValidation.Results;
using ValueOf;
namespace Customers.Api.Domain.Common;
public class EmailAddress : ValueOf<string, EmailAddress>
{
private static readonly Regex EmailRegex =
new("^[\\w!#$%&*+/=?`{|}~^-]+(?:\\.[\\w!#$%&*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
protected override void Validate()
{
if (!EmailRegex.IsMatch(Value))
{
var message = $"{Value} is not a valid email address";
throw new ValidationException(message, new []
{
new ValidationFailure(nameof(EmailAddress), message)
});
}
}
}

View File

@ -0,0 +1,24 @@
using System.Text.RegularExpressions;
using FluentValidation;
using FluentValidation.Results;
using ValueOf;
namespace Customers.Api.Domain.Common;
public class FullName : ValueOf<string, FullName>
{
private static readonly Regex FullNameRegex =
new("^[a-z ,.'-]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
protected override void Validate()
{
if (!FullNameRegex.IsMatch(Value))
{
var message = $"{Value} is not a valid full name";
throw new ValidationException(message, new []
{
new ValidationFailure(nameof(FullName), message)
});
}
}
}

View File

@ -0,0 +1,24 @@
using System.Text.RegularExpressions;
using FluentValidation;
using FluentValidation.Results;
using ValueOf;
namespace Customers.Api.Domain.Common;
public class Username : ValueOf<string, Username>
{
private static readonly Regex UsernameRegex =
new("^[a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38}$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
protected override void Validate()
{
if (!UsernameRegex.IsMatch(Value))
{
var message = $"{Value} is not a valid username";
throw new ValidationException(message, new []
{
new ValidationFailure(nameof(Username), message)
});
}
}
}

View File

@ -0,0 +1,16 @@
using Customers.Api.Domain.Common;
namespace Customers.Api.Domain;
public class Customer
{
public CustomerId Id { get; init; } = CustomerId.From(Guid.NewGuid());
public Username Username { get; init; } = default!;
public FullName FullName { get; init; } = default!;
public EmailAddress Email { get; init; } = default!;
public DateOfBirth DateOfBirth { get; init; } = default!;
}

View File

@ -0,0 +1,30 @@
using Customers.Api.Contracts.Requests;
using Customers.Api.Contracts.Responses;
using Customers.Api.Mapping;
using Customers.Api.Services;
using FastEndpoints;
using Microsoft.AspNetCore.Authorization;
namespace Customers.Api.Endpoints;
[HttpPost("customers"), AllowAnonymous]
public class CreateCustomerEndpoint : Endpoint<CreateCustomerRequest, CustomerResponse>
{
private readonly ICustomerService _customerService;
public CreateCustomerEndpoint(ICustomerService customerService)
{
_customerService = customerService;
}
public override async Task HandleAsync(CreateCustomerRequest req, CancellationToken ct)
{
var customer = req.ToCustomer();
await _customerService.CreateAsync(customer);
var customerResponse = customer.ToCustomerResponse();
await SendCreatedAtAsync<GetCustomerEndpoint>(
new { Id = customer.Id.Value }, customerResponse, generateAbsoluteUrl: true, cancellation: ct);
}
}

View File

@ -0,0 +1,29 @@
using Customers.Api.Contracts.Requests;
using Customers.Api.Services;
using FastEndpoints;
using Microsoft.AspNetCore.Authorization;
namespace Customers.Api.Endpoints;
[HttpDelete("customers/{id:guid}"), AllowAnonymous]
public class DeleteCustomerEndpoint : Endpoint<DeleteCustomerRequest>
{
private readonly ICustomerService _customerService;
public DeleteCustomerEndpoint(ICustomerService customerService)
{
_customerService = customerService;
}
public override async Task HandleAsync(DeleteCustomerRequest req, CancellationToken ct)
{
var deleted = await _customerService.DeleteAsync(req.Id);
if (!deleted)
{
await SendNotFoundAsync(ct);
return;
}
await SendNoContentAsync(ct);
}
}

View File

@ -0,0 +1,25 @@
using Customers.Api.Contracts.Responses;
using Customers.Api.Mapping;
using Customers.Api.Services;
using FastEndpoints;
using Microsoft.AspNetCore.Authorization;
namespace Customers.Api.Endpoints;
[HttpGet("customers"), AllowAnonymous]
public class GetAllCustomersEndpoint : EndpointWithoutRequest<GetAllCustomersResponse>
{
private readonly ICustomerService _customerService;
public GetAllCustomersEndpoint(ICustomerService customerService)
{
_customerService = customerService;
}
public override async Task HandleAsync(CancellationToken ct)
{
var customers = await _customerService.GetAllAsync();
var customersResponse = customers.ToCustomersResponse();
await SendOkAsync(customersResponse, ct);
}
}

View File

@ -0,0 +1,33 @@
using Customers.Api.Contracts.Requests;
using Customers.Api.Contracts.Responses;
using Customers.Api.Mapping;
using Customers.Api.Services;
using FastEndpoints;
using Microsoft.AspNetCore.Authorization;
namespace Customers.Api.Endpoints;
[HttpGet("customers/{id:guid}"), AllowAnonymous]
public class GetCustomerEndpoint : Endpoint<GetCustomerRequest, CustomerResponse>
{
private readonly ICustomerService _customerService;
public GetCustomerEndpoint(ICustomerService customerService)
{
_customerService = customerService;
}
public override async Task HandleAsync(GetCustomerRequest req, CancellationToken ct)
{
var customer = await _customerService.GetAsync(req.Id);
if (customer is null)
{
await SendNotFoundAsync(ct);
return;
}
var customerResponse = customer.ToCustomerResponse();
await SendOkAsync(customerResponse, ct);
}
}

View File

@ -0,0 +1,36 @@
using Customers.Api.Contracts.Requests;
using Customers.Api.Contracts.Responses;
using Customers.Api.Mapping;
using Customers.Api.Services;
using FastEndpoints;
using Microsoft.AspNetCore.Authorization;
namespace Customers.Api.Endpoints;
[HttpPut("customers/{id:guid}"), AllowAnonymous]
public class UpdateCustomerEndpoint : Endpoint<UpdateCustomerRequest, CustomerResponse>
{
private readonly ICustomerService _customerService;
public UpdateCustomerEndpoint(ICustomerService customerService)
{
_customerService = customerService;
}
public override async Task HandleAsync(UpdateCustomerRequest req, CancellationToken ct)
{
var existingCustomer = await _customerService.GetAsync(req.Id);
if (existingCustomer is null)
{
await SendNotFoundAsync(ct);
return;
}
var customer = req.ToCustomer();
await _customerService.UpdateAsync(customer);
var customerResponse = customer.ToCustomerResponse();
await SendOkAsync(customerResponse, ct);
}
}

View File

@ -0,0 +1,32 @@
using Customers.Api.Contracts.Requests;
using Customers.Api.Domain;
using Customers.Api.Domain.Common;
namespace Customers.Api.Mapping;
public static class ApiContractToDomainMapper
{
public static Customer ToCustomer(this CreateCustomerRequest request)
{
return new Customer
{
Id = CustomerId.From(Guid.NewGuid()),
Email = EmailAddress.From(request.Email),
Username = Username.From(request.Username),
FullName = FullName.From(request.FullName),
DateOfBirth = DateOfBirth.From(DateOnly.FromDateTime(request.DateOfBirth))
};
}
public static Customer ToCustomer(this UpdateCustomerRequest request)
{
return new Customer
{
Id = CustomerId.From(request.Id),
Email = EmailAddress.From(request.Email),
Username = Username.From(request.Username),
FullName = FullName.From(request.FullName),
DateOfBirth = DateOfBirth.From(DateOnly.FromDateTime(request.DateOfBirth))
};
}
}

View File

@ -0,0 +1,34 @@
using Customers.Api.Contracts.Responses;
using Customers.Api.Domain;
namespace Customers.Api.Mapping;
public static class DomainToApiContractMapper
{
public static CustomerResponse ToCustomerResponse(this Customer customer)
{
return new CustomerResponse
{
Id = customer.Id.Value,
Email = customer.Email.Value,
Username = customer.Username.Value,
FullName = customer.FullName.Value,
DateOfBirth = customer.DateOfBirth.Value.ToDateTime(TimeOnly.MinValue)
};
}
public static GetAllCustomersResponse ToCustomersResponse(this IEnumerable<Customer> customers)
{
return new GetAllCustomersResponse
{
Customers = customers.Select(x => new CustomerResponse
{
Id = x.Id.Value,
Email = x.Email.Value,
Username = x.Username.Value,
FullName = x.FullName.Value,
DateOfBirth = x.DateOfBirth.Value.ToDateTime(TimeOnly.MinValue)
})
};
}
}

View File

@ -0,0 +1,19 @@
using Customers.Api.Contracts.Data;
using Customers.Api.Domain;
namespace Customers.Api.Mapping;
public static class DomainToDtoMapper
{
public static CustomerDto ToCustomerDto(this Customer customer)
{
return new CustomerDto
{
Id = customer.Id.Value.ToString(),
Email = customer.Email.Value,
Username = customer.Username.Value,
FullName = customer.FullName.Value,
DateOfBirth = customer.DateOfBirth.Value.ToDateTime(TimeOnly.MinValue)
};
}
}

View File

@ -0,0 +1,20 @@
using Customers.Api.Contracts.Data;
using Customers.Api.Domain;
using Customers.Api.Domain.Common;
namespace Customers.Api.Mapping;
public static class DtoToDomainMapper
{
public static Customer ToCustomer(this CustomerDto customerDto)
{
return new Customer
{
Id = CustomerId.From(Guid.Parse(customerDto.Id)),
Email = EmailAddress.From(customerDto.Email),
Username = Username.From(customerDto.Username),
FullName = FullName.From(customerDto.FullName),
DateOfBirth = DateOfBirth.From(DateOnly.FromDateTime(customerDto.DateOfBirth))
};
}
}

View File

@ -0,0 +1,44 @@
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

View File

@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:63472",
"sslPort": 44301
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5190",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7119;http://localhost:5190",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,56 @@
using Customers.Api.Contracts.Data;
using Customers.Api.Database;
using Dapper;
namespace Customers.Api.Repositories;
public class CustomerRepository : ICustomerRepository
{
private readonly IDbConnectionFactory _connectionFactory;
public CustomerRepository(IDbConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}
public async Task<bool> CreateAsync(CustomerDto customer)
{
using var connection = await _connectionFactory.CreateConnectionAsync();
var result = await connection.ExecuteAsync(
@"INSERT INTO Customers (Id, Username, FullName, Email, DateOfBirth)
VALUES (@Id, @Username, @FullName, @Email, @DateOfBirth)",
customer);
return result > 0;
}
public async Task<CustomerDto?> GetAsync(Guid id)
{
using var connection = await _connectionFactory.CreateConnectionAsync();
return await connection.QuerySingleOrDefaultAsync<CustomerDto>(
"SELECT * FROM Customers WHERE Id = @Id LIMIT 1", new { Id = id.ToString() });
}
public async Task<IEnumerable<CustomerDto>> GetAllAsync()
{
using var connection = await _connectionFactory.CreateConnectionAsync();
return await connection.QueryAsync<CustomerDto>("SELECT * FROM Customers");
}
public async Task<bool> UpdateAsync(CustomerDto customer)
{
using var connection = await _connectionFactory.CreateConnectionAsync();
var result = await connection.ExecuteAsync(
@"UPDATE Customers SET Username = @Username, FullName = @FullName, Email = @Email,
DateOfBirth = @DateOfBirth WHERE Id = @Id",
customer);
return result > 0;
}
public async Task<bool> DeleteAsync(Guid id)
{
using var connection = await _connectionFactory.CreateConnectionAsync();
var result = await connection.ExecuteAsync(@"DELETE FROM Customers WHERE Id = @Id",
new {Id = id.ToString()});
return result > 0;
}
}

View File

@ -0,0 +1,16 @@
using Customers.Api.Contracts.Data;
namespace Customers.Api.Repositories;
public interface ICustomerRepository
{
Task<bool> CreateAsync(CustomerDto customer);
Task<CustomerDto?> GetAsync(Guid id);
Task<IEnumerable<CustomerDto>> GetAllAsync();
Task<bool> UpdateAsync(CustomerDto customer);
Task<bool> DeleteAsync(Guid id);
}

View File

@ -0,0 +1,56 @@
using Customers.Api.Domain;
using Customers.Api.Mapping;
using Customers.Api.Repositories;
using FluentValidation;
using FluentValidation.Results;
namespace Customers.Api.Services;
public class CustomerService : ICustomerService
{
private readonly ICustomerRepository _customerRepository;
public CustomerService(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public async Task<bool> CreateAsync(Customer customer)
{
var existingUser = await _customerRepository.GetAsync(customer.Id.Value);
if (existingUser is not null)
{
var message = $"A user with id {customer.Id} already exists";
throw new ValidationException(message, new []
{
new ValidationFailure(nameof(Customer), message)
});
}
var customerDto = customer.ToCustomerDto();
return await _customerRepository.CreateAsync(customerDto);
}
public async Task<Customer?> GetAsync(Guid id)
{
var customerDto = await _customerRepository.GetAsync(id);
return customerDto?.ToCustomer();
}
public async Task<IEnumerable<Customer>> GetAllAsync()
{
var customerDtos = await _customerRepository.GetAllAsync();
return customerDtos.Select(x => x.ToCustomer());
}
public async Task<bool> UpdateAsync(Customer customer)
{
var customerDto = customer.ToCustomerDto();
return await _customerRepository.UpdateAsync(customerDto);
}
public async Task<bool> DeleteAsync(Guid id)
{
return await _customerRepository.DeleteAsync(id);
}
}

View File

@ -0,0 +1,16 @@
using Customers.Api.Domain;
namespace Customers.Api.Services;
public interface ICustomerService
{
Task<bool> CreateAsync(Customer customer);
Task<Customer?> GetAsync(Guid id);
Task<IEnumerable<Customer>> GetAllAsync();
Task<bool> UpdateAsync(Customer customer);
Task<bool> DeleteAsync(Guid id);
}

View File

@ -0,0 +1,16 @@
using Customers.Api.Contracts.Responses;
using Customers.Api.Endpoints;
using FastEndpoints;
namespace Customers.Api.Summaries;
public class CreateCustomerSummary : Summary<CreateCustomerEndpoint>
{
public CreateCustomerSummary()
{
Summary = "Creates a new customer in the system";
Description = "Creates a new customer in the system";
Response<CustomerResponse>(201, "Customer was successfully created");
Response<ValidationFailureResponse>(400, "The request did not pass validation checks");
}
}

View File

@ -0,0 +1,15 @@
using Customers.Api.Endpoints;
using FastEndpoints;
namespace Customers.Api.Summaries;
public class DeleteCustomerSummary : Summary<DeleteCustomerEndpoint>
{
public DeleteCustomerSummary()
{
Summary = "Deleted a customer the system";
Description = "Deleted a customer the system";
Response(204, "The customer was deleted successfully");
Response(404, "The customer was not found in the system");
}
}

View File

@ -0,0 +1,15 @@
using Customers.Api.Contracts.Responses;
using Customers.Api.Endpoints;
using FastEndpoints;
namespace Customers.Api.Summaries;
public class GetAllCustomersSummary : Summary<GetAllCustomersEndpoint>
{
public GetAllCustomersSummary()
{
Summary = "Returns all the customers in the system";
Description = "Returns all the customers in the system";
Response<GetAllCustomersResponse>(200, "All customers in the system are returned");
}
}

View File

@ -0,0 +1,16 @@
using Customers.Api.Contracts.Responses;
using Customers.Api.Endpoints;
using FastEndpoints;
namespace Customers.Api.Summaries;
public class GetCustomerSummary : Summary<GetCustomerEndpoint>
{
public GetCustomerSummary()
{
Summary = "Returns a single customer by id";
Description = "Returns a single customer by id";
Response<GetAllCustomersResponse>(200, "Successfully found and returned the customer");
Response(404, "The customer does not exist in the system");
}
}

View File

@ -0,0 +1,16 @@
using Customers.Api.Contracts.Responses;
using Customers.Api.Endpoints;
using FastEndpoints;
namespace Customers.Api.Summaries;
public class UpdateCustomerSummary : Summary<UpdateCustomerEndpoint>
{
public UpdateCustomerSummary()
{
Summary = "Updates an existing customer in the system";
Description = "Updates an existing customer in the system";
Response<CustomerResponse>(201, "Customer was successfully updated");
Response<ValidationFailureResponse>(400, "The request did not pass validation checks");
}
}

View File

@ -0,0 +1,15 @@
using Customers.Api.Contracts.Requests;
using FluentValidation;
namespace Customers.Api.Validation;
public class CreateCustomerRequestValidator : AbstractValidator<CreateCustomerRequest>
{
public CreateCustomerRequestValidator()
{
RuleFor(x => x.FullName).NotEmpty();
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Username).NotEmpty();
RuleFor(x => x.DateOfBirth).NotEmpty();
}
}

View File

@ -0,0 +1,15 @@
using Customers.Api.Contracts.Requests;
using FluentValidation;
namespace Customers.Api.Validation;
public class UpdateCustomerRequestValidator : AbstractValidator<UpdateCustomerRequest>
{
public UpdateCustomerRequestValidator()
{
RuleFor(x => x.FullName).NotEmpty();
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Username).NotEmpty();
RuleFor(x => x.DateOfBirth).NotEmpty();
}
}

View File

@ -0,0 +1,32 @@
using Customers.Api.Contracts.Responses;
using FluentValidation;
namespace Customers.Api.Validation;
public class ValidationExceptionMiddleware
{
private readonly RequestDelegate _request;
public ValidationExceptionMiddleware(RequestDelegate request)
{
_request = request;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _request(context);
}
catch (ValidationException exception)
{
context.Response.StatusCode = 400;
var messages = exception.Errors.Select(x => x.ErrorMessage).ToList();
var validationFailureResponse = new ValidationFailureResponse
{
Errors = messages
};
await context.Response.WriteAsJsonAsync(validationFailureResponse);
}
}
}

View File

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="FastEndpoints" Version="5.26.0" />
<PackageReference Include="FastEndpoints.Swagger" Version="5.26.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.6" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="ValueOf" Version="2.0.31" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DataAccess\DataAccess.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,6 @@
@WretchedMachinesBackend_HostAddress = http://localhost:5190
GET {{WretchedMachinesBackend_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WretchedMachinesBackend", "WretchedMachinesBackend.csproj", "{A9D8EB0B-C828-47D2-99ED-94ABF8BB3D75}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A9D8EB0B-C828-47D2-99ED-94ABF8BB3D75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9D8EB0B-C828-47D2-99ED-94ABF8BB3D75}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9D8EB0B-C828-47D2-99ED-94ABF8BB3D75}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9D8EB0B-C828-47D2-99ED-94ABF8BB3D75}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4B866C14-5893-473B-AD16-A48F3F277F01}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}