Skip to content

Commit

Permalink
Merge pull request #20 from Purdue-ACM-SIGAPP/User
Browse files Browse the repository at this point in the history
User Entity Class and Controller Class Implemented
  • Loading branch information
AndrewZacharyLiu authored Oct 10, 2024
2 parents eedc62d + d32ab72 commit 167bc9d
Show file tree
Hide file tree
Showing 3 changed files with 159 additions and 0 deletions.
126 changes: 126 additions & 0 deletions Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
using Microsoft.AspNetCore.Mvc;
using SimpleWebAppReact.Entities;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using SimpleWebAppReact.Services;

namespace SimpleWebAppReact.Controllers
{
/// <summary>
/// Defines endpoints for operations relating the User table
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
private readonly ILogger<UserController> _logger;
private readonly IMongoCollection<User>? _users;

public UserController(ILogger<UserController> logger, MongoDbService mongoDbService)
{
_logger = logger;
_users = mongoDbService.Database?.GetCollection<User>("user");
}

/// <summary>
/// gets user, with optional query parameters
/// </summary>
/// <param name="name"></param>
/// <param name="phoneNumber"></param>
/// <param name="accountType"></param>
/// <returns></returns>
[HttpGet]
public async Task<IEnumerable<User>> Get([FromQuery] string? name = null, [FromQuery] string? phoneNumber = null, [FromQuery] int? accountType = null)
{
// Build the filter using a filter builder
var filterBuilder = Builders<User>.Filter;
var filter = FilterDefinition<User>.Empty;

// Apply the name filter if the parameter is provided
if (!string.IsNullOrEmpty(name))
{
filter &= filterBuilder.Eq(b => b.Name, name);
}

// Apply the phoneNumber filter if the parameter is provided
if (!string.IsNullOrEmpty(phoneNumber))
{
filter &= filterBuilder.Eq(b => b.PhoneNumber, phoneNumber);
}

// Apply the accountType filter if the parameter is provided,
// an account type too high or low will be ignored
if (accountType != null)
{
int max = Enum.GetValues(typeof(UserType)).Cast<int>().Max();
int min = Enum.GetValues(typeof(UserType)).Cast<int>().Min();
if (accountType >= min || accountType <= max)
{
filter &= filterBuilder.Eq(b => b.AccountType, accountType);
}
}

// Fetch the users from the database using the filter
return await _users.Find(filter).ToListAsync();
}

/// <summary>
/// gets specific user with id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<ActionResult<User?>> GetById(string id)

Check warning on line 73 in Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / test

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
// Simple validation to check if the ID is not null
if (string.IsNullOrEmpty(id))
{
return BadRequest("Invalid ID format.");
}

var filter = Builders<User>.Filter.Eq(x => x.Id, id);
var user = _users.Find(filter).FirstOrDefault();
return user is not null ? Ok(user) : NotFound();
}

/// <summary>
/// adds user entry to table
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult> Post(User user)
{
await _users.InsertOneAsync(user);

Check warning on line 94 in Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / test

Dereference of a possibly null reference.
return CreatedAtAction(nameof(GetById), new { id = user.Id }, user);

}

/// <summary>
/// updates a user entry
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
[HttpPut]
public async Task<ActionResult> Update(User user)
{
var filter = Builders<User>.Filter.Eq(x => x.Id, user.Id);
await _users.ReplaceOneAsync(filter, user);

Check warning on line 108 in Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / test

Dereference of a possibly null reference.
return Ok();
}

/// <summary>
/// deletes a user entry
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(string id)
{
var filter = Builders<User>.Filter.Eq(x => x.Id, id);
await _users.DeleteOneAsync(filter);
return Ok();
}
}
}

21 changes: 21 additions & 0 deletions Entities/User.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace SimpleWebAppReact.Entities;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
/// <summary>
/// Class structure matches 1-1 with User Table in database
/// </summary>
public class User
{
[BsonId]
[BsonElement("_id"), BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }

[BsonElement("name"), BsonRepresentation(BsonType.String)]
public string? Name { get; set; }

[BsonElement("phoneNumber"), BsonRepresentation(BsonType.String)]
public string? PhoneNumber { get; set; }

[BsonElement("accountType"), BsonRepresentation(BsonType.Int32)]
public int? AccountType { get; set; }
}
12 changes: 12 additions & 0 deletions Entities/UserType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace SimpleWebAppReact.Entities;
/// <summary>
/// Enum containing all possible account types
/// </summary>
public enum UserType
{
Student,
ResidentAssistant,
GreekLife,
Landlord,
Admin
}

0 comments on commit 167bc9d

Please sign in to comment.