Skip to content

Commit b64fe65

Browse files
LiverpoolOwenMarkPieszak
authored andcommitted
Web API improvements (TrilonIO#182)
* Removed no longer used API * Pluralised API to "Users" and depluralised model to "User". All UsersAPI's now point to same URI. * Updated web API status codes
1 parent 906af4f commit b64fe65

File tree

6 files changed

+148
-134
lines changed

6 files changed

+148
-134
lines changed

Client/app/containers/users/users.component.ts

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,14 +50,16 @@ export class UsersComponent implements OnInit {
5050
// The Client then re-uses this Http result instead of hitting the server again!
5151

5252
// NOTE : transferHttp also automatically does .map(res => res.json()) for you, so no need for these calls
53-
this.transferHttp.get(`${this.baseUrl}/api/user/all`).subscribe(result => {
54-
console.log('TransferHttp [GET] /api/user/allresult', result);
53+
this.transferHttp.get(`${this.baseUrl}/api/users`).subscribe(result => {
54+
console.log('Get user result: ', result);
55+
console.log('TransferHttp [GET] /api/users/allresult', result);
5556
this.users = result as IUser[];
5657
});
5758
}
5859

5960
deleteUser(user) {
60-
this.http.delete(`${this.baseUrl}/api/user/delete/` + user.id).subscribe(result => {
61+
this.http.delete(`${this.baseUrl}/api/users/` + user.id).subscribe(result => {
62+
console.log('Delete user result: ', result);
6163
if (result.ok) {
6264
let position = this.users.indexOf(user);
6365
this.users.splice(position, 1);
@@ -68,23 +70,17 @@ export class UsersComponent implements OnInit {
6870
}
6971

7072
editUser(user) {
71-
let urlSearchParams = new URLSearchParams();
72-
urlSearchParams.append('id', user.id);
73-
urlSearchParams.append('name', user.name);
74-
75-
this.http.put(`${this.baseUrl}/api/user/update`, urlSearchParams).subscribe(result => {
76-
console.log('result: ', result);
73+
this.http.put(`${this.baseUrl}/api/users/` + user.id, user).subscribe(result => {
74+
console.log('Put user result: ', result);
7775
if (!result) {
7876
alert('There was an issue, Could not edit user');
7977
}
8078
});
8179
}
8280

8381
addUser(newUserName) {
84-
let urlSearchParams = new URLSearchParams();
85-
urlSearchParams.append('name', newUserName);
86-
87-
this.http.post(`${this.baseUrl}/api/user/insert`, urlSearchParams).subscribe(result => {
82+
this.http.post(`${this.baseUrl}/api/users`, { name: newUserName }).subscribe(result => {
83+
console.log('Post user result: ', result);
8884
if (result) {
8985
this.users.push(result.json());
9086
this.newUserName = '';

Server/Data/DbInitializer.cs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,22 @@ public static void Initialize(SpaDbContext context)
1717
{
1818
return; // DB has been seeded
1919
}
20-
var users = new Users[]
20+
var users = new User[]
2121
{
22-
new Users(){Name = "Mark Pieszak"},
23-
new Users(){Name = "Abrar Jahin"},
24-
new Users(){Name = "hakonamatata"},
25-
new Users(){Name = "LiverpoolOwen"},
26-
new Users(){Name = "Ketrex"},
27-
new Users(){Name = "markwhitfeld"},
28-
new Users(){Name = "daveo1001"},
29-
new Users(){Name = "paonath"},
30-
new Users(){Name = "nalex095"},
31-
new Users(){Name = "ORuban"},
32-
new Users(){Name = "Gaulomatic"}
22+
new User(){Name = "Mark Pieszak"},
23+
new User(){Name = "Abrar Jahin"},
24+
new User(){Name = "hakonamatata"},
25+
new User(){Name = "LiverpoolOwen"},
26+
new User(){Name = "Ketrex"},
27+
new User(){Name = "markwhitfeld"},
28+
new User(){Name = "daveo1001"},
29+
new User(){Name = "paonath"},
30+
new User(){Name = "nalex095"},
31+
new User(){Name = "ORuban"},
32+
new User(){Name = "Gaulomatic"}
3333
};
3434

35-
foreach (Users s in users)
35+
foreach (User s in users)
3636
{
3737
context.User.Add(s);
3838
}

Server/Data/SpaDbContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@ public SpaDbContext(DbContextOptions<SpaDbContext> options)
1212
}
1313

1414
//List of DB Models - Add your DB models here
15-
public DbSet<Users> User { get; set; }
15+
public DbSet<User> User { get; set; }
1616
}
1717
}

Server/Models/Users.cs renamed to Server/Models/User.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
namespace AspCoreServer.Models
55
{
6-
public class Users
6+
public class User
77
{
88
public int ID { get; set; }
99
public string Name { get; set; }
@@ -13,7 +13,7 @@ public class Users
1313
public DateTime EntryTime { get; set; }
1414

1515
//Setting Default value
16-
public Users()
16+
public User()
1717
{
1818
EntryTime = DateTime.Now;
1919
}

Server/RestAPI/UserController.cs

Lines changed: 0 additions & 105 deletions
This file was deleted.

Server/RestAPI/UsersController.cs

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
using AspCoreServer.Data;
2+
using AspCoreServer.Models;
3+
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.EntityFrameworkCore;
5+
using System;
6+
using System.Linq;
7+
using System.Threading.Tasks;
8+
9+
namespace AspCoreServer.Controllers
10+
{
11+
[Route("api/[controller]")]
12+
public class UsersController : Controller
13+
{
14+
private readonly SpaDbContext _context;
15+
16+
public UsersController(SpaDbContext context)
17+
{
18+
_context = context;
19+
}
20+
21+
[HttpGet]
22+
public async Task<IActionResult> Get(int currentPageNo = 1, int pageSize = 20)
23+
{
24+
var users = await _context.User
25+
.OrderByDescending(u => u.EntryTime)
26+
.Skip((currentPageNo - 1) * pageSize)
27+
.Take(pageSize)
28+
.ToArrayAsync();
29+
30+
if (!users.Any())
31+
{
32+
return NotFound("Users not Found");
33+
}
34+
else
35+
{
36+
return Ok(users);
37+
}
38+
}
39+
40+
[HttpGet("{id}")]
41+
public async Task<IActionResult> Get(int id)
42+
{
43+
var user = await _context.User
44+
.Where(u => u.ID == id)
45+
.AsNoTracking()
46+
.SingleOrDefaultAsync(m => m.ID == id);
47+
48+
if (user == null)
49+
{
50+
return NotFound("User not Found");
51+
}
52+
else
53+
{
54+
return Ok(user);
55+
}
56+
}
57+
58+
[HttpPost]
59+
public async Task<IActionResult> Post([FromBody]User user)
60+
{
61+
if (!string.IsNullOrEmpty(user.Name))
62+
{
63+
_context.Add(user);
64+
await _context.SaveChangesAsync();
65+
return CreatedAtAction("Post", user);
66+
}
67+
else
68+
{
69+
return BadRequest("User's name was not given");
70+
}
71+
}
72+
73+
[HttpPut("{id}")]
74+
public async Task<IActionResult> Put(int id, [FromBody]User userUpdateValue)
75+
{
76+
try
77+
{
78+
userUpdateValue.EntryTime = DateTime.Now;
79+
80+
var userToEdit = await _context.User
81+
.AsNoTracking()
82+
.SingleOrDefaultAsync(m => m.ID == id);
83+
84+
if (userToEdit == null)
85+
{
86+
return NotFound("Could not update user as it was not Found");
87+
}
88+
else
89+
{
90+
_context.Update(userUpdateValue);
91+
await _context.SaveChangesAsync();
92+
return Ok("Updated user - " + userUpdateValue.Name);
93+
}
94+
}
95+
catch (DbUpdateException)
96+
{
97+
//Log the error (uncomment ex variable name and write a log.)
98+
ModelState.AddModelError("", "Unable to save changes. " +
99+
"Try again, and if the problem persists, " +
100+
"see your system administrator.");
101+
return NotFound("User not Found");
102+
}
103+
}
104+
105+
[HttpDelete("{id}")]
106+
public async Task<IActionResult> Delete(int id)
107+
{
108+
var userToRemove = await _context.User
109+
.AsNoTracking()
110+
.SingleOrDefaultAsync(m => m.ID == id);
111+
if (userToRemove == null)
112+
{
113+
return NotFound("Could not delete user as it was not Found");
114+
}
115+
else
116+
{
117+
_context.User.Remove(userToRemove);
118+
await _context.SaveChangesAsync();
119+
return Ok("Deleted user - " + userToRemove.Name);
120+
}
121+
}
122+
}
123+
}

0 commit comments

Comments
 (0)