├── .gitignore ├── LICENSE ├── README.md └── src ├── .dockerignore ├── Authentication ├── ClaimsPrincipalExtensions.cs ├── Endpoints │ ├── Login.cs │ └── Signup.cs └── Services │ └── Jwt.cs ├── Chirper.csproj ├── Chirper.sln ├── Comments └── Endpoints │ ├── CreateComment.cs │ ├── GetCommentReplies.cs │ ├── LikeComment.cs │ └── UnlikeComment.cs ├── Common └── Api │ ├── Extensions │ └── RouteHandlerBuilderValidationExtensions.cs │ ├── Filters │ ├── EnsureEntityExistsFilter.cs │ ├── EnsureUserOwnsEntityFilter.cs │ ├── RequestLoggingFilter.cs │ └── RequestValidationFilter.cs │ ├── IEndpoint.cs │ ├── Requests │ └── PagedRequest.cs │ └── Results │ ├── NotFoundProblem.cs │ └── ValidationError.cs ├── ConfigureApp.cs ├── ConfigureServices.cs ├── Data ├── AppDbContext.cs ├── Migrations │ ├── 20240715103609_Init.Designer.cs │ ├── 20240715103609_Init.cs │ └── AppDbContextModelSnapshot.cs └── Types │ ├── Comment.cs │ ├── IEntity.cs │ ├── Post.cs │ ├── PostLike.cs │ └── User.cs ├── Dockerfile ├── Endpoints.cs ├── Posts └── Endpoints │ ├── CreatePost.cs │ ├── DeletePost.cs │ ├── GetPostById.cs │ ├── GetPostComments.cs │ ├── GetPosts.cs │ ├── LikePost.cs │ ├── UnlikePost.cs │ └── UpdatePost.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Users └── Endpoints │ ├── FollowUser.cs │ ├── GetUserComments.cs │ ├── GetUserFollowers.cs │ ├── GetUserFollowing.cs │ ├── GetUserLikedComments.cs │ ├── GetUserLikedPosts.cs │ ├── GetUserPosts.cs │ └── UnfollowUser.cs └── appsettings.json /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Structured Minimal API 2 | An example on how to structure a minmal API using [Vertical Slice Architecture](https://www.jimmybogard.com/vertical-slice-architecture/) 3 | 4 | ## Video Walkthrough 5 | Prefer watching videos rather than reading the code? Check [this video out](https://www.youtube.com/watch?v=ZA2X1gaAhJk), it's a walkthrough of the solution and explains some concepts / reasoning 6 | 7 | ## What is Vertical Slice Architecture? 8 | Vertical slice architecture is an approach for organising your code into features/vertical slices rather than organising by technical conerns (e.g. Controllers, Models, Services etc). 9 | Each slice will contain all the code which fullfills a feature or use case inside the application. 10 | One of the main benefits of VSA is the ability to structure each feature/slice independently, so each feature/slice can be as simple or complicated as it needs to be. 11 | 12 | ## What does this API do? 13 | This is an API for Twitter/X like social media, where users can make text posts, like and comment on posts and follow other users. 14 | 15 | ## Some Important Design Decisions In This Project 16 | 1. Each `endpoint` will define their own `request`/`response` contract 17 | - I have found trying to resuse DTOs can be a pain as soon as an edge case requires the DTO to diverge from the common structure. Rather than dealing with that pain later, bite the bullet now and create a seperate `request`/`response` DTO. 18 | 2. Let **DATA BE DATA** 19 | - I'm not using [Domain Driven Design](https://martinfowler.com/bliki/DomainDrivenDesign.html), after using DDD on real world projects, I personally, don't like the approach (if it works for you, keep doing it, don't let me change that), I found I was always trying to search for the code that was actually doing the thing, or trying to figure out which *Domain object* the code belongs too rather than writing the code. 20 | - After experimenting with [Golang](https://go.dev/) I really like the approach of letting data just be simple `structs` and using methods/functions to operate over them. 21 | - So, in this project our `Data Types` will just be simple data buckets, no logic inside them, they are just there to represent our data. Some people call this an [Anemic Domain Model](https://martinfowler.com/bliki/AnemicDomainModel.html) 22 | 3. No `IRepository` abstraction over [EF Core](https://learn.microsoft.com/en-us/ef/core/) 23 | - Controversial, I know. My take is EF Core is already a pretty solid abstraction over a database and covers 99.9% of use cases. Some people say "What about unit testing?", I think you shouldn't be mocking **YOUR OWN** database, if you need to test something which is reading/writing to your database, you should be writing an [integration test](https://en.wikipedia.org/wiki/Integration_testing) 24 | - If EF Core isn't suitable for a specific feature/slice, we can use anything we want (e.g. [Dapper](https://github.com/DapperLib/Dapper)) as each feature/slice is independent. 25 | -------------------------------------------------------------------------------- /src/.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md 26 | !**/.gitignore 27 | !.git/HEAD 28 | !.git/config 29 | !.git/packed-refs 30 | !.git/refs/heads/** -------------------------------------------------------------------------------- /src/Authentication/ClaimsPrincipalExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace System.Security.Claims; 2 | 3 | public static class ClaimsPrincipalExtensions 4 | { 5 | public static int GetUserId(this ClaimsPrincipal claimsPrincipal) 6 | { 7 | if(!int.TryParse(claimsPrincipal.FindFirstValue(ClaimTypes.NameIdentifier), out var id)) 8 | { 9 | throw new InvalidOperationException("Invalid UserId"); 10 | } 11 | 12 | return id; 13 | } 14 | } -------------------------------------------------------------------------------- /src/Authentication/Endpoints/Login.cs: -------------------------------------------------------------------------------- 1 | using Chirper.Authentication.Services; 2 | 3 | namespace Chirper.Authentication.Endpoints; 4 | 5 | public class Login : IEndpoint 6 | { 7 | public static void Map(IEndpointRouteBuilder app) => app 8 | .MapPost("/login", Handle) 9 | .WithSummary("Logs in a user") 10 | .WithRequestValidation(); 11 | 12 | public record Request(string Username, string Password); 13 | public record Response(string Token); 14 | public class RequestValidator : AbstractValidator 15 | { 16 | public RequestValidator() 17 | { 18 | RuleFor(x => x.Username).NotEmpty(); 19 | RuleFor(x => x.Password).NotEmpty(); 20 | } 21 | } 22 | 23 | private static async Task, UnauthorizedHttpResult>> Handle(Request request, AppDbContext database, Jwt jwt, CancellationToken cancellationToken) 24 | { 25 | var user = await database.Users.SingleOrDefaultAsync(x => x.Username == request.Username && x.Password == request.Password, cancellationToken); 26 | 27 | if (user is null || user.Password != request.Password) 28 | { 29 | return TypedResults.Unauthorized(); 30 | } 31 | 32 | var token = jwt.GenerateToken(user); 33 | var response = new Response(token); 34 | return TypedResults.Ok(response); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Authentication/Endpoints/Signup.cs: -------------------------------------------------------------------------------- 1 | using Chirper.Authentication.Services; 2 | 3 | namespace Chirper.Authentication.Endpoints; 4 | 5 | public class Signup : IEndpoint 6 | { 7 | public static void Map(IEndpointRouteBuilder app) => app 8 | .MapPost("/signup", Handle) 9 | .WithSummary("Creates a new user account") 10 | .WithRequestValidation(); 11 | 12 | public record Request(string Username, string Password, string Name); 13 | public record Response(string Token); 14 | public class RequestValidator : AbstractValidator 15 | { 16 | public RequestValidator() 17 | { 18 | RuleFor(x => x.Username).NotEmpty(); 19 | RuleFor(x => x.Password).NotEmpty(); 20 | RuleFor(x => x.Name).NotEmpty(); 21 | } 22 | } 23 | 24 | private static async Task, ValidationError>> Handle(Request request, AppDbContext database, Jwt jwt, CancellationToken cancellationToken) 25 | { 26 | var isUsernameTaken = await database.Users 27 | .AnyAsync(x => x.Username == request.Username, cancellationToken); 28 | 29 | if (isUsernameTaken) 30 | { 31 | return new ValidationError("Username is already taken"); 32 | } 33 | 34 | var user = new User 35 | { 36 | Username = request.Username, 37 | Password = request.Password, 38 | DisplayName = request.Name 39 | }; 40 | await database.Users.AddAsync(user, cancellationToken); 41 | await database.SaveChangesAsync(cancellationToken); 42 | 43 | var token = jwt.GenerateToken(user); 44 | var response = new Response(token); 45 | return TypedResults.Ok(response); 46 | } 47 | } -------------------------------------------------------------------------------- /src/Authentication/Services/Jwt.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Options; 2 | using Microsoft.IdentityModel.Tokens; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.Text; 5 | 6 | namespace Chirper.Authentication.Services; 7 | 8 | public class JwtOptions 9 | { 10 | public required string Key { get; init; } 11 | } 12 | 13 | public class Jwt(IOptions options) 14 | { 15 | public string GenerateToken(User user) 16 | { 17 | var key = SecurityKey(options.Value.Key); 18 | var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature); 19 | 20 | var token = new JwtSecurityToken 21 | ( 22 | claims: [new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())], 23 | signingCredentials: new(key, SecurityAlgorithms.HmacSha256Signature), 24 | expires: DateTime.UtcNow.AddYears(1) 25 | ); 26 | 27 | return new JwtSecurityTokenHandler().WriteToken(token); 28 | } 29 | 30 | public static SymmetricSecurityKey SecurityKey(string key) => new(Encoding.ASCII.GetBytes(key)); 31 | } -------------------------------------------------------------------------------- /src/Chirper.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | c279879d-f8b7-41a2-a1cc-5024f759d4c8 8 | Linux 9 | . 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | all 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/Chirper.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34511.84 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Chirper", "Chirper.csproj", "{9A24ADE8-C8B3-4384-9B80-FD47709C69A6}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {9A24ADE8-C8B3-4384-9B80-FD47709C69A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {9A24ADE8-C8B3-4384-9B80-FD47709C69A6}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {9A24ADE8-C8B3-4384-9B80-FD47709C69A6}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {9A24ADE8-C8B3-4384-9B80-FD47709C69A6}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {CF54B583-55B7-4102-AA36-C32B3DD54969} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/Comments/Endpoints/CreateComment.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Comments.Endpoints; 2 | 3 | public class CreateComment : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapPost("/", Handle) 7 | .WithSummary("Creates a new comment") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.PostId) 10 | .WithEnsureEntityExists(x => x.ReplyToCommentId); 11 | 12 | public record Request(int PostId, string Content, int? ReplyToCommentId); 13 | public record Response(int Id); 14 | public class RequestValidator : AbstractValidator 15 | { 16 | public RequestValidator() 17 | { 18 | RuleFor(x => x.PostId).GreaterThan(0); 19 | RuleFor(x => x.Content).NotEmpty(); 20 | RuleFor(x => x.ReplyToCommentId).GreaterThan(0); 21 | } 22 | } 23 | 24 | private static async Task> Handle(Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 25 | { 26 | var comment = new Comment 27 | { 28 | PostId = request.PostId, 29 | UserId = claimsPrincipal.GetUserId(), 30 | Content = request.Content, 31 | ReplyToCommentId = request.ReplyToCommentId 32 | }; 33 | await database.Comments.AddAsync(comment, cancellationToken); 34 | await database.SaveChangesAsync(cancellationToken); 35 | var response = new Response(comment.Id); 36 | return TypedResults.Ok(response); 37 | } 38 | } -------------------------------------------------------------------------------- /src/Comments/Endpoints/GetCommentReplies.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Comments.Endpoints; 2 | 3 | public class GetCommentReplies : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}/replies", Handle) 7 | .WithSummary("Gets all replies to a comment") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id, int? Page, int? PageSize) : IPagedRequest; 12 | public record Response(int Id, int UserId, string Username, string UserDisplayName, string Content, int NumberOfReplies); 13 | public class RequestValidator : PagedRequestValidator 14 | { 15 | public RequestValidator() 16 | { 17 | RuleFor(x => x.Id).GreaterThan(0); 18 | } 19 | } 20 | 21 | private static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 22 | { 23 | var replies = await database.Comments 24 | .Where(x => x.ReplyToCommentId == request.Id) 25 | .OrderByDescending(x => x.CreatedAtUtc) 26 | .Select(x => new Response 27 | ( 28 | x.Id, 29 | x.UserId, 30 | x.User.Username, 31 | x.User.DisplayName, 32 | x.Content, 33 | x.Replies.Count 34 | )) 35 | .ToPagedListAsync(request, cancellationToken); 36 | 37 | return replies; 38 | } 39 | } -------------------------------------------------------------------------------- /src/Comments/Endpoints/LikeComment.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Comments.Endpoints; 2 | 3 | public class LikeComment : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapPost("/{id}/like", Handle) 7 | .WithSummary("Like a comment") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | 20 | public static async Task Handle([AsParameters] Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 21 | { 22 | var userId = claimsPrincipal.GetUserId(); 23 | 24 | var exists = await database.CommentLikes 25 | .AnyAsync(x => x.CommentId == request.Id && x.UserId == userId, cancellationToken); 26 | 27 | if (exists) 28 | { 29 | return TypedResults.Ok(); 30 | } 31 | 32 | var like = new CommentLike 33 | { 34 | CommentId = request.Id, 35 | UserId = userId, 36 | }; 37 | 38 | await database.CommentLikes.AddAsync(like, cancellationToken); 39 | await database.SaveChangesAsync(cancellationToken); 40 | return TypedResults.Ok(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Comments/Endpoints/UnlikeComment.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Comments.Endpoints; 2 | 3 | public class UnlikeComment : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapDelete("/{id}/unlike", Handle) 7 | .WithSummary("Unlike a comment") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | 20 | public static async Task> Handle([AsParameters] Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 21 | { 22 | var userId = claimsPrincipal.GetUserId(); 23 | 24 | var rowsDeleted = await database.CommentLikes 25 | .Where(x => x.CommentId == request.Id && x.UserId == userId) 26 | .ExecuteDeleteAsync(cancellationToken); 27 | 28 | if (rowsDeleted == 0) 29 | { 30 | return TypedResults.NotFound(); 31 | } 32 | 33 | // TODO: Publish event to notify comment unliked 34 | 35 | return TypedResults.Ok(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Common/Api/Extensions/RouteHandlerBuilderValidationExtensions.cs: -------------------------------------------------------------------------------- 1 | using Chirper.Common.Api.Filters; 2 | 3 | namespace Chirper.Common.Api.Extensions; 4 | 5 | public static class RouteHandlerBuilderValidationExtensions 6 | { 7 | /// 8 | /// Adds a request validation filter to the route handler. 9 | /// 10 | /// 11 | /// 12 | /// A that can be used to futher customize the endpoint. 13 | public static RouteHandlerBuilder WithRequestValidation(this RouteHandlerBuilder builder) 14 | { 15 | return builder 16 | .AddEndpointFilter>() 17 | .ProducesValidationProblem(); 18 | } 19 | 20 | /// 21 | /// Adds a request validation filter to the route handler to ensure a exists with the id returned by . 22 | /// 23 | /// 24 | /// 25 | /// 26 | /// A function which selects the Id property from the 27 | /// A that can be used to futher customize the endpoint. 28 | public static RouteHandlerBuilder WithEnsureEntityExists(this RouteHandlerBuilder builder, Func idSelector) where TEntity : class, IEntity 29 | { 30 | return builder 31 | .AddEndpointFilterFactory((endpointFilterFactoryContext, next) => async context => 32 | { 33 | var db = context.HttpContext.RequestServices.GetRequiredService(); 34 | var filter = new EnsureEntityExistsFilter(db, idSelector); 35 | return await filter.InvokeAsync(context, next); 36 | }) 37 | .ProducesProblem(StatusCodes.Status404NotFound); 38 | } 39 | 40 | /// 41 | /// Adds a request validation filter to the route handler to ensure the current owns the with the id returned by . 42 | /// 43 | /// 44 | /// 45 | /// 46 | /// A function which selects the Id property from the 47 | /// A that can be used to futher customize the endpoint. 48 | public static RouteHandlerBuilder WithEnsureUserOwnsEntity(this RouteHandlerBuilder builder, Func idSelector) where TEntity : class, IEntity, IOwnedEntity 49 | { 50 | return builder 51 | .AddEndpointFilterFactory((endpointFilterFactoryContext, next) => async context => 52 | { 53 | var db = context.HttpContext.RequestServices.GetRequiredService(); 54 | var filter = new EnsureUserOwnsEntityFilter(db, idSelector); 55 | return await filter.InvokeAsync(context, next); 56 | }) 57 | .ProducesProblem(StatusCodes.Status404NotFound) 58 | .Produces(StatusCodes.Status403Forbidden); 59 | } 60 | } -------------------------------------------------------------------------------- /src/Common/Api/Filters/EnsureEntityExistsFilter.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Common.Api.Filters; 2 | 3 | public class EnsureEntityExistsFilter(AppDbContext database, Func idSelector) : IEndpointFilter 4 | where TEntity : class, IEntity 5 | { 6 | public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) 7 | { 8 | var request = context.Arguments.OfType().Single(); 9 | var cancellationToken = context.HttpContext.RequestAborted; 10 | var id = idSelector(request); 11 | 12 | if (!id.HasValue) 13 | { 14 | return await next(context); 15 | } 16 | 17 | var exists = await database 18 | .Set() 19 | .AnyAsync(x => x.Id == id, cancellationToken); 20 | 21 | return exists 22 | ? await next(context) 23 | : new NotFoundProblem($"{typeof(TEntity).Name} with id {id} was not found."); 24 | } 25 | } -------------------------------------------------------------------------------- /src/Common/Api/Filters/EnsureUserOwnsEntityFilter.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Common.Api.Filters; 2 | 3 | public class EnsureUserOwnsEntityFilter(AppDbContext database, Func idSelector) : IEndpointFilter 4 | where TEntity : class, IEntity, IOwnedEntity 5 | { 6 | public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) 7 | { 8 | var request = context.Arguments.OfType().Single(); 9 | var cancellationToken = context.HttpContext.RequestAborted; 10 | var userId = context.HttpContext.User.GetUserId(); 11 | var id = idSelector(request); 12 | 13 | var entity = await database 14 | .Set() 15 | .Where(x => x.Id == id) 16 | .Select(x => new Entity(x.Id, x.UserId)) 17 | .SingleOrDefaultAsync(cancellationToken); 18 | 19 | return entity switch 20 | { 21 | null => new NotFoundProblem($"{typeof(TEntity).Name} with id {id} was not found."), 22 | _ when entity.UserId != userId => TypedResults.Forbid(), 23 | _ => await next(context) 24 | }; 25 | } 26 | 27 | private record Entity(int Id, int UserId); 28 | } -------------------------------------------------------------------------------- /src/Common/Api/Filters/RequestLoggingFilter.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Common.Api.Filters; 2 | 3 | public class RequestLoggingFilter(ILogger logger) : IEndpointFilter 4 | { 5 | public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) 6 | { 7 | logger.LogInformation("HTTP {Method} {Path} received", context.HttpContext.Request.Method, context.HttpContext.Request.Path); 8 | return await next(context); 9 | } 10 | } -------------------------------------------------------------------------------- /src/Common/Api/Filters/RequestValidationFilter.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Common.Api.Filters; 2 | 3 | public class RequestValidationFilter(ILogger> logger, IValidator? validator = null) : IEndpointFilter 4 | { 5 | public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) 6 | { 7 | var requestName = typeof(TRequest).FullName; 8 | 9 | if (validator is null) 10 | { 11 | logger.LogInformation("{Request}: No validator configured.", requestName); 12 | return await next(context); 13 | } 14 | 15 | logger.LogInformation("{Request}: Validating...", requestName); 16 | var request = context.Arguments.OfType().First(); 17 | var validationResult = await validator.ValidateAsync(request, context.HttpContext.RequestAborted); 18 | if (!validationResult.IsValid) 19 | { 20 | logger.LogWarning("{Request}: Validation failed.", requestName); 21 | return TypedResults.ValidationProblem(validationResult.ToDictionary()); 22 | } 23 | 24 | logger.LogInformation("{Request}: Validation succeeded.", requestName); 25 | return await next(context); 26 | } 27 | } -------------------------------------------------------------------------------- /src/Common/Api/IEndpoint.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Common.Api; 2 | 3 | public interface IEndpoint 4 | { 5 | static abstract void Map(IEndpointRouteBuilder app); 6 | } 7 | -------------------------------------------------------------------------------- /src/Common/Api/Requests/PagedRequest.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Common.Api.Requests; 2 | 3 | public interface IPagedRequest 4 | { 5 | public const int MaxPageSize = 100; 6 | int? Page { get; } 7 | int? PageSize { get; } 8 | } 9 | 10 | public class PagedRequestValidator : AbstractValidator where T : IPagedRequest 11 | { 12 | public PagedRequestValidator() 13 | { 14 | RuleFor(x => x.Page).GreaterThan(0); 15 | RuleFor(x => x.PageSize) 16 | .GreaterThan(0) 17 | .LessThanOrEqualTo(IPagedRequest.MaxPageSize); 18 | } 19 | } 20 | 21 | public record PagedList(List Items, int Page, int PageSize, int TotalItems) 22 | { 23 | public bool HasNextPage => Page * PageSize < TotalItems; 24 | public bool HasPreviousPage => Page > 1; 25 | } 26 | 27 | public static class PaginationDatabaseExtensions 28 | { 29 | public static async Task> ToPagedListAsync(this IQueryable query, TRequest request, CancellationToken cancellationToken = default) where TRequest : IPagedRequest 30 | { 31 | var page = request.Page ?? 1; 32 | var pageSize = request.PageSize ?? 10; 33 | 34 | ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(page, 0); 35 | ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(pageSize, 0); 36 | ArgumentOutOfRangeException.ThrowIfGreaterThan(pageSize, IPagedRequest.MaxPageSize); 37 | 38 | var totalItems = await query.CountAsync(cancellationToken); 39 | 40 | var items = await query 41 | .Skip((page - 1) * pageSize) 42 | .Take(pageSize) 43 | .ToListAsync(cancellationToken); 44 | 45 | return new PagedList(items, page, pageSize, totalItems); 46 | } 47 | } -------------------------------------------------------------------------------- /src/Common/Api/Results/NotFoundProblem.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http.Metadata; 2 | using Microsoft.AspNetCore.Mvc; 3 | using System.Reflection; 4 | 5 | namespace Chirper.Common.Api.Results; 6 | 7 | public sealed class NotFoundProblem : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IContentTypeHttpResult, IValueHttpResult, IValueHttpResult 8 | { 9 | private readonly ProblemHttpResult problem; 10 | 11 | public NotFoundProblem(string errorMessage) 12 | { 13 | problem = TypedResults.Problem 14 | ( 15 | statusCode: StatusCode, 16 | title: "Not Found", 17 | detail: errorMessage 18 | ); 19 | } 20 | 21 | public int? StatusCode => StatusCodes.Status404NotFound; 22 | public string? ContentType => problem.ContentType; 23 | public object? Value => problem.ProblemDetails; 24 | ProblemDetails? IValueHttpResult.Value => problem.ProblemDetails; 25 | 26 | public static void PopulateMetadata(MethodInfo method, EndpointBuilder builder) 27 | { 28 | builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status404NotFound, typeof(ProblemDetails), ["application/problem+json"])); 29 | } 30 | 31 | public async Task ExecuteAsync(HttpContext httpContext) 32 | { 33 | await problem.ExecuteAsync(httpContext); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Common/Api/Results/ValidationError.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http.Metadata; 2 | using System.Reflection; 3 | 4 | namespace Chirper.Common.Api.Results; 5 | 6 | public sealed class ValidationError : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IContentTypeHttpResult, IValueHttpResult, IValueHttpResult 7 | { 8 | private readonly ValidationProblem problem; 9 | 10 | public ValidationError(string errorMessage) 11 | { 12 | problem = TypedResults.ValidationProblem 13 | ( 14 | errors: new Dictionary(), 15 | detail: errorMessage 16 | ); 17 | } 18 | 19 | public int? StatusCode => problem.StatusCode; 20 | public string? ContentType => problem.ContentType; 21 | public object? Value => problem.ProblemDetails; 22 | HttpValidationProblemDetails? IValueHttpResult.Value => problem.ProblemDetails; 23 | 24 | public static void PopulateMetadata(MethodInfo method, EndpointBuilder builder) 25 | { 26 | builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status400BadRequest, typeof(HttpValidationProblemDetails), ["application/problem+json"])); 27 | } 28 | 29 | public async Task ExecuteAsync(HttpContext httpContext) 30 | { 31 | await problem.ExecuteAsync(httpContext); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/ConfigureApp.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | 3 | namespace Chirper; 4 | 5 | public static class ConfigureApp 6 | { 7 | public static async Task Configure(this WebApplication app) 8 | { 9 | app.UseSerilogRequestLogging(); 10 | app.UseSwagger(); 11 | app.UseSwaggerUI(); 12 | app.UseHttpsRedirection(); 13 | app.MapEndpoints(); 14 | await app.EnsureDatabaseCreated(); 15 | } 16 | 17 | private static async Task EnsureDatabaseCreated(this WebApplication app) 18 | { 19 | using var scope = app.Services.CreateScope(); 20 | var db = scope.ServiceProvider.GetRequiredService(); 21 | await db.Database.MigrateAsync(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/ConfigureServices.cs: -------------------------------------------------------------------------------- 1 | using Chirper.Authentication.Services; 2 | using Microsoft.IdentityModel.Tokens; 3 | using Serilog; 4 | 5 | namespace Chirper; 6 | 7 | public static class ConfigureServices 8 | { 9 | public static void AddServices(this WebApplicationBuilder builder) 10 | { 11 | builder.AddSerilog(); 12 | builder.AddSwagger(); 13 | builder.AddDatabase(); 14 | builder.Services.AddValidatorsFromAssembly(typeof(ConfigureServices).Assembly); 15 | builder.AddJwtAuthentication(); 16 | } 17 | 18 | private static void AddSwagger(this WebApplicationBuilder builder) 19 | { 20 | builder.Services.AddEndpointsApiExplorer(); 21 | builder.Services.AddSwaggerGen(options => 22 | { 23 | options.CustomSchemaIds(type => type.FullName?.Replace('+', '.')); 24 | options.InferSecuritySchemes(); 25 | }); 26 | } 27 | 28 | private static void AddSerilog(this WebApplicationBuilder builder) 29 | { 30 | builder.Host.UseSerilog((context, configuration) => 31 | { 32 | configuration.ReadFrom.Configuration(context.Configuration); 33 | }); 34 | } 35 | 36 | private static void AddDatabase(this WebApplicationBuilder builder) 37 | { 38 | builder.Services.AddDbContext(options => 39 | { 40 | options.UseSqlServer(builder.Configuration.GetConnectionString("Default")); 41 | }); 42 | } 43 | 44 | private static void AddJwtAuthentication(this WebApplicationBuilder builder) 45 | { 46 | builder.Services.AddAuthentication().AddJwtBearer(options => 47 | { 48 | options.TokenValidationParameters = new TokenValidationParameters 49 | { 50 | IssuerSigningKey = Jwt.SecurityKey(builder.Configuration["Jwt:Key"]!), 51 | ValidateIssuer = false, 52 | ValidateAudience = false, 53 | ValidateLifetime = true, 54 | ValidateIssuerSigningKey = true, 55 | ClockSkew = TimeSpan.Zero 56 | }; 57 | }); 58 | builder.Services.AddAuthorization(); 59 | 60 | builder.Services.Configure(builder.Configuration.GetSection("Jwt")); 61 | builder.Services.AddTransient(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/Data/AppDbContext.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Data; 2 | 3 | public class AppDbContext(DbContextOptions options) : DbContext(options) 4 | { 5 | public DbSet Users { get; set; } 6 | public DbSet Posts { get; set; } 7 | public DbSet PostLikes { get; set; } 8 | public DbSet Comments { get; set; } 9 | public DbSet CommentLikes { get; set; } 10 | public DbSet Follows { get; set; } 11 | 12 | protected override void OnModelCreating(ModelBuilder modelBuilder) 13 | { 14 | ConfigureUsersTable(modelBuilder); 15 | ConfigurePostsTable(modelBuilder); 16 | ConfigureCommentsTable(modelBuilder); 17 | ConfigureLikesTable(modelBuilder); 18 | ConfigureFollowsTable(modelBuilder); 19 | ConfigureCommentLikesTable(modelBuilder); 20 | base.OnModelCreating(modelBuilder); 21 | } 22 | 23 | private static void ConfigureUsersTable(ModelBuilder modelBuilder) 24 | { 25 | var builder = modelBuilder.Entity(); 26 | 27 | builder.HasIndex(x => x.Username) 28 | .IsUnique(); 29 | 30 | builder.HasIndex(x => x.ReferenceId) 31 | .IsUnique(); 32 | 33 | builder.HasMany(x => x.Posts) 34 | .WithOne(x => x.User) 35 | .HasForeignKey(x => x.UserId) 36 | .OnDelete(DeleteBehavior.NoAction); 37 | 38 | builder.HasMany(x => x.LikedPosts) 39 | .WithOne(x => x.User) 40 | .HasForeignKey(x => x.UserId) 41 | .OnDelete(DeleteBehavior.NoAction); 42 | 43 | builder.HasMany(x => x.Comments) 44 | .WithOne(x => x.User) 45 | .HasForeignKey(x => x.UserId) 46 | .OnDelete(DeleteBehavior.NoAction); 47 | 48 | builder.HasMany(x => x.LikedComments) 49 | .WithOne(x => x.User) 50 | .HasForeignKey(x => x.UserId) 51 | .OnDelete(DeleteBehavior.NoAction); 52 | 53 | builder.HasMany(x => x.Following) 54 | .WithOne(x => x.FollowerUser) 55 | .HasForeignKey(x => x.FollowerUserId) 56 | .OnDelete(DeleteBehavior.NoAction); 57 | 58 | builder.HasMany(x => x.Followers) 59 | .WithOne(x => x.FollowedUser) 60 | .HasForeignKey(x => x.FollowedUserId) 61 | .OnDelete(DeleteBehavior.NoAction); 62 | } 63 | 64 | private static void ConfigurePostsTable(ModelBuilder modelBuilder) 65 | { 66 | var builder = modelBuilder.Entity(); 67 | 68 | builder.HasIndex(x => x.ReferenceId) 69 | .IsUnique(); 70 | 71 | builder.Property(x => x.Title) 72 | .HasMaxLength(100); 73 | 74 | builder.HasMany(x => x.Likes) 75 | .WithOne(x => x.Post) 76 | .HasForeignKey(x => x.PostId) 77 | .OnDelete(DeleteBehavior.NoAction); 78 | 79 | builder.HasMany(x => x.Comments) 80 | .WithOne(x => x.Post) 81 | .HasForeignKey(x => x.PostId) 82 | .OnDelete(DeleteBehavior.NoAction); 83 | } 84 | 85 | private static void ConfigureCommentsTable(ModelBuilder modelBuilder) 86 | { 87 | var builder = modelBuilder.Entity(); 88 | 89 | builder.HasIndex(x => x.ReferenceId) 90 | .IsUnique(); 91 | 92 | builder.HasMany(x => x.Likes) 93 | .WithOne(x => x.Comment) 94 | .HasForeignKey(x => x.CommentId) 95 | .OnDelete(DeleteBehavior.NoAction); 96 | 97 | builder.HasMany(x => x.Replies) 98 | .WithOne(x => x.ReplyToComment) 99 | .HasForeignKey(x => x.ReplyToCommentId) 100 | .OnDelete(DeleteBehavior.NoAction); 101 | } 102 | 103 | private static void ConfigureLikesTable(ModelBuilder modelBuilder) 104 | { 105 | var builder = modelBuilder.Entity(); 106 | builder.HasKey(x => new { x.PostId, x.UserId }); 107 | } 108 | 109 | private static void ConfigureFollowsTable(ModelBuilder modelBuilder) 110 | { 111 | var builder = modelBuilder.Entity(); 112 | builder.HasKey(x => new { x.FollowerUserId, x.FollowedUserId }); 113 | } 114 | 115 | private static void ConfigureCommentLikesTable(ModelBuilder modelBuilder) 116 | { 117 | var builder = modelBuilder.Entity(); 118 | builder.HasKey(x => new { x.CommentId, x.UserId }); 119 | } 120 | } -------------------------------------------------------------------------------- /src/Data/Migrations/20240715103609_Init.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Chirper.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | #nullable disable 11 | 12 | namespace Chirper.Data.Migrations 13 | { 14 | [DbContext(typeof(AppDbContext))] 15 | [Migration("20240715103609_Init")] 16 | partial class Init 17 | { 18 | /// 19 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 20 | { 21 | #pragma warning disable 612, 618 22 | modelBuilder 23 | .HasAnnotation("ProductVersion", "8.0.2") 24 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 25 | 26 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 27 | 28 | modelBuilder.Entity("Chirper.Data.Types.Comment", b => 29 | { 30 | b.Property("Id") 31 | .ValueGeneratedOnAdd() 32 | .HasColumnType("int"); 33 | 34 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 35 | 36 | b.Property("Content") 37 | .IsRequired() 38 | .HasColumnType("nvarchar(max)"); 39 | 40 | b.Property("CreatedAtUtc") 41 | .HasColumnType("datetime2"); 42 | 43 | b.Property("PostId") 44 | .HasColumnType("int"); 45 | 46 | b.Property("ReferenceId") 47 | .HasColumnType("uniqueidentifier"); 48 | 49 | b.Property("ReplyToCommentId") 50 | .HasColumnType("int"); 51 | 52 | b.Property("UpdatedAtUtc") 53 | .HasColumnType("datetime2"); 54 | 55 | b.Property("UserId") 56 | .HasColumnType("int"); 57 | 58 | b.HasKey("Id"); 59 | 60 | b.HasIndex("PostId"); 61 | 62 | b.HasIndex("ReferenceId") 63 | .IsUnique(); 64 | 65 | b.HasIndex("ReplyToCommentId"); 66 | 67 | b.HasIndex("UserId"); 68 | 69 | b.ToTable("Comments"); 70 | }); 71 | 72 | modelBuilder.Entity("Chirper.Data.Types.CommentLike", b => 73 | { 74 | b.Property("CommentId") 75 | .HasColumnType("int"); 76 | 77 | b.Property("UserId") 78 | .HasColumnType("int"); 79 | 80 | b.Property("CreatedAtUtc") 81 | .HasColumnType("datetime2"); 82 | 83 | b.HasKey("CommentId", "UserId"); 84 | 85 | b.HasIndex("UserId"); 86 | 87 | b.ToTable("CommentLikes"); 88 | }); 89 | 90 | modelBuilder.Entity("Chirper.Data.Types.Follow", b => 91 | { 92 | b.Property("FollowerUserId") 93 | .HasColumnType("int"); 94 | 95 | b.Property("FollowedUserId") 96 | .HasColumnType("int"); 97 | 98 | b.Property("CreatedAtUtc") 99 | .HasColumnType("datetime2"); 100 | 101 | b.HasKey("FollowerUserId", "FollowedUserId"); 102 | 103 | b.HasIndex("FollowedUserId"); 104 | 105 | b.ToTable("Follows"); 106 | }); 107 | 108 | modelBuilder.Entity("Chirper.Data.Types.Post", b => 109 | { 110 | b.Property("Id") 111 | .ValueGeneratedOnAdd() 112 | .HasColumnType("int"); 113 | 114 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 115 | 116 | b.Property("Content") 117 | .HasColumnType("nvarchar(max)"); 118 | 119 | b.Property("CreatedAtUtc") 120 | .HasColumnType("datetime2"); 121 | 122 | b.Property("ReferenceId") 123 | .HasColumnType("uniqueidentifier"); 124 | 125 | b.Property("Title") 126 | .IsRequired() 127 | .HasMaxLength(100) 128 | .HasColumnType("nvarchar(100)"); 129 | 130 | b.Property("UpdatedAtUtc") 131 | .HasColumnType("datetime2"); 132 | 133 | b.Property("UserId") 134 | .HasColumnType("int"); 135 | 136 | b.HasKey("Id"); 137 | 138 | b.HasIndex("ReferenceId") 139 | .IsUnique(); 140 | 141 | b.HasIndex("UserId"); 142 | 143 | b.ToTable("Posts"); 144 | }); 145 | 146 | modelBuilder.Entity("Chirper.Data.Types.PostLike", b => 147 | { 148 | b.Property("PostId") 149 | .HasColumnType("int"); 150 | 151 | b.Property("UserId") 152 | .HasColumnType("int"); 153 | 154 | b.Property("CreatedAtUtc") 155 | .HasColumnType("datetime2"); 156 | 157 | b.HasKey("PostId", "UserId"); 158 | 159 | b.HasIndex("UserId"); 160 | 161 | b.ToTable("PostLikes"); 162 | }); 163 | 164 | modelBuilder.Entity("Chirper.Data.Types.User", b => 165 | { 166 | b.Property("Id") 167 | .ValueGeneratedOnAdd() 168 | .HasColumnType("int"); 169 | 170 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 171 | 172 | b.Property("CreatedAtUtc") 173 | .HasColumnType("datetime2"); 174 | 175 | b.Property("DisplayName") 176 | .IsRequired() 177 | .HasColumnType("nvarchar(max)"); 178 | 179 | b.Property("Password") 180 | .IsRequired() 181 | .HasColumnType("nvarchar(max)"); 182 | 183 | b.Property("ReferenceId") 184 | .HasColumnType("uniqueidentifier"); 185 | 186 | b.Property("Username") 187 | .IsRequired() 188 | .HasColumnType("nvarchar(450)"); 189 | 190 | b.HasKey("Id"); 191 | 192 | b.HasIndex("ReferenceId") 193 | .IsUnique(); 194 | 195 | b.HasIndex("Username") 196 | .IsUnique(); 197 | 198 | b.ToTable("Users"); 199 | }); 200 | 201 | modelBuilder.Entity("Chirper.Data.Types.Comment", b => 202 | { 203 | b.HasOne("Chirper.Data.Types.Post", "Post") 204 | .WithMany("Comments") 205 | .HasForeignKey("PostId") 206 | .OnDelete(DeleteBehavior.NoAction) 207 | .IsRequired(); 208 | 209 | b.HasOne("Chirper.Data.Types.Comment", "ReplyToComment") 210 | .WithMany("Replies") 211 | .HasForeignKey("ReplyToCommentId") 212 | .OnDelete(DeleteBehavior.NoAction); 213 | 214 | b.HasOne("Chirper.Data.Types.User", "User") 215 | .WithMany("Comments") 216 | .HasForeignKey("UserId") 217 | .OnDelete(DeleteBehavior.NoAction) 218 | .IsRequired(); 219 | 220 | b.Navigation("Post"); 221 | 222 | b.Navigation("ReplyToComment"); 223 | 224 | b.Navigation("User"); 225 | }); 226 | 227 | modelBuilder.Entity("Chirper.Data.Types.CommentLike", b => 228 | { 229 | b.HasOne("Chirper.Data.Types.Comment", "Comment") 230 | .WithMany("Likes") 231 | .HasForeignKey("CommentId") 232 | .OnDelete(DeleteBehavior.NoAction) 233 | .IsRequired(); 234 | 235 | b.HasOne("Chirper.Data.Types.User", "User") 236 | .WithMany("LikedComments") 237 | .HasForeignKey("UserId") 238 | .OnDelete(DeleteBehavior.NoAction) 239 | .IsRequired(); 240 | 241 | b.Navigation("Comment"); 242 | 243 | b.Navigation("User"); 244 | }); 245 | 246 | modelBuilder.Entity("Chirper.Data.Types.Follow", b => 247 | { 248 | b.HasOne("Chirper.Data.Types.User", "FollowedUser") 249 | .WithMany("Followers") 250 | .HasForeignKey("FollowedUserId") 251 | .OnDelete(DeleteBehavior.NoAction) 252 | .IsRequired(); 253 | 254 | b.HasOne("Chirper.Data.Types.User", "FollowerUser") 255 | .WithMany("Following") 256 | .HasForeignKey("FollowerUserId") 257 | .OnDelete(DeleteBehavior.NoAction) 258 | .IsRequired(); 259 | 260 | b.Navigation("FollowedUser"); 261 | 262 | b.Navigation("FollowerUser"); 263 | }); 264 | 265 | modelBuilder.Entity("Chirper.Data.Types.Post", b => 266 | { 267 | b.HasOne("Chirper.Data.Types.User", "User") 268 | .WithMany("Posts") 269 | .HasForeignKey("UserId") 270 | .OnDelete(DeleteBehavior.NoAction) 271 | .IsRequired(); 272 | 273 | b.Navigation("User"); 274 | }); 275 | 276 | modelBuilder.Entity("Chirper.Data.Types.PostLike", b => 277 | { 278 | b.HasOne("Chirper.Data.Types.Post", "Post") 279 | .WithMany("Likes") 280 | .HasForeignKey("PostId") 281 | .OnDelete(DeleteBehavior.NoAction) 282 | .IsRequired(); 283 | 284 | b.HasOne("Chirper.Data.Types.User", "User") 285 | .WithMany("LikedPosts") 286 | .HasForeignKey("UserId") 287 | .OnDelete(DeleteBehavior.NoAction) 288 | .IsRequired(); 289 | 290 | b.Navigation("Post"); 291 | 292 | b.Navigation("User"); 293 | }); 294 | 295 | modelBuilder.Entity("Chirper.Data.Types.Comment", b => 296 | { 297 | b.Navigation("Likes"); 298 | 299 | b.Navigation("Replies"); 300 | }); 301 | 302 | modelBuilder.Entity("Chirper.Data.Types.Post", b => 303 | { 304 | b.Navigation("Comments"); 305 | 306 | b.Navigation("Likes"); 307 | }); 308 | 309 | modelBuilder.Entity("Chirper.Data.Types.User", b => 310 | { 311 | b.Navigation("Comments"); 312 | 313 | b.Navigation("Followers"); 314 | 315 | b.Navigation("Following"); 316 | 317 | b.Navigation("LikedComments"); 318 | 319 | b.Navigation("LikedPosts"); 320 | 321 | b.Navigation("Posts"); 322 | }); 323 | #pragma warning restore 612, 618 324 | } 325 | } 326 | } 327 | -------------------------------------------------------------------------------- /src/Data/Migrations/20240715103609_Init.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace Chirper.Data.Migrations 7 | { 8 | /// 9 | public partial class Init : Migration 10 | { 11 | /// 12 | protected override void Up(MigrationBuilder migrationBuilder) 13 | { 14 | migrationBuilder.CreateTable( 15 | name: "Users", 16 | columns: table => new 17 | { 18 | Id = table.Column(type: "int", nullable: false) 19 | .Annotation("SqlServer:Identity", "1, 1"), 20 | ReferenceId = table.Column(type: "uniqueidentifier", nullable: false), 21 | Username = table.Column(type: "nvarchar(450)", nullable: false), 22 | Password = table.Column(type: "nvarchar(max)", nullable: false), 23 | DisplayName = table.Column(type: "nvarchar(max)", nullable: false), 24 | CreatedAtUtc = table.Column(type: "datetime2", nullable: false) 25 | }, 26 | constraints: table => 27 | { 28 | table.PrimaryKey("PK_Users", x => x.Id); 29 | }); 30 | 31 | migrationBuilder.CreateTable( 32 | name: "Follows", 33 | columns: table => new 34 | { 35 | FollowerUserId = table.Column(type: "int", nullable: false), 36 | FollowedUserId = table.Column(type: "int", nullable: false), 37 | CreatedAtUtc = table.Column(type: "datetime2", nullable: false) 38 | }, 39 | constraints: table => 40 | { 41 | table.PrimaryKey("PK_Follows", x => new { x.FollowerUserId, x.FollowedUserId }); 42 | table.ForeignKey( 43 | name: "FK_Follows_Users_FollowedUserId", 44 | column: x => x.FollowedUserId, 45 | principalTable: "Users", 46 | principalColumn: "Id"); 47 | table.ForeignKey( 48 | name: "FK_Follows_Users_FollowerUserId", 49 | column: x => x.FollowerUserId, 50 | principalTable: "Users", 51 | principalColumn: "Id"); 52 | }); 53 | 54 | migrationBuilder.CreateTable( 55 | name: "Posts", 56 | columns: table => new 57 | { 58 | Id = table.Column(type: "int", nullable: false) 59 | .Annotation("SqlServer:Identity", "1, 1"), 60 | ReferenceId = table.Column(type: "uniqueidentifier", nullable: false), 61 | Title = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), 62 | Content = table.Column(type: "nvarchar(max)", nullable: true), 63 | UserId = table.Column(type: "int", nullable: false), 64 | CreatedAtUtc = table.Column(type: "datetime2", nullable: false), 65 | UpdatedAtUtc = table.Column(type: "datetime2", nullable: true) 66 | }, 67 | constraints: table => 68 | { 69 | table.PrimaryKey("PK_Posts", x => x.Id); 70 | table.ForeignKey( 71 | name: "FK_Posts_Users_UserId", 72 | column: x => x.UserId, 73 | principalTable: "Users", 74 | principalColumn: "Id"); 75 | }); 76 | 77 | migrationBuilder.CreateTable( 78 | name: "Comments", 79 | columns: table => new 80 | { 81 | Id = table.Column(type: "int", nullable: false) 82 | .Annotation("SqlServer:Identity", "1, 1"), 83 | ReferenceId = table.Column(type: "uniqueidentifier", nullable: false), 84 | PostId = table.Column(type: "int", nullable: false), 85 | UserId = table.Column(type: "int", nullable: false), 86 | Content = table.Column(type: "nvarchar(max)", nullable: false), 87 | ReplyToCommentId = table.Column(type: "int", nullable: true), 88 | CreatedAtUtc = table.Column(type: "datetime2", nullable: false), 89 | UpdatedAtUtc = table.Column(type: "datetime2", nullable: true) 90 | }, 91 | constraints: table => 92 | { 93 | table.PrimaryKey("PK_Comments", x => x.Id); 94 | table.ForeignKey( 95 | name: "FK_Comments_Comments_ReplyToCommentId", 96 | column: x => x.ReplyToCommentId, 97 | principalTable: "Comments", 98 | principalColumn: "Id"); 99 | table.ForeignKey( 100 | name: "FK_Comments_Posts_PostId", 101 | column: x => x.PostId, 102 | principalTable: "Posts", 103 | principalColumn: "Id"); 104 | table.ForeignKey( 105 | name: "FK_Comments_Users_UserId", 106 | column: x => x.UserId, 107 | principalTable: "Users", 108 | principalColumn: "Id"); 109 | }); 110 | 111 | migrationBuilder.CreateTable( 112 | name: "PostLikes", 113 | columns: table => new 114 | { 115 | PostId = table.Column(type: "int", nullable: false), 116 | UserId = table.Column(type: "int", nullable: false), 117 | CreatedAtUtc = table.Column(type: "datetime2", nullable: false) 118 | }, 119 | constraints: table => 120 | { 121 | table.PrimaryKey("PK_PostLikes", x => new { x.PostId, x.UserId }); 122 | table.ForeignKey( 123 | name: "FK_PostLikes_Posts_PostId", 124 | column: x => x.PostId, 125 | principalTable: "Posts", 126 | principalColumn: "Id"); 127 | table.ForeignKey( 128 | name: "FK_PostLikes_Users_UserId", 129 | column: x => x.UserId, 130 | principalTable: "Users", 131 | principalColumn: "Id"); 132 | }); 133 | 134 | migrationBuilder.CreateTable( 135 | name: "CommentLikes", 136 | columns: table => new 137 | { 138 | CommentId = table.Column(type: "int", nullable: false), 139 | UserId = table.Column(type: "int", nullable: false), 140 | CreatedAtUtc = table.Column(type: "datetime2", nullable: false) 141 | }, 142 | constraints: table => 143 | { 144 | table.PrimaryKey("PK_CommentLikes", x => new { x.CommentId, x.UserId }); 145 | table.ForeignKey( 146 | name: "FK_CommentLikes_Comments_CommentId", 147 | column: x => x.CommentId, 148 | principalTable: "Comments", 149 | principalColumn: "Id"); 150 | table.ForeignKey( 151 | name: "FK_CommentLikes_Users_UserId", 152 | column: x => x.UserId, 153 | principalTable: "Users", 154 | principalColumn: "Id"); 155 | }); 156 | 157 | migrationBuilder.CreateIndex( 158 | name: "IX_CommentLikes_UserId", 159 | table: "CommentLikes", 160 | column: "UserId"); 161 | 162 | migrationBuilder.CreateIndex( 163 | name: "IX_Comments_PostId", 164 | table: "Comments", 165 | column: "PostId"); 166 | 167 | migrationBuilder.CreateIndex( 168 | name: "IX_Comments_ReferenceId", 169 | table: "Comments", 170 | column: "ReferenceId", 171 | unique: true); 172 | 173 | migrationBuilder.CreateIndex( 174 | name: "IX_Comments_ReplyToCommentId", 175 | table: "Comments", 176 | column: "ReplyToCommentId"); 177 | 178 | migrationBuilder.CreateIndex( 179 | name: "IX_Comments_UserId", 180 | table: "Comments", 181 | column: "UserId"); 182 | 183 | migrationBuilder.CreateIndex( 184 | name: "IX_Follows_FollowedUserId", 185 | table: "Follows", 186 | column: "FollowedUserId"); 187 | 188 | migrationBuilder.CreateIndex( 189 | name: "IX_PostLikes_UserId", 190 | table: "PostLikes", 191 | column: "UserId"); 192 | 193 | migrationBuilder.CreateIndex( 194 | name: "IX_Posts_ReferenceId", 195 | table: "Posts", 196 | column: "ReferenceId", 197 | unique: true); 198 | 199 | migrationBuilder.CreateIndex( 200 | name: "IX_Posts_UserId", 201 | table: "Posts", 202 | column: "UserId"); 203 | 204 | migrationBuilder.CreateIndex( 205 | name: "IX_Users_ReferenceId", 206 | table: "Users", 207 | column: "ReferenceId", 208 | unique: true); 209 | 210 | migrationBuilder.CreateIndex( 211 | name: "IX_Users_Username", 212 | table: "Users", 213 | column: "Username", 214 | unique: true); 215 | } 216 | 217 | /// 218 | protected override void Down(MigrationBuilder migrationBuilder) 219 | { 220 | migrationBuilder.DropTable( 221 | name: "CommentLikes"); 222 | 223 | migrationBuilder.DropTable( 224 | name: "Follows"); 225 | 226 | migrationBuilder.DropTable( 227 | name: "PostLikes"); 228 | 229 | migrationBuilder.DropTable( 230 | name: "Comments"); 231 | 232 | migrationBuilder.DropTable( 233 | name: "Posts"); 234 | 235 | migrationBuilder.DropTable( 236 | name: "Users"); 237 | } 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /src/Data/Migrations/AppDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Chirper.Data; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | #nullable disable 10 | 11 | namespace Chirper.Data.Migrations 12 | { 13 | [DbContext(typeof(AppDbContext))] 14 | partial class AppDbContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "8.0.2") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 24 | 25 | modelBuilder.Entity("Chirper.Data.Types.Comment", b => 26 | { 27 | b.Property("Id") 28 | .ValueGeneratedOnAdd() 29 | .HasColumnType("int"); 30 | 31 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 32 | 33 | b.Property("Content") 34 | .IsRequired() 35 | .HasColumnType("nvarchar(max)"); 36 | 37 | b.Property("CreatedAtUtc") 38 | .HasColumnType("datetime2"); 39 | 40 | b.Property("PostId") 41 | .HasColumnType("int"); 42 | 43 | b.Property("ReferenceId") 44 | .HasColumnType("uniqueidentifier"); 45 | 46 | b.Property("ReplyToCommentId") 47 | .HasColumnType("int"); 48 | 49 | b.Property("UpdatedAtUtc") 50 | .HasColumnType("datetime2"); 51 | 52 | b.Property("UserId") 53 | .HasColumnType("int"); 54 | 55 | b.HasKey("Id"); 56 | 57 | b.HasIndex("PostId"); 58 | 59 | b.HasIndex("ReferenceId") 60 | .IsUnique(); 61 | 62 | b.HasIndex("ReplyToCommentId"); 63 | 64 | b.HasIndex("UserId"); 65 | 66 | b.ToTable("Comments"); 67 | }); 68 | 69 | modelBuilder.Entity("Chirper.Data.Types.CommentLike", b => 70 | { 71 | b.Property("CommentId") 72 | .HasColumnType("int"); 73 | 74 | b.Property("UserId") 75 | .HasColumnType("int"); 76 | 77 | b.Property("CreatedAtUtc") 78 | .HasColumnType("datetime2"); 79 | 80 | b.HasKey("CommentId", "UserId"); 81 | 82 | b.HasIndex("UserId"); 83 | 84 | b.ToTable("CommentLikes"); 85 | }); 86 | 87 | modelBuilder.Entity("Chirper.Data.Types.Follow", b => 88 | { 89 | b.Property("FollowerUserId") 90 | .HasColumnType("int"); 91 | 92 | b.Property("FollowedUserId") 93 | .HasColumnType("int"); 94 | 95 | b.Property("CreatedAtUtc") 96 | .HasColumnType("datetime2"); 97 | 98 | b.HasKey("FollowerUserId", "FollowedUserId"); 99 | 100 | b.HasIndex("FollowedUserId"); 101 | 102 | b.ToTable("Follows"); 103 | }); 104 | 105 | modelBuilder.Entity("Chirper.Data.Types.Post", b => 106 | { 107 | b.Property("Id") 108 | .ValueGeneratedOnAdd() 109 | .HasColumnType("int"); 110 | 111 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 112 | 113 | b.Property("Content") 114 | .HasColumnType("nvarchar(max)"); 115 | 116 | b.Property("CreatedAtUtc") 117 | .HasColumnType("datetime2"); 118 | 119 | b.Property("ReferenceId") 120 | .HasColumnType("uniqueidentifier"); 121 | 122 | b.Property("Title") 123 | .IsRequired() 124 | .HasMaxLength(100) 125 | .HasColumnType("nvarchar(100)"); 126 | 127 | b.Property("UpdatedAtUtc") 128 | .HasColumnType("datetime2"); 129 | 130 | b.Property("UserId") 131 | .HasColumnType("int"); 132 | 133 | b.HasKey("Id"); 134 | 135 | b.HasIndex("ReferenceId") 136 | .IsUnique(); 137 | 138 | b.HasIndex("UserId"); 139 | 140 | b.ToTable("Posts"); 141 | }); 142 | 143 | modelBuilder.Entity("Chirper.Data.Types.PostLike", b => 144 | { 145 | b.Property("PostId") 146 | .HasColumnType("int"); 147 | 148 | b.Property("UserId") 149 | .HasColumnType("int"); 150 | 151 | b.Property("CreatedAtUtc") 152 | .HasColumnType("datetime2"); 153 | 154 | b.HasKey("PostId", "UserId"); 155 | 156 | b.HasIndex("UserId"); 157 | 158 | b.ToTable("PostLikes"); 159 | }); 160 | 161 | modelBuilder.Entity("Chirper.Data.Types.User", b => 162 | { 163 | b.Property("Id") 164 | .ValueGeneratedOnAdd() 165 | .HasColumnType("int"); 166 | 167 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 168 | 169 | b.Property("CreatedAtUtc") 170 | .HasColumnType("datetime2"); 171 | 172 | b.Property("DisplayName") 173 | .IsRequired() 174 | .HasColumnType("nvarchar(max)"); 175 | 176 | b.Property("Password") 177 | .IsRequired() 178 | .HasColumnType("nvarchar(max)"); 179 | 180 | b.Property("ReferenceId") 181 | .HasColumnType("uniqueidentifier"); 182 | 183 | b.Property("Username") 184 | .IsRequired() 185 | .HasColumnType("nvarchar(450)"); 186 | 187 | b.HasKey("Id"); 188 | 189 | b.HasIndex("ReferenceId") 190 | .IsUnique(); 191 | 192 | b.HasIndex("Username") 193 | .IsUnique(); 194 | 195 | b.ToTable("Users"); 196 | }); 197 | 198 | modelBuilder.Entity("Chirper.Data.Types.Comment", b => 199 | { 200 | b.HasOne("Chirper.Data.Types.Post", "Post") 201 | .WithMany("Comments") 202 | .HasForeignKey("PostId") 203 | .OnDelete(DeleteBehavior.NoAction) 204 | .IsRequired(); 205 | 206 | b.HasOne("Chirper.Data.Types.Comment", "ReplyToComment") 207 | .WithMany("Replies") 208 | .HasForeignKey("ReplyToCommentId") 209 | .OnDelete(DeleteBehavior.NoAction); 210 | 211 | b.HasOne("Chirper.Data.Types.User", "User") 212 | .WithMany("Comments") 213 | .HasForeignKey("UserId") 214 | .OnDelete(DeleteBehavior.NoAction) 215 | .IsRequired(); 216 | 217 | b.Navigation("Post"); 218 | 219 | b.Navigation("ReplyToComment"); 220 | 221 | b.Navigation("User"); 222 | }); 223 | 224 | modelBuilder.Entity("Chirper.Data.Types.CommentLike", b => 225 | { 226 | b.HasOne("Chirper.Data.Types.Comment", "Comment") 227 | .WithMany("Likes") 228 | .HasForeignKey("CommentId") 229 | .OnDelete(DeleteBehavior.NoAction) 230 | .IsRequired(); 231 | 232 | b.HasOne("Chirper.Data.Types.User", "User") 233 | .WithMany("LikedComments") 234 | .HasForeignKey("UserId") 235 | .OnDelete(DeleteBehavior.NoAction) 236 | .IsRequired(); 237 | 238 | b.Navigation("Comment"); 239 | 240 | b.Navigation("User"); 241 | }); 242 | 243 | modelBuilder.Entity("Chirper.Data.Types.Follow", b => 244 | { 245 | b.HasOne("Chirper.Data.Types.User", "FollowedUser") 246 | .WithMany("Followers") 247 | .HasForeignKey("FollowedUserId") 248 | .OnDelete(DeleteBehavior.NoAction) 249 | .IsRequired(); 250 | 251 | b.HasOne("Chirper.Data.Types.User", "FollowerUser") 252 | .WithMany("Following") 253 | .HasForeignKey("FollowerUserId") 254 | .OnDelete(DeleteBehavior.NoAction) 255 | .IsRequired(); 256 | 257 | b.Navigation("FollowedUser"); 258 | 259 | b.Navigation("FollowerUser"); 260 | }); 261 | 262 | modelBuilder.Entity("Chirper.Data.Types.Post", b => 263 | { 264 | b.HasOne("Chirper.Data.Types.User", "User") 265 | .WithMany("Posts") 266 | .HasForeignKey("UserId") 267 | .OnDelete(DeleteBehavior.NoAction) 268 | .IsRequired(); 269 | 270 | b.Navigation("User"); 271 | }); 272 | 273 | modelBuilder.Entity("Chirper.Data.Types.PostLike", b => 274 | { 275 | b.HasOne("Chirper.Data.Types.Post", "Post") 276 | .WithMany("Likes") 277 | .HasForeignKey("PostId") 278 | .OnDelete(DeleteBehavior.NoAction) 279 | .IsRequired(); 280 | 281 | b.HasOne("Chirper.Data.Types.User", "User") 282 | .WithMany("LikedPosts") 283 | .HasForeignKey("UserId") 284 | .OnDelete(DeleteBehavior.NoAction) 285 | .IsRequired(); 286 | 287 | b.Navigation("Post"); 288 | 289 | b.Navigation("User"); 290 | }); 291 | 292 | modelBuilder.Entity("Chirper.Data.Types.Comment", b => 293 | { 294 | b.Navigation("Likes"); 295 | 296 | b.Navigation("Replies"); 297 | }); 298 | 299 | modelBuilder.Entity("Chirper.Data.Types.Post", b => 300 | { 301 | b.Navigation("Comments"); 302 | 303 | b.Navigation("Likes"); 304 | }); 305 | 306 | modelBuilder.Entity("Chirper.Data.Types.User", b => 307 | { 308 | b.Navigation("Comments"); 309 | 310 | b.Navigation("Followers"); 311 | 312 | b.Navigation("Following"); 313 | 314 | b.Navigation("LikedComments"); 315 | 316 | b.Navigation("LikedPosts"); 317 | 318 | b.Navigation("Posts"); 319 | }); 320 | #pragma warning restore 612, 618 321 | } 322 | } 323 | } 324 | -------------------------------------------------------------------------------- /src/Data/Types/Comment.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Data.Types; 2 | 3 | public class Comment : IEntity, IOwnedEntity 4 | { 5 | public int Id { get; private set; } 6 | public Guid ReferenceId { get; private init; } = Guid.NewGuid(); 7 | public required int PostId { get; init; } 8 | public Post Post { get; init; } = null!; 9 | public required int UserId { get; init; } 10 | public User User { get; init; } = null!; 11 | public required string Content { get; set; } 12 | public int? ReplyToCommentId { get; init; } 13 | public Comment? ReplyToComment { get; init; } 14 | public DateTime CreatedAtUtc { get; private init; } = DateTime.UtcNow; 15 | public DateTime? UpdatedAtUtc { get; set; } 16 | public List Replies { get; init; } = []; 17 | public List Likes { get; init; } = []; 18 | } 19 | 20 | public class CommentLike : IOwnedEntity 21 | { 22 | public required int CommentId { get; init; } 23 | public Comment Comment { get; init; } = null!; 24 | 25 | public required int UserId { get; init; } 26 | public User User { get; init; } = null!; 27 | 28 | public DateTime CreatedAtUtc { get; private init; } = DateTime.UtcNow; 29 | } -------------------------------------------------------------------------------- /src/Data/Types/IEntity.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Data.Types; 2 | 3 | public interface IEntity 4 | { 5 | int Id { get; } 6 | Guid ReferenceId { get; } 7 | } 8 | 9 | public interface IOwnedEntity 10 | { 11 | int UserId { get; } 12 | } -------------------------------------------------------------------------------- /src/Data/Types/Post.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Data.Types; 2 | 3 | public class Post : IEntity, IOwnedEntity 4 | { 5 | public int Id { get; private set; } 6 | public Guid ReferenceId { get; private init; } = Guid.NewGuid(); 7 | public required string Title { get; set; } 8 | public string? Content { get; set; } 9 | public required int UserId { get; init; } 10 | public User User { get; init; } = null!; 11 | public DateTime CreatedAtUtc { get; private init; } = DateTime.UtcNow; 12 | public DateTime? UpdatedAtUtc { get; set; } 13 | public List Likes { get; init; } = []; 14 | public List Comments { get; init; } = []; 15 | } -------------------------------------------------------------------------------- /src/Data/Types/PostLike.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Data.Types; 2 | 3 | public class PostLike : IOwnedEntity 4 | { 5 | public required int PostId { get; init; } 6 | public Post Post { get; init; } = null!; 7 | public required int UserId { get; init; } 8 | public User User { get; init; } = null!; 9 | public DateTime CreatedAtUtc { get; private init; } = DateTime.UtcNow; 10 | } -------------------------------------------------------------------------------- /src/Data/Types/User.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Data.Types; 2 | 3 | public class User : IEntity 4 | { 5 | public int Id { get; private init; } 6 | public Guid ReferenceId { get; private init; } = Guid.NewGuid(); 7 | public required string Username { get; set; } 8 | public required string Password { get; set; } 9 | public required string DisplayName { get; set; } 10 | public DateTime CreatedAtUtc { get; private init; } = DateTime.UtcNow; 11 | public List Posts { get; init; } = []; 12 | public List LikedPosts { get; init; } = []; 13 | public List Comments { get; init; } = []; 14 | public List LikedComments { get; init; } = []; 15 | public List Following { get; init; } = []; 16 | public List Followers { get; init; } = []; 17 | } 18 | 19 | public class Follow 20 | { 21 | public required int FollowerUserId { get; init; } 22 | public User FollowerUser { get; init; } = null!; 23 | 24 | public required int FollowedUserId { get; init; } 25 | public User FollowedUser { get; init; } = null!; 26 | 27 | public DateTime CreatedAtUtc { get; private init; } = DateTime.UtcNow; 28 | } -------------------------------------------------------------------------------- /src/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base 4 | USER app 5 | WORKDIR /app 6 | EXPOSE 8080 7 | EXPOSE 8081 8 | 9 | FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build 10 | ARG BUILD_CONFIGURATION=Release 11 | WORKDIR /src 12 | COPY ["Chirper.csproj", "."] 13 | RUN dotnet restore "./././Chirper.csproj" 14 | COPY . . 15 | WORKDIR "/src/." 16 | RUN dotnet build "./Chirper.csproj" -c $BUILD_CONFIGURATION -o /app/build 17 | 18 | FROM build AS publish 19 | ARG BUILD_CONFIGURATION=Release 20 | RUN dotnet publish "./Chirper.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false 21 | 22 | FROM base AS final 23 | WORKDIR /app 24 | COPY --from=publish /app/publish . 25 | ENTRYPOINT ["dotnet", "Chirper.dll"] -------------------------------------------------------------------------------- /src/Endpoints.cs: -------------------------------------------------------------------------------- 1 | using Chirper.Authentication.Endpoints; 2 | using Chirper.Comments.Endpoints; 3 | using Chirper.Common.Api.Filters; 4 | using Chirper.Posts.Endpoints; 5 | using Chirper.Users.Endpoints; 6 | using Microsoft.AspNetCore.Authentication.JwtBearer; 7 | using Microsoft.OpenApi.Models; 8 | 9 | namespace Chirper; 10 | 11 | public static class Endpoints 12 | { 13 | private static readonly OpenApiSecurityScheme securityScheme = new() 14 | { 15 | Type = SecuritySchemeType.Http, 16 | Name = JwtBearerDefaults.AuthenticationScheme, 17 | Scheme = JwtBearerDefaults.AuthenticationScheme, 18 | Reference = new() 19 | { 20 | Type = ReferenceType.SecurityScheme, 21 | Id = JwtBearerDefaults.AuthenticationScheme 22 | } 23 | }; 24 | 25 | public static void MapEndpoints(this WebApplication app) 26 | { 27 | var endpoints = app.MapGroup("") 28 | .AddEndpointFilter() 29 | .WithOpenApi(); 30 | 31 | endpoints.MapAuthenticationEndpoints(); 32 | endpoints.MapPostEndpoints(); 33 | endpoints.MapCommentEndpoints(); 34 | endpoints.MapUserEndpoints(); 35 | } 36 | 37 | private static void MapAuthenticationEndpoints(this IEndpointRouteBuilder app) 38 | { 39 | var endpoints = app.MapGroup("/auth") 40 | .WithTags("Authentication"); 41 | 42 | endpoints.MapPublicGroup() 43 | .MapEndpoint() 44 | .MapEndpoint(); 45 | } 46 | 47 | private static void MapPostEndpoints(this IEndpointRouteBuilder app) 48 | { 49 | var endpoints = app.MapGroup("/posts") 50 | .WithTags("Posts"); 51 | 52 | endpoints.MapPublicGroup() 53 | .MapEndpoint() 54 | .MapEndpoint() 55 | .MapEndpoint(); 56 | 57 | endpoints.MapAuthorizedGroup() 58 | .MapEndpoint() 59 | .MapEndpoint() 60 | .MapEndpoint() 61 | .MapEndpoint() 62 | .MapEndpoint(); 63 | } 64 | 65 | private static void MapCommentEndpoints(this IEndpointRouteBuilder app) 66 | { 67 | var endpoints = app.MapGroup("/comments") 68 | .WithTags("Comments"); 69 | 70 | endpoints.MapPublicGroup() 71 | .MapEndpoint(); 72 | 73 | endpoints.MapAuthorizedGroup() 74 | .MapEndpoint() 75 | .MapEndpoint() 76 | .MapEndpoint(); 77 | } 78 | 79 | private static void MapUserEndpoints(this IEndpointRouteBuilder app) 80 | { 81 | var endpoints = app.MapGroup("/users") 82 | .WithTags("Users"); 83 | 84 | endpoints.MapPublicGroup() 85 | .MapEndpoint() 86 | .MapEndpoint() 87 | .MapEndpoint() 88 | .MapEndpoint() 89 | .MapEndpoint() 90 | .MapEndpoint(); 91 | 92 | endpoints.MapAuthorizedGroup() 93 | .MapEndpoint() 94 | .MapEndpoint(); 95 | } 96 | 97 | private static RouteGroupBuilder MapPublicGroup(this IEndpointRouteBuilder app, string? prefix = null) 98 | { 99 | return app.MapGroup(prefix ?? string.Empty) 100 | .AllowAnonymous(); 101 | } 102 | 103 | private static RouteGroupBuilder MapAuthorizedGroup(this IEndpointRouteBuilder app, string? prefix = null) 104 | { 105 | return app.MapGroup(prefix ?? string.Empty) 106 | .RequireAuthorization() 107 | .WithOpenApi(x => new(x) 108 | { 109 | Security = [new() { [securityScheme] = [] }], 110 | }); 111 | } 112 | 113 | private static IEndpointRouteBuilder MapEndpoint(this IEndpointRouteBuilder app) where TEndpoint : IEndpoint 114 | { 115 | TEndpoint.Map(app); 116 | return app; 117 | } 118 | } -------------------------------------------------------------------------------- /src/Posts/Endpoints/CreatePost.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Posts.Endpoints; 2 | 3 | public class CreatePost : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapPost("/", Handle) 7 | .WithSummary("Creates a new post") 8 | .WithRequestValidation(); 9 | 10 | public record Request(string Title, string? Content); 11 | public record Response(int Id); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Title) 17 | .NotEmpty() 18 | .MaximumLength(100); 19 | } 20 | } 21 | 22 | private static async Task> Handle(Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 23 | { 24 | var post = new Post 25 | { 26 | Title = request.Title, 27 | Content = request.Content, 28 | UserId = claimsPrincipal.GetUserId() 29 | }; 30 | 31 | await database.Posts.AddAsync(post, cancellationToken); 32 | await database.SaveChangesAsync(cancellationToken); 33 | var response = new Response(post.Id); 34 | return TypedResults.Ok(response); 35 | } 36 | } -------------------------------------------------------------------------------- /src/Posts/Endpoints/DeletePost.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Posts.Endpoints; 2 | 3 | public class DeletePost : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapDelete("/{id}", Handle) 7 | .WithSummary("Deletes a post") 8 | .WithRequestValidation() 9 | .WithEnsureUserOwnsEntity(x => x.Id); 10 | 11 | public record Request(int Id); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | 20 | private static async Task> Handle([AsParameters] Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 21 | { 22 | var rowsDeleted = await database.Posts 23 | .Where(x => x.Id == request.Id) 24 | .ExecuteDeleteAsync(cancellationToken); 25 | 26 | return rowsDeleted == 1 27 | ? TypedResults.Ok() 28 | : TypedResults.NotFound(); 29 | } 30 | } -------------------------------------------------------------------------------- /src/Posts/Endpoints/GetPostById.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Posts.Endpoints; 2 | 3 | public class GetPostById : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}", Handle) 7 | .WithSummary("Gets a post by id") 8 | .WithRequestValidation(); 9 | 10 | public record Request(int Id); 11 | public class RequestValidator : AbstractValidator 12 | { 13 | public RequestValidator() 14 | { 15 | RuleFor(x => x.Id).GreaterThan(0); 16 | } 17 | } 18 | public record Response( 19 | int Id, 20 | string Title, 21 | string? Content, 22 | int UserId, 23 | string Username, 24 | string UserDisplayName, 25 | DateTime CreateAtUtc, 26 | DateTime? UpdatedAtUtc, 27 | int LikesCount, 28 | int CommentsCount 29 | ); 30 | 31 | private static async Task, NotFound>> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 32 | { 33 | var post = await database.Posts 34 | .Where(x => x.Id == request.Id) 35 | .Select(x => new Response 36 | ( 37 | x.Id, 38 | x.Title, 39 | x.Content, 40 | x.UserId, 41 | x.User.Username, 42 | x.User.DisplayName, 43 | x.CreatedAtUtc, 44 | x.UpdatedAtUtc, 45 | x.Likes.Count, 46 | x.Comments.Count 47 | )) 48 | .SingleOrDefaultAsync(cancellationToken); 49 | 50 | return post is null 51 | ? TypedResults.NotFound() 52 | : TypedResults.Ok(post); 53 | } 54 | } -------------------------------------------------------------------------------- /src/Posts/Endpoints/GetPostComments.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Posts.Endpoints; 2 | 3 | public class GetPostComments : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}/comments", Handle) 7 | .WithSummary("Get a post's top level comments") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id, int? Page, int? PageSize) : IPagedRequest; 12 | public class RequestValidator : PagedRequestValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | public record Response(int Id, int UserId, string Username, string DisplayName, string Content, DateTime CreatedAtUtc, DateTime? UpdatedAtUtc, int LikesCount, int RepliesCount); 20 | 21 | public static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 22 | { 23 | return await database.Comments 24 | .Where(x => x.PostId == request.Id && x.ReplyToCommentId == null) 25 | .OrderByDescending(x => x.CreatedAtUtc) 26 | .Select(x => new Response 27 | ( 28 | x.Id, 29 | x.UserId, 30 | x.User.Username, 31 | x.User.DisplayName, 32 | x.Content, 33 | x.CreatedAtUtc, 34 | x.UpdatedAtUtc, 35 | x.Likes.Count, 36 | x.Replies.Count 37 | )) 38 | .ToPagedListAsync(request, cancellationToken); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Posts/Endpoints/GetPosts.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Posts.Endpoints; 2 | 3 | public class GetPosts : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/", Handle) 7 | .WithSummary("Gets all posts") 8 | .WithRequestValidation(); 9 | 10 | public record Request(int? Page, int? PageSize) : IPagedRequest; 11 | public class RequestValidator : PagedRequestValidator; 12 | public record Response( 13 | int Id, 14 | string Title, 15 | string? Content, 16 | int UserId, 17 | string Username, 18 | string UserDisplayName, 19 | DateTime CreateAtUtc, 20 | DateTime? UpdatedAtUtc, 21 | int LikesCount, 22 | int CommentsCount 23 | ); 24 | 25 | private static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 26 | { 27 | return await database.Posts 28 | .Select(x => new Response 29 | ( 30 | x.Id, 31 | x.Title, 32 | x.Content, 33 | x.UserId, 34 | x.User.Username, 35 | x.User.DisplayName, 36 | x.CreatedAtUtc, 37 | x.UpdatedAtUtc, 38 | x.Likes.Count, 39 | x.Comments.Count 40 | )) 41 | .ToPagedListAsync(request, cancellationToken); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Posts/Endpoints/LikePost.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Posts.Endpoints; 2 | 3 | public class LikePost : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapPost("/{id}/like", Handle) 7 | .WithSummary("Likes a post") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | 20 | private static async Task Handle([AsParameters] Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 21 | { 22 | var userId = claimsPrincipal.GetUserId(); 23 | var doesLikeExist = await database.PostLikes.AnyAsync(x => x.PostId == request.Id && x.UserId == userId, cancellationToken); 24 | if (doesLikeExist) 25 | { 26 | return TypedResults.Ok(); 27 | } 28 | 29 | var like = new PostLike 30 | { 31 | PostId = request.Id, 32 | UserId = userId 33 | }; 34 | await database.PostLikes.AddAsync(like, cancellationToken); 35 | await database.SaveChangesAsync(cancellationToken); 36 | return TypedResults.Ok(); 37 | } 38 | } -------------------------------------------------------------------------------- /src/Posts/Endpoints/UnlikePost.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Posts.Endpoints; 2 | 3 | public class UnlikePost : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapDelete("/{id}/unlike", Handle) 7 | .WithSummary("Unlikes a post") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | 20 | private static async Task> Handle([AsParameters] Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 21 | { 22 | var userId = claimsPrincipal.GetUserId(); 23 | 24 | var rowsDeleted = await database.PostLikes 25 | .Where(x => x.PostId == request.Id && x.UserId == userId) 26 | .ExecuteDeleteAsync(cancellationToken); 27 | 28 | return rowsDeleted == 0 29 | ? TypedResults.NotFound() 30 | : TypedResults.Ok(); 31 | } 32 | } -------------------------------------------------------------------------------- /src/Posts/Endpoints/UpdatePost.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Posts.Endpoints; 2 | 3 | public class UpdatePost : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapPut("/", Handle) 7 | .WithSummary("Updates a post") 8 | .WithRequestValidation() 9 | .WithEnsureUserOwnsEntity(x => x.Id); 10 | 11 | public record Request(int Id, string Title, string? Content); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | RuleFor(x => x.Title) 18 | .NotEmpty() 19 | .MaximumLength(100); 20 | } 21 | } 22 | 23 | private static async Task Handle(Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 24 | { 25 | var post = await database.Posts.SingleAsync(x => x.Id == request.Id, cancellationToken); 26 | post.Title = request.Title; 27 | post.Content = request.Content; 28 | post.UpdatedAtUtc = DateTime.UtcNow; 29 | await database.SaveChangesAsync(cancellationToken); 30 | 31 | // TODO: Publish post updated event 32 | 33 | return TypedResults.Ok(); 34 | } 35 | } -------------------------------------------------------------------------------- /src/Program.cs: -------------------------------------------------------------------------------- 1 | global using Chirper.Common.Api; 2 | global using Chirper.Common.Api.Extensions; 3 | global using Chirper.Common.Api.Requests; 4 | global using Chirper.Common.Api.Results; 5 | global using Chirper.Data; 6 | global using Chirper.Data.Types; 7 | global using FluentValidation; 8 | global using Microsoft.AspNetCore.Http.HttpResults; 9 | global using Microsoft.EntityFrameworkCore; 10 | global using System.Security.Claims; 11 | using Chirper; 12 | using Serilog; 13 | 14 | 15 | Log.Logger = new LoggerConfiguration() 16 | .WriteTo.Console() 17 | .CreateBootstrapLogger(); 18 | 19 | try 20 | { 21 | Log.Information("Starting web application"); 22 | var builder = WebApplication.CreateBuilder(args); 23 | builder.AddServices(); 24 | var app = builder.Build(); 25 | await app.Configure(); 26 | app.Run(); 27 | } 28 | catch (Exception ex) 29 | { 30 | Log.Fatal(ex, "Application terminated unexpectedly"); 31 | } 32 | finally 33 | { 34 | Log.CloseAndFlush(); 35 | } -------------------------------------------------------------------------------- /src/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "http": { 4 | "commandName": "Project", 5 | "launchBrowser": true, 6 | "launchUrl": "swagger", 7 | "environmentVariables": { 8 | "ASPNETCORE_ENVIRONMENT": "Development" 9 | }, 10 | "dotnetRunMessages": true, 11 | "applicationUrl": "http://localhost:5026" 12 | }, 13 | "https": { 14 | "commandName": "Project", 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | }, 20 | "dotnetRunMessages": true, 21 | "applicationUrl": "https://localhost:7128;http://localhost:5026" 22 | }, 23 | "IIS Express": { 24 | "commandName": "IISExpress", 25 | "launchBrowser": true, 26 | "launchUrl": "swagger", 27 | "environmentVariables": { 28 | "ASPNETCORE_ENVIRONMENT": "Development" 29 | } 30 | }, 31 | "Docker": { 32 | "commandName": "Docker", 33 | "launchBrowser": true, 34 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", 35 | "environmentVariables": { 36 | "ASPNETCORE_HTTPS_PORTS": "8081", 37 | "ASPNETCORE_HTTP_PORTS": "8080" 38 | }, 39 | "publishAllPorts": true, 40 | "useSSL": true 41 | } 42 | }, 43 | "$schema": "http://json.schemastore.org/launchsettings.json", 44 | "iisSettings": { 45 | "windowsAuthentication": false, 46 | "anonymousAuthentication": true, 47 | "iisExpress": { 48 | "applicationUrl": "http://localhost:12760", 49 | "sslPort": 44315 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /src/Users/Endpoints/FollowUser.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Users.Endpoints; 2 | 3 | public class FollowUser : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapPost("/{id}/follow", Handle) 7 | .WithSummary("Follows a user") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | 20 | private static async Task> Handle([AsParameters] Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 21 | { 22 | var userId = claimsPrincipal.GetUserId(); 23 | 24 | if (userId == request.Id) 25 | { 26 | return new ValidationError("You cannot follow yourself."); 27 | } 28 | 29 | var isAlreadyFollowing = await database.Follows.AnyAsync(x => 30 | x.FollowerUserId == userId && 31 | x.FollowedUserId == request.Id, 32 | cancellationToken 33 | ); 34 | 35 | if (isAlreadyFollowing) 36 | { 37 | return new ValidationError("You are already following this user."); 38 | } 39 | 40 | var follow = new Follow 41 | { 42 | FollowerUserId = userId, 43 | FollowedUserId = request.Id 44 | }; 45 | 46 | // TODO: Send a notification to the user being followed 47 | 48 | await database.Follows.AddAsync(follow, cancellationToken); 49 | await database.SaveChangesAsync(cancellationToken); 50 | return TypedResults.Ok(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Users/Endpoints/GetUserComments.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Users.Endpoints; 2 | 3 | public class GetUserComments : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}/comments", Handle) 7 | .WithSummary("Get a user's comments") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id, int? Page, int? PageSize) : IPagedRequest; 12 | public class RequestValidator : PagedRequestValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | public record Response( 20 | int Id, 21 | int PostId, 22 | string Content, 23 | DateTime CreatedAtUtc, 24 | DateTime? UpdatedAtUtc, 25 | int LikesCount, 26 | int RepliesCount 27 | ); 28 | 29 | public static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 30 | { 31 | return await database.Comments 32 | .Where(x => x.UserId == request.Id) 33 | .OrderByDescending(x => x.CreatedAtUtc) 34 | .Select(x => new Response 35 | ( 36 | x.Id, 37 | x.PostId, 38 | x.Content, 39 | x.CreatedAtUtc, 40 | x.UpdatedAtUtc, 41 | x.Likes.Count, 42 | x.Replies.Count 43 | )) 44 | .ToPagedListAsync(request, cancellationToken); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Users/Endpoints/GetUserFollowers.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Users.Endpoints; 2 | 3 | public class GetUserFollowers : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}/followers", Handle) 7 | .WithSummary("Get a user's followers") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id, int? Page, int? PageSize) : IPagedRequest; 12 | public class RequestValidator : PagedRequestValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | 20 | public record Response(int Id, string Username, string Name, DateTime CreatedAtUtc); 21 | 22 | private static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 23 | { 24 | return await database.Follows 25 | .Where(x => x.FollowedUserId == request.Id) 26 | .OrderByDescending(x => x.CreatedAtUtc) 27 | .Select(x => new Response 28 | ( 29 | x.FollowerUser.Id, 30 | x.FollowerUser.Username, 31 | x.FollowerUser.DisplayName, 32 | x.CreatedAtUtc 33 | )) 34 | .ToPagedListAsync(request, cancellationToken); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Users/Endpoints/GetUserFollowing.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Users.Endpoints; 2 | 3 | public class GetUserFollowing : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}/following", Handle) 7 | .WithSummary("Get a user's following list") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id, int? Page, int? PageSize) : IPagedRequest; 12 | public class RequestValidator : PagedRequestValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | public record Response(int Id, string Username, string DisplayName, DateTime CreatedAtUtc); 20 | 21 | public static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 22 | { 23 | return await database.Follows 24 | .Where(x => x.FollowerUserId == request.Id) 25 | .OrderByDescending(x => x.CreatedAtUtc) 26 | .Select(x => new Response 27 | ( 28 | x.FollowedUserId, 29 | x.FollowedUser.Username, 30 | x.FollowedUser.DisplayName, 31 | x.CreatedAtUtc 32 | )) 33 | .ToPagedListAsync(request, cancellationToken); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Users/Endpoints/GetUserLikedComments.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Users.Endpoints; 2 | 3 | public class GetUserLikedComments : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}/liked-comments", Handle) 7 | .WithSummary("Get a user's liked comments") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id, int? Page, int? PageSize) : IPagedRequest; 12 | public class RequestValidator : PagedRequestValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | public record Response( 20 | int Id, 21 | int PostId, 22 | int UserId, 23 | string Username, 24 | string DisplayName, 25 | string Content, 26 | DateTime CreatedAtUtc, 27 | DateTime? UpdatedAtUtc, 28 | int LikesCount, 29 | int RepliesCount, 30 | DateTime LikedAtUtc 31 | ); 32 | 33 | public static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 34 | { 35 | return await database.CommentLikes 36 | .Where(x => x.UserId == request.Id) 37 | .OrderByDescending(x => x.CreatedAtUtc) 38 | .Select(x => new Response 39 | ( 40 | x.CommentId, 41 | x.Comment.PostId, 42 | x.Comment.UserId, 43 | x.Comment.User.Username, 44 | x.Comment.User.DisplayName, 45 | x.Comment.Content, 46 | x.Comment.CreatedAtUtc, 47 | x.Comment.UpdatedAtUtc, 48 | x.Comment.Likes.Count, 49 | x.Comment.Replies.Count, 50 | x.CreatedAtUtc 51 | )) 52 | .ToPagedListAsync(request, cancellationToken); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Users/Endpoints/GetUserLikedPosts.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Users.Endpoints; 2 | 3 | public class GetUserLikedPosts : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}/liked-posts", Handle) 7 | .WithSummary("Get a user's liked posts") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id, int? Page, int? PageSize) : IPagedRequest; 12 | public class RequestValidator : PagedRequestValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | public record Response( 20 | int Id, 21 | int UserId, 22 | string? Content, 23 | DateTime CreatedAtUtc, 24 | DateTime? UpdatedAtUtc, 25 | int LikesCount, 26 | int CommentsCount, 27 | DateTime LikedAtUtc 28 | ); 29 | 30 | public static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 31 | { 32 | return await database.PostLikes 33 | .Where(x => x.UserId == request.Id) 34 | .OrderByDescending(x => x.CreatedAtUtc) 35 | .Select(x => new Response 36 | ( 37 | x.PostId, 38 | x.Post.UserId, 39 | x.Post.Content, 40 | x.Post.CreatedAtUtc, 41 | x.Post.UpdatedAtUtc, 42 | x.Post.Likes.Count, 43 | x.Post.Comments.Count, 44 | x.CreatedAtUtc 45 | )) 46 | .ToPagedListAsync(request, cancellationToken); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Users/Endpoints/GetUserPosts.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Users.Endpoints; 2 | 3 | public class GetUserPosts : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapGet("/{id}/posts", Handle) 7 | .WithSummary("Get a user's posts") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id, int? Page, int? PageSize) : IPagedRequest; 12 | public class RequestValidator : PagedRequestValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | public record Response(int Id, string Title, string? Content, DateTime CreatedAtUtc, DateTime? UpdatedAtUtc, int LikesCount, int CommentsCount); 20 | 21 | public static async Task> Handle([AsParameters] Request request, AppDbContext database, CancellationToken cancellationToken) 22 | { 23 | return await database.Posts 24 | .Where(x => x.UserId == request.Id) 25 | .OrderByDescending(x => x.CreatedAtUtc) 26 | .Select(x => new Response 27 | ( 28 | x.Id, 29 | x.Title, 30 | x.Content, 31 | x.CreatedAtUtc, 32 | x.UpdatedAtUtc, 33 | x.Likes.Count, 34 | x.Comments.Count 35 | )) 36 | .ToPagedListAsync(request, cancellationToken); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Users/Endpoints/UnfollowUser.cs: -------------------------------------------------------------------------------- 1 | namespace Chirper.Users.Endpoints; 2 | 3 | public class UnfollowUser : IEndpoint 4 | { 5 | public static void Map(IEndpointRouteBuilder app) => app 6 | .MapDelete("/{id}/unfollow", Handle) 7 | .WithSummary("Unfollows a user") 8 | .WithRequestValidation() 9 | .WithEnsureEntityExists(x => x.Id); 10 | 11 | public record Request(int Id); 12 | public class RequestValidator : AbstractValidator 13 | { 14 | public RequestValidator() 15 | { 16 | RuleFor(x => x.Id).GreaterThan(0); 17 | } 18 | } 19 | 20 | public static async Task> Handle([AsParameters] Request request, AppDbContext database, ClaimsPrincipal claimsPrincipal, CancellationToken cancellationToken) 21 | { 22 | var userId = claimsPrincipal.GetUserId(); 23 | if (userId == request.Id) 24 | { 25 | return new ValidationError("You cannot unfollow yourself."); 26 | } 27 | 28 | var rowsDeleted = await database.Follows 29 | .Where(x => x.FollowerUserId == userId && x.FollowedUserId == request.Id) 30 | .ExecuteDeleteAsync(cancellationToken); 31 | 32 | if (rowsDeleted == 0) 33 | { 34 | return new ValidationError("You are not following this user."); 35 | } 36 | 37 | // TODO: Publish event of an unfollow to decrement the follower count 38 | 39 | return TypedResults.Ok(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Serilog": { 3 | "MinimumLevel": { 4 | "Default": "Information", 5 | "Override": { 6 | "Microsoft": "Information", 7 | "System": "Warning" 8 | } 9 | }, 10 | "WriteTo": [ "Console" ] 11 | }, 12 | "AllowedHosts": "*", 13 | "ConnectionStrings": { 14 | "Default": "Server=.;Database=Chirper;Trusted_Connection=True;Encrypt=False;" 15 | }, 16 | "Jwt": { 17 | "Key": "superdupersecretkeythatsreallyreallylong" 18 | } 19 | } 20 | --------------------------------------------------------------------------------