From f008c31c218deff4614a4b32b9564a1b87454488 Mon Sep 17 00:00:00 2001 From: Eero Holmala Date: Sun, 2 Jun 2024 09:48:39 +0300 Subject: [PATCH] Added upgraded clean-minimal-api template as WretchedMachinesBackend --- WretchedMachinesBackend/.gitignore | 484 ++++++++++++++++++ .../Contracts/Data/CustomerDto.cs | 14 + .../Requests/CreateCustomerRequest.cs | 12 + .../Requests/DeleteCustomerRequest.cs | 6 + .../Contracts/Requests/GetCustomerRequest.cs | 6 + .../Requests/UpdateCustomerRequest.cs | 14 + .../Contracts/Responses/CustomerResponse.cs | 14 + .../Responses/GetAllCustomersResponse.cs | 6 + .../Responses/ValidationFailureResponse.cs | 6 + .../Database/DatabaseInitializer.cs | 24 + .../Database/DbConnectionFactory.cs | 26 + .../Domain/Common/CustomerId.cs | 14 + .../Domain/Common/DateOfBirth.cs | 20 + .../Domain/Common/EmailAddress.cs | 25 + .../Domain/Common/FullName.cs | 24 + .../Domain/Common/Username.cs | 24 + WretchedMachinesBackend/Domain/Customer.cs | 16 + .../Endpoints/CreateCustomerEndpoint.cs | 30 ++ .../Endpoints/DeleteCustomerEndpoint.cs | 29 ++ .../Endpoints/GetAllCustomersEndpoint.cs | 25 + .../Endpoints/GetCustomerEndpoint.cs | 33 ++ .../Endpoints/UpdateCustomerEndpoint.cs | 36 ++ .../Mapping/ApiContractToDomainMapper.cs | 32 ++ .../Mapping/DomainToApiContractMapper.cs | 34 ++ .../Mapping/DomainToDtoMapper.cs | 19 + .../Mapping/DtoToDomainMapper.cs | 20 + WretchedMachinesBackend/Program.cs | 44 ++ .../Properties/launchSettings.json | 41 ++ .../Repositories/CustomerRepository.cs | 56 ++ .../Repositories/ICustomerRepository.cs | 16 + .../Services/CustomerService.cs | 56 ++ .../Services/ICustomerService.cs | 16 + .../Summaries/CreateCustomerSummary.cs | 16 + .../Summaries/DeleteCustomerSummary.cs | 15 + .../Summaries/GetAllCustomersSummary.cs | 15 + .../Summaries/GetCustomerSummary.cs | 16 + .../Summaries/UpdateCustomerSummary.cs | 16 + .../CreateCustomerRequestValidator.cs | 15 + .../UpdateCustomerRequestValidator.cs | 15 + .../ValidationExceptionMiddleware.cs | 32 ++ .../WretchedMachinesBackend.csproj | 24 + .../WretchedMachinesBackend.http | 6 + .../appsettings.Development.json | 8 + WretchedMachinesBackend/appsettings.json | 9 + 44 files changed, 1409 insertions(+) create mode 100644 WretchedMachinesBackend/.gitignore create mode 100644 WretchedMachinesBackend/Contracts/Data/CustomerDto.cs create mode 100644 WretchedMachinesBackend/Contracts/Requests/CreateCustomerRequest.cs create mode 100644 WretchedMachinesBackend/Contracts/Requests/DeleteCustomerRequest.cs create mode 100644 WretchedMachinesBackend/Contracts/Requests/GetCustomerRequest.cs create mode 100644 WretchedMachinesBackend/Contracts/Requests/UpdateCustomerRequest.cs create mode 100644 WretchedMachinesBackend/Contracts/Responses/CustomerResponse.cs create mode 100644 WretchedMachinesBackend/Contracts/Responses/GetAllCustomersResponse.cs create mode 100644 WretchedMachinesBackend/Contracts/Responses/ValidationFailureResponse.cs create mode 100644 WretchedMachinesBackend/Database/DatabaseInitializer.cs create mode 100644 WretchedMachinesBackend/Database/DbConnectionFactory.cs create mode 100644 WretchedMachinesBackend/Domain/Common/CustomerId.cs create mode 100644 WretchedMachinesBackend/Domain/Common/DateOfBirth.cs create mode 100644 WretchedMachinesBackend/Domain/Common/EmailAddress.cs create mode 100644 WretchedMachinesBackend/Domain/Common/FullName.cs create mode 100644 WretchedMachinesBackend/Domain/Common/Username.cs create mode 100644 WretchedMachinesBackend/Domain/Customer.cs create mode 100644 WretchedMachinesBackend/Endpoints/CreateCustomerEndpoint.cs create mode 100644 WretchedMachinesBackend/Endpoints/DeleteCustomerEndpoint.cs create mode 100644 WretchedMachinesBackend/Endpoints/GetAllCustomersEndpoint.cs create mode 100644 WretchedMachinesBackend/Endpoints/GetCustomerEndpoint.cs create mode 100644 WretchedMachinesBackend/Endpoints/UpdateCustomerEndpoint.cs create mode 100644 WretchedMachinesBackend/Mapping/ApiContractToDomainMapper.cs create mode 100644 WretchedMachinesBackend/Mapping/DomainToApiContractMapper.cs create mode 100644 WretchedMachinesBackend/Mapping/DomainToDtoMapper.cs create mode 100644 WretchedMachinesBackend/Mapping/DtoToDomainMapper.cs create mode 100644 WretchedMachinesBackend/Program.cs create mode 100644 WretchedMachinesBackend/Properties/launchSettings.json create mode 100644 WretchedMachinesBackend/Repositories/CustomerRepository.cs create mode 100644 WretchedMachinesBackend/Repositories/ICustomerRepository.cs create mode 100644 WretchedMachinesBackend/Services/CustomerService.cs create mode 100644 WretchedMachinesBackend/Services/ICustomerService.cs create mode 100644 WretchedMachinesBackend/Summaries/CreateCustomerSummary.cs create mode 100644 WretchedMachinesBackend/Summaries/DeleteCustomerSummary.cs create mode 100644 WretchedMachinesBackend/Summaries/GetAllCustomersSummary.cs create mode 100644 WretchedMachinesBackend/Summaries/GetCustomerSummary.cs create mode 100644 WretchedMachinesBackend/Summaries/UpdateCustomerSummary.cs create mode 100644 WretchedMachinesBackend/Validation/CreateCustomerRequestValidator.cs create mode 100644 WretchedMachinesBackend/Validation/UpdateCustomerRequestValidator.cs create mode 100644 WretchedMachinesBackend/Validation/ValidationExceptionMiddleware.cs create mode 100644 WretchedMachinesBackend/WretchedMachinesBackend.csproj create mode 100644 WretchedMachinesBackend/WretchedMachinesBackend.http create mode 100644 WretchedMachinesBackend/appsettings.Development.json create mode 100644 WretchedMachinesBackend/appsettings.json diff --git a/WretchedMachinesBackend/.gitignore b/WretchedMachinesBackend/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/WretchedMachinesBackend/.gitignore @@ -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 diff --git a/WretchedMachinesBackend/Contracts/Data/CustomerDto.cs b/WretchedMachinesBackend/Contracts/Data/CustomerDto.cs new file mode 100644 index 0000000..4e3afb4 --- /dev/null +++ b/WretchedMachinesBackend/Contracts/Data/CustomerDto.cs @@ -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; } +} diff --git a/WretchedMachinesBackend/Contracts/Requests/CreateCustomerRequest.cs b/WretchedMachinesBackend/Contracts/Requests/CreateCustomerRequest.cs new file mode 100644 index 0000000..6fa96f5 --- /dev/null +++ b/WretchedMachinesBackend/Contracts/Requests/CreateCustomerRequest.cs @@ -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; } +} diff --git a/WretchedMachinesBackend/Contracts/Requests/DeleteCustomerRequest.cs b/WretchedMachinesBackend/Contracts/Requests/DeleteCustomerRequest.cs new file mode 100644 index 0000000..410789a --- /dev/null +++ b/WretchedMachinesBackend/Contracts/Requests/DeleteCustomerRequest.cs @@ -0,0 +1,6 @@ +namespace Customers.Api.Contracts.Requests; + +public class DeleteCustomerRequest +{ + public Guid Id { get; init; } +} diff --git a/WretchedMachinesBackend/Contracts/Requests/GetCustomerRequest.cs b/WretchedMachinesBackend/Contracts/Requests/GetCustomerRequest.cs new file mode 100644 index 0000000..c66ce24 --- /dev/null +++ b/WretchedMachinesBackend/Contracts/Requests/GetCustomerRequest.cs @@ -0,0 +1,6 @@ +namespace Customers.Api.Contracts.Requests; + +public class GetCustomerRequest +{ + public Guid Id { get; init; } +} diff --git a/WretchedMachinesBackend/Contracts/Requests/UpdateCustomerRequest.cs b/WretchedMachinesBackend/Contracts/Requests/UpdateCustomerRequest.cs new file mode 100644 index 0000000..e19d733 --- /dev/null +++ b/WretchedMachinesBackend/Contracts/Requests/UpdateCustomerRequest.cs @@ -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; } +} diff --git a/WretchedMachinesBackend/Contracts/Responses/CustomerResponse.cs b/WretchedMachinesBackend/Contracts/Responses/CustomerResponse.cs new file mode 100644 index 0000000..53db312 --- /dev/null +++ b/WretchedMachinesBackend/Contracts/Responses/CustomerResponse.cs @@ -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; } +} diff --git a/WretchedMachinesBackend/Contracts/Responses/GetAllCustomersResponse.cs b/WretchedMachinesBackend/Contracts/Responses/GetAllCustomersResponse.cs new file mode 100644 index 0000000..dba46f2 --- /dev/null +++ b/WretchedMachinesBackend/Contracts/Responses/GetAllCustomersResponse.cs @@ -0,0 +1,6 @@ +namespace Customers.Api.Contracts.Responses; + +public class GetAllCustomersResponse +{ + public IEnumerable Customers { get; init; } = Enumerable.Empty(); +} diff --git a/WretchedMachinesBackend/Contracts/Responses/ValidationFailureResponse.cs b/WretchedMachinesBackend/Contracts/Responses/ValidationFailureResponse.cs new file mode 100644 index 0000000..7c3beae --- /dev/null +++ b/WretchedMachinesBackend/Contracts/Responses/ValidationFailureResponse.cs @@ -0,0 +1,6 @@ +namespace Customers.Api.Contracts.Responses; + +public class ValidationFailureResponse +{ + public List Errors { get; init; } = new(); +} diff --git a/WretchedMachinesBackend/Database/DatabaseInitializer.cs b/WretchedMachinesBackend/Database/DatabaseInitializer.cs new file mode 100644 index 0000000..c36c5fb --- /dev/null +++ b/WretchedMachinesBackend/Database/DatabaseInitializer.cs @@ -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)"); + } +} diff --git a/WretchedMachinesBackend/Database/DbConnectionFactory.cs b/WretchedMachinesBackend/Database/DbConnectionFactory.cs new file mode 100644 index 0000000..9e3c38e --- /dev/null +++ b/WretchedMachinesBackend/Database/DbConnectionFactory.cs @@ -0,0 +1,26 @@ +using System.Data; +using Microsoft.Data.Sqlite; + +namespace Customers.Api.Database; + +public interface IDbConnectionFactory +{ + public Task CreateConnectionAsync(); +} + +public class SqliteConnectionFactory : IDbConnectionFactory +{ + private readonly string _connectionString; + + public SqliteConnectionFactory(string connectionString) + { + _connectionString = connectionString; + } + + public async Task CreateConnectionAsync() + { + var connection = new SqliteConnection(_connectionString); + await connection.OpenAsync(); + return connection; + } +} diff --git a/WretchedMachinesBackend/Domain/Common/CustomerId.cs b/WretchedMachinesBackend/Domain/Common/CustomerId.cs new file mode 100644 index 0000000..1648330 --- /dev/null +++ b/WretchedMachinesBackend/Domain/Common/CustomerId.cs @@ -0,0 +1,14 @@ +using ValueOf; + +namespace Customers.Api.Domain.Common; + +public class CustomerId : ValueOf +{ + protected override void Validate() + { + if (Value == Guid.Empty) + { + throw new ArgumentException("Customer Id cannot be empty", nameof(CustomerId)); + } + } +} diff --git a/WretchedMachinesBackend/Domain/Common/DateOfBirth.cs b/WretchedMachinesBackend/Domain/Common/DateOfBirth.cs new file mode 100644 index 0000000..5dc5a6d --- /dev/null +++ b/WretchedMachinesBackend/Domain/Common/DateOfBirth.cs @@ -0,0 +1,20 @@ +using FluentValidation; +using FluentValidation.Results; +using ValueOf; + +namespace Customers.Api.Domain.Common; + +public class DateOfBirth : ValueOf +{ + 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) + }); + } + } +} diff --git a/WretchedMachinesBackend/Domain/Common/EmailAddress.cs b/WretchedMachinesBackend/Domain/Common/EmailAddress.cs new file mode 100644 index 0000000..8b5f297 --- /dev/null +++ b/WretchedMachinesBackend/Domain/Common/EmailAddress.cs @@ -0,0 +1,25 @@ +using System.Text.RegularExpressions; +using FluentValidation; +using FluentValidation.Results; +using ValueOf; + +namespace Customers.Api.Domain.Common; + +public class EmailAddress : ValueOf +{ + 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) + }); + } + } +} diff --git a/WretchedMachinesBackend/Domain/Common/FullName.cs b/WretchedMachinesBackend/Domain/Common/FullName.cs new file mode 100644 index 0000000..cf2e4b9 --- /dev/null +++ b/WretchedMachinesBackend/Domain/Common/FullName.cs @@ -0,0 +1,24 @@ +using System.Text.RegularExpressions; +using FluentValidation; +using FluentValidation.Results; +using ValueOf; + +namespace Customers.Api.Domain.Common; + +public class FullName : ValueOf +{ + 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) + }); + } + } +} diff --git a/WretchedMachinesBackend/Domain/Common/Username.cs b/WretchedMachinesBackend/Domain/Common/Username.cs new file mode 100644 index 0000000..6f27543 --- /dev/null +++ b/WretchedMachinesBackend/Domain/Common/Username.cs @@ -0,0 +1,24 @@ +using System.Text.RegularExpressions; +using FluentValidation; +using FluentValidation.Results; +using ValueOf; + +namespace Customers.Api.Domain.Common; + +public class Username : ValueOf +{ + 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) + }); + } + } +} diff --git a/WretchedMachinesBackend/Domain/Customer.cs b/WretchedMachinesBackend/Domain/Customer.cs new file mode 100644 index 0000000..65b583c --- /dev/null +++ b/WretchedMachinesBackend/Domain/Customer.cs @@ -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!; +} diff --git a/WretchedMachinesBackend/Endpoints/CreateCustomerEndpoint.cs b/WretchedMachinesBackend/Endpoints/CreateCustomerEndpoint.cs new file mode 100644 index 0000000..5e15630 --- /dev/null +++ b/WretchedMachinesBackend/Endpoints/CreateCustomerEndpoint.cs @@ -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 +{ + 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( + new { Id = customer.Id.Value }, customerResponse, generateAbsoluteUrl: true, cancellation: ct); + } +} diff --git a/WretchedMachinesBackend/Endpoints/DeleteCustomerEndpoint.cs b/WretchedMachinesBackend/Endpoints/DeleteCustomerEndpoint.cs new file mode 100644 index 0000000..26865b7 --- /dev/null +++ b/WretchedMachinesBackend/Endpoints/DeleteCustomerEndpoint.cs @@ -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 +{ + 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); + } +} diff --git a/WretchedMachinesBackend/Endpoints/GetAllCustomersEndpoint.cs b/WretchedMachinesBackend/Endpoints/GetAllCustomersEndpoint.cs new file mode 100644 index 0000000..7af0710 --- /dev/null +++ b/WretchedMachinesBackend/Endpoints/GetAllCustomersEndpoint.cs @@ -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 +{ + 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); + } +} diff --git a/WretchedMachinesBackend/Endpoints/GetCustomerEndpoint.cs b/WretchedMachinesBackend/Endpoints/GetCustomerEndpoint.cs new file mode 100644 index 0000000..086a834 --- /dev/null +++ b/WretchedMachinesBackend/Endpoints/GetCustomerEndpoint.cs @@ -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 +{ + 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); + } +} diff --git a/WretchedMachinesBackend/Endpoints/UpdateCustomerEndpoint.cs b/WretchedMachinesBackend/Endpoints/UpdateCustomerEndpoint.cs new file mode 100644 index 0000000..c6b9a30 --- /dev/null +++ b/WretchedMachinesBackend/Endpoints/UpdateCustomerEndpoint.cs @@ -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 +{ + 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); + } +} diff --git a/WretchedMachinesBackend/Mapping/ApiContractToDomainMapper.cs b/WretchedMachinesBackend/Mapping/ApiContractToDomainMapper.cs new file mode 100644 index 0000000..c548ec1 --- /dev/null +++ b/WretchedMachinesBackend/Mapping/ApiContractToDomainMapper.cs @@ -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)) + }; + } +} diff --git a/WretchedMachinesBackend/Mapping/DomainToApiContractMapper.cs b/WretchedMachinesBackend/Mapping/DomainToApiContractMapper.cs new file mode 100644 index 0000000..4f35d01 --- /dev/null +++ b/WretchedMachinesBackend/Mapping/DomainToApiContractMapper.cs @@ -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 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) + }) + }; + } +} diff --git a/WretchedMachinesBackend/Mapping/DomainToDtoMapper.cs b/WretchedMachinesBackend/Mapping/DomainToDtoMapper.cs new file mode 100644 index 0000000..96ef370 --- /dev/null +++ b/WretchedMachinesBackend/Mapping/DomainToDtoMapper.cs @@ -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) + }; + } +} diff --git a/WretchedMachinesBackend/Mapping/DtoToDomainMapper.cs b/WretchedMachinesBackend/Mapping/DtoToDomainMapper.cs new file mode 100644 index 0000000..aa7a1e5 --- /dev/null +++ b/WretchedMachinesBackend/Mapping/DtoToDomainMapper.cs @@ -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)) + }; + } +} diff --git a/WretchedMachinesBackend/Program.cs b/WretchedMachinesBackend/Program.cs new file mode 100644 index 0000000..00ff539 --- /dev/null +++ b/WretchedMachinesBackend/Program.cs @@ -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); +} diff --git a/WretchedMachinesBackend/Properties/launchSettings.json b/WretchedMachinesBackend/Properties/launchSettings.json new file mode 100644 index 0000000..b991e6e --- /dev/null +++ b/WretchedMachinesBackend/Properties/launchSettings.json @@ -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" + } + } + } +} diff --git a/WretchedMachinesBackend/Repositories/CustomerRepository.cs b/WretchedMachinesBackend/Repositories/CustomerRepository.cs new file mode 100644 index 0000000..47f2852 --- /dev/null +++ b/WretchedMachinesBackend/Repositories/CustomerRepository.cs @@ -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 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 GetAsync(Guid id) + { + using var connection = await _connectionFactory.CreateConnectionAsync(); + return await connection.QuerySingleOrDefaultAsync( + "SELECT * FROM Customers WHERE Id = @Id LIMIT 1", new { Id = id.ToString() }); + } + + public async Task> GetAllAsync() + { + using var connection = await _connectionFactory.CreateConnectionAsync(); + return await connection.QueryAsync("SELECT * FROM Customers"); + } + + public async Task 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 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; + } +} diff --git a/WretchedMachinesBackend/Repositories/ICustomerRepository.cs b/WretchedMachinesBackend/Repositories/ICustomerRepository.cs new file mode 100644 index 0000000..2ad6840 --- /dev/null +++ b/WretchedMachinesBackend/Repositories/ICustomerRepository.cs @@ -0,0 +1,16 @@ +using Customers.Api.Contracts.Data; + +namespace Customers.Api.Repositories; + +public interface ICustomerRepository +{ + Task CreateAsync(CustomerDto customer); + + Task GetAsync(Guid id); + + Task> GetAllAsync(); + + Task UpdateAsync(CustomerDto customer); + + Task DeleteAsync(Guid id); +} diff --git a/WretchedMachinesBackend/Services/CustomerService.cs b/WretchedMachinesBackend/Services/CustomerService.cs new file mode 100644 index 0000000..090ef4b --- /dev/null +++ b/WretchedMachinesBackend/Services/CustomerService.cs @@ -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 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 GetAsync(Guid id) + { + var customerDto = await _customerRepository.GetAsync(id); + return customerDto?.ToCustomer(); + } + + public async Task> GetAllAsync() + { + var customerDtos = await _customerRepository.GetAllAsync(); + return customerDtos.Select(x => x.ToCustomer()); + } + + public async Task UpdateAsync(Customer customer) + { + var customerDto = customer.ToCustomerDto(); + return await _customerRepository.UpdateAsync(customerDto); + } + + public async Task DeleteAsync(Guid id) + { + return await _customerRepository.DeleteAsync(id); + } +} diff --git a/WretchedMachinesBackend/Services/ICustomerService.cs b/WretchedMachinesBackend/Services/ICustomerService.cs new file mode 100644 index 0000000..77f382c --- /dev/null +++ b/WretchedMachinesBackend/Services/ICustomerService.cs @@ -0,0 +1,16 @@ +using Customers.Api.Domain; + +namespace Customers.Api.Services; + +public interface ICustomerService +{ + Task CreateAsync(Customer customer); + + Task GetAsync(Guid id); + + Task> GetAllAsync(); + + Task UpdateAsync(Customer customer); + + Task DeleteAsync(Guid id); +} diff --git a/WretchedMachinesBackend/Summaries/CreateCustomerSummary.cs b/WretchedMachinesBackend/Summaries/CreateCustomerSummary.cs new file mode 100644 index 0000000..0b92ef4 --- /dev/null +++ b/WretchedMachinesBackend/Summaries/CreateCustomerSummary.cs @@ -0,0 +1,16 @@ +using Customers.Api.Contracts.Responses; +using Customers.Api.Endpoints; +using FastEndpoints; + +namespace Customers.Api.Summaries; + +public class CreateCustomerSummary : Summary +{ + public CreateCustomerSummary() + { + Summary = "Creates a new customer in the system"; + Description = "Creates a new customer in the system"; + Response(201, "Customer was successfully created"); + Response(400, "The request did not pass validation checks"); + } +} diff --git a/WretchedMachinesBackend/Summaries/DeleteCustomerSummary.cs b/WretchedMachinesBackend/Summaries/DeleteCustomerSummary.cs new file mode 100644 index 0000000..2dcf9d2 --- /dev/null +++ b/WretchedMachinesBackend/Summaries/DeleteCustomerSummary.cs @@ -0,0 +1,15 @@ +using Customers.Api.Endpoints; +using FastEndpoints; + +namespace Customers.Api.Summaries; + +public class DeleteCustomerSummary : Summary +{ + 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"); + } +} diff --git a/WretchedMachinesBackend/Summaries/GetAllCustomersSummary.cs b/WretchedMachinesBackend/Summaries/GetAllCustomersSummary.cs new file mode 100644 index 0000000..507b2a2 --- /dev/null +++ b/WretchedMachinesBackend/Summaries/GetAllCustomersSummary.cs @@ -0,0 +1,15 @@ +using Customers.Api.Contracts.Responses; +using Customers.Api.Endpoints; +using FastEndpoints; + +namespace Customers.Api.Summaries; + +public class GetAllCustomersSummary : Summary +{ + public GetAllCustomersSummary() + { + Summary = "Returns all the customers in the system"; + Description = "Returns all the customers in the system"; + Response(200, "All customers in the system are returned"); + } +} diff --git a/WretchedMachinesBackend/Summaries/GetCustomerSummary.cs b/WretchedMachinesBackend/Summaries/GetCustomerSummary.cs new file mode 100644 index 0000000..bd72d07 --- /dev/null +++ b/WretchedMachinesBackend/Summaries/GetCustomerSummary.cs @@ -0,0 +1,16 @@ +using Customers.Api.Contracts.Responses; +using Customers.Api.Endpoints; +using FastEndpoints; + +namespace Customers.Api.Summaries; + +public class GetCustomerSummary : Summary +{ + public GetCustomerSummary() + { + Summary = "Returns a single customer by id"; + Description = "Returns a single customer by id"; + Response(200, "Successfully found and returned the customer"); + Response(404, "The customer does not exist in the system"); + } +} diff --git a/WretchedMachinesBackend/Summaries/UpdateCustomerSummary.cs b/WretchedMachinesBackend/Summaries/UpdateCustomerSummary.cs new file mode 100644 index 0000000..68a5801 --- /dev/null +++ b/WretchedMachinesBackend/Summaries/UpdateCustomerSummary.cs @@ -0,0 +1,16 @@ +using Customers.Api.Contracts.Responses; +using Customers.Api.Endpoints; +using FastEndpoints; + +namespace Customers.Api.Summaries; + +public class UpdateCustomerSummary : Summary +{ + public UpdateCustomerSummary() + { + Summary = "Updates an existing customer in the system"; + Description = "Updates an existing customer in the system"; + Response(201, "Customer was successfully updated"); + Response(400, "The request did not pass validation checks"); + } +} diff --git a/WretchedMachinesBackend/Validation/CreateCustomerRequestValidator.cs b/WretchedMachinesBackend/Validation/CreateCustomerRequestValidator.cs new file mode 100644 index 0000000..7497cd6 --- /dev/null +++ b/WretchedMachinesBackend/Validation/CreateCustomerRequestValidator.cs @@ -0,0 +1,15 @@ +using Customers.Api.Contracts.Requests; +using FluentValidation; + +namespace Customers.Api.Validation; + +public class CreateCustomerRequestValidator : AbstractValidator +{ + public CreateCustomerRequestValidator() + { + RuleFor(x => x.FullName).NotEmpty(); + RuleFor(x => x.Email).NotEmpty(); + RuleFor(x => x.Username).NotEmpty(); + RuleFor(x => x.DateOfBirth).NotEmpty(); + } +} diff --git a/WretchedMachinesBackend/Validation/UpdateCustomerRequestValidator.cs b/WretchedMachinesBackend/Validation/UpdateCustomerRequestValidator.cs new file mode 100644 index 0000000..eb9d8d8 --- /dev/null +++ b/WretchedMachinesBackend/Validation/UpdateCustomerRequestValidator.cs @@ -0,0 +1,15 @@ +using Customers.Api.Contracts.Requests; +using FluentValidation; + +namespace Customers.Api.Validation; + +public class UpdateCustomerRequestValidator : AbstractValidator +{ + public UpdateCustomerRequestValidator() + { + RuleFor(x => x.FullName).NotEmpty(); + RuleFor(x => x.Email).NotEmpty(); + RuleFor(x => x.Username).NotEmpty(); + RuleFor(x => x.DateOfBirth).NotEmpty(); + } +} diff --git a/WretchedMachinesBackend/Validation/ValidationExceptionMiddleware.cs b/WretchedMachinesBackend/Validation/ValidationExceptionMiddleware.cs new file mode 100644 index 0000000..7184f02 --- /dev/null +++ b/WretchedMachinesBackend/Validation/ValidationExceptionMiddleware.cs @@ -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); + } + } +} diff --git a/WretchedMachinesBackend/WretchedMachinesBackend.csproj b/WretchedMachinesBackend/WretchedMachinesBackend.csproj new file mode 100644 index 0000000..b6b3899 --- /dev/null +++ b/WretchedMachinesBackend/WretchedMachinesBackend.csproj @@ -0,0 +1,24 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + + + diff --git a/WretchedMachinesBackend/WretchedMachinesBackend.http b/WretchedMachinesBackend/WretchedMachinesBackend.http new file mode 100644 index 0000000..8a83615 --- /dev/null +++ b/WretchedMachinesBackend/WretchedMachinesBackend.http @@ -0,0 +1,6 @@ +@WretchedMachinesBackend_HostAddress = http://localhost:5190 + +GET {{WretchedMachinesBackend_HostAddress}}/weatherforecast/ +Accept: application/json + +### diff --git a/WretchedMachinesBackend/appsettings.Development.json b/WretchedMachinesBackend/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/WretchedMachinesBackend/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/WretchedMachinesBackend/appsettings.json b/WretchedMachinesBackend/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/WretchedMachinesBackend/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}