UserController.cs (2472B)
1 using Api.Data; 2 using Api.Models; 3 using Microsoft.AspNetCore.Mvc; 4 using Shared; 5 using Shared.Contracts; 6 7 namespace Api.Controllers; 8 9 [Route(Endpoints.Users)] 10 [ApiController] 11 public class UserController : ControllerBase 12 { 13 private readonly AppDbContext _context; 14 15 public UserController(AppDbContext context) 16 { 17 _context = context; 18 } 19 20 [HttpGet] 21 public IActionResult Get() 22 { 23 var userDataList = _context.Users 24 .Select(user => new UserData 25 { 26 Username = user.Name, 27 CreatedAt = user.CreatedAt 28 }) 29 .ToList(); 30 31 var userContract = new GetUsersContract { users = userDataList }; 32 33 return Ok(userContract); 34 } 35 36 [HttpGet] 37 [Route("{id}")] 38 public IActionResult Get(Guid id) 39 { 40 var user = _context.Users.Find(id); 41 if (user == null) 42 { 43 return NotFound($"Could not find user {id}"); 44 } 45 46 return Ok(user); 47 } 48 49 [HttpPost] 50 public IActionResult Post([FromBody] UserContract userContract) 51 { 52 var baseUsername = userContract.Username; 53 string preferredName; 54 var attempts = 0; 55 Random random = new Random(); 56 HashSet<string> triedUsernames = new HashSet<string>(); 57 58 do 59 { 60 var randomNumber = random.Next(0, 9999); 61 preferredName = $"{baseUsername}#{randomNumber:D4}"; 62 63 if (triedUsernames.Contains(preferredName)) 64 { 65 continue; 66 } 67 68 attempts++; 69 triedUsernames.Add(preferredName); 70 71 if (attempts > 9999) 72 { 73 return BadRequest("Username already taken"); 74 } 75 76 } while (_context.Users.Any(user => user.Name == preferredName)); 77 78 var user = new User { Name = preferredName }; 79 80 _context.Users.Add(user); 81 _context.SaveChanges(); 82 83 NewUserContract newUserContract = new NewUserContract 84 { 85 Name = user.Name, 86 Key = user.Key, 87 CreatedAt = user.CreatedAt 88 }; 89 90 return Ok(newUserContract); 91 } 92 93 [HttpDelete("{id}")] 94 public IActionResult Delete(Guid id) 95 { 96 var user = _context.Users.Find(id); 97 if (user == null) 98 { 99 return NotFound($"Could not find user {id}"); 100 } 101 102 _context.Users.Remove(user); 103 return Ok($"Removed user {id}"); 104 } 105 }