Skip to content

Commit

Permalink
Set up API calls in front-end
Browse files Browse the repository at this point in the history
  • Loading branch information
marvac committed Feb 25, 2019
1 parent e3f8fd8 commit 277cddd
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 5 deletions.
4 changes: 3 additions & 1 deletion Client/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { PhotoEditorComponent } from './components/members/photo-editor/photo-ed
import { FileUploadModule } from 'ng2-file-upload';
import { TimeAgoPipe } from 'time-ago-pipe';
import { ListsResolver } from './resolvers/lists.resolver';
import { MessagesResolver } from './resolvers/messages.resolver';


export function tokenGetter() {
Expand Down Expand Up @@ -83,7 +84,8 @@ export function tokenGetter() {
MemberDetailResolver,
MemberListResolver,
MemberEditResolver,
ListsResolver
ListsResolver,
MessagesResolver
],
bootstrap: [AppComponent]
})
Expand Down
38 changes: 37 additions & 1 deletion Client/src/app/components/messages/messages.component.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,51 @@
import { Component, OnInit } from '@angular/core';
import { Message } from '../../models/message'
import { Pagination, PaginatedResult } from 'src/app/models/pagination';
import { AuthService } from 'src/app/services/auth.service';
import { ActivatedRoute } from '@angular/router';
import { AlertifyService } from 'src/app/services/alertify.service';
import { UserService } from 'src/app/services/user.service';

@Component({
selector: 'app-messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
messages: Message[];
pagination: Pagination;
messageContainer: string = "Unread";

constructor() { }
constructor(
private authService: AuthService,
private userService: UserService,
private route: ActivatedRoute,
private alertify: AlertifyService) { }

ngOnInit() {
this.route.data.subscribe(data => {
this.messages = data['messages'].result;
this.pagination = data['messages'].pagination;
});
}

loadMessages() {
this.userService.getMessages(
this.authService.decodedToken.nameid,
this.pagination.currentPage,
this.pagination.itemsPerPage,
this.messageContainer)
.subscribe((result: PaginatedResult<Message[]>) => {
this.messages = result.result;
this.pagination = result.pagination;
}, error => {
this.alertify.error(error);
});
}

pageChanged(event: any): void {
this.pagination.currentPage = event.page;
this.loadMessages;
}

}
12 changes: 12 additions & 0 deletions Client/src/app/models/message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export interface Message {
id: number;
senderId: number;
senderKnownAs: string;
senderPhotoUrl: string;
recipientId: number;
recipientKnownAs: string;
content: string;
markedAsRead: boolean;
readDate: Date;
messageSent: Date;
}
31 changes: 31 additions & 0 deletions Client/src/app/resolvers/messages.resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Injectable } from "@angular/core";
import { User } from "../models/user";
import { UserService } from "../services/user.service";
import { Resolve, Router, ActivatedRouteSnapshot } from "@angular/router";
import { AlertifyService } from "../services/alertify.service";
import { Observable, of } from "rxjs";
import { catchError } from "rxjs/operators";
import { Message } from "../models/message";
import { AuthService } from "../services/auth.service";

@Injectable()
export class MessagesResolver implements Resolve<Message[]> {
pageNumber: number = 1;
pageSize: number = 12;
messageContainer: string = "Unread";

constructor(
private userService: UserService,
private authService: AuthService,
private router: Router,
private alertify: AlertifyService) { }

resolve(route: ActivatedRouteSnapshot): Observable<Message[]> {
return this.userService.getMessages(this.authService.decodedToken.nameid, this.pageNumber, this.pageSize, this.messageContainer)
.pipe(catchError(error => {
this.alertify.error('Problem retrieving messages');
this.router.navigate(['/home']);
return of(null);
}));
}
}
3 changes: 2 additions & 1 deletion Client/src/app/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { MemberEditComponent } from './components/members/member-edit/member-edi
import { MemberEditResolver } from './resolvers/member-edit.resolver';
import { UnsavedChangesGuard } from './guards/unsaved-changes.guard';
import { ListsResolver } from './resolvers/lists.resolver';
import { MessagesResolver } from './resolvers/messages.resolver';

export const appRoutes: Routes = [
{ path: '', component: HomeComponent },
Expand All @@ -22,7 +23,7 @@ export const appRoutes: Routes = [
{ path: 'members', component: MemberListComponent, resolve: { users: MemberListResolver } },
{ path: 'members/edit', component: MemberEditComponent, resolve: { user: MemberEditResolver }, canDeactivate: [UnsavedChangesGuard] },
{ path: 'members/:id', component: MemberDetailComponent, resolve: { user: MemberDetailResolver } },
{ path: 'messages', component: MessagesComponent },
{ path: 'messages', component: MessagesComponent, resolve: { messages: MessagesResolver } },
{ path: 'lists', component: ListsComponent, resolve: { users: ListsResolver } }
]
},
Expand Down
25 changes: 24 additions & 1 deletion Client/src/app/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Observable } from 'rxjs';
import { User } from '../models/user';
import { PaginatedResult } from '../models/pagination';
import { map } from 'rxjs/operators';
import { Message } from '../models/message';


@Injectable({
Expand All @@ -15,7 +16,7 @@ export class UserService {
constructor(private http: HttpClient) { }

getUsers(page?, itemsPerPage?, userParameters?, likesParameter?): Observable<PaginatedResult<User[]>> {

const paginatedResult: PaginatedResult<User[]> = new PaginatedResult<User[]>();

let params = new HttpParams();
Expand All @@ -42,6 +43,7 @@ export class UserService {
if (response.headers.get('Pagination') != null) {
paginatedResult.pagination = JSON.parse(response.headers.get('Pagination'));
}

return paginatedResult;
}));
}
Expand All @@ -65,4 +67,25 @@ export class UserService {
likeUser(userId: number, recipientId: number) {
return this.http.post(`${this.usersUrl}${userId}/like/${recipientId}`, {});
}

getMessages(userId: number, page?, itemsPerPage?, messageContainer?): Observable<PaginatedResult<Message[]>> {
const paginatedResult: PaginatedResult<Message[]> = new PaginatedResult<Message[]>();
let params = new HttpParams();
params = params.append('MessageContainer', messageContainer);

if (page != null && itemsPerPage != null) {
params = params.append('pageNumber', page);
params = params.append('pageSize', itemsPerPage);
}

return this.http.get<Message[]>(`${this.usersUrl}${userId}/messages`, { observe: 'response', params })
.pipe(map(response => {
paginatedResult.result = response.body;
if (response.headers.get('Pagination') != null) {
paginatedResult.pagination = JSON.parse(response.headers.get('Pagination'));
}

return paginatedResult;
}));
}
}
17 changes: 17 additions & 0 deletions Controllers/MessagesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@ public async Task<IActionResult> GetMessages(int userId, [FromQuery]MessageParam
return Ok(messagesResource);
}

[HttpGet("thread/{recipientId}")]
public async Task<IActionResult> GetMessageThread(int userId, int recipientId)
{
int id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

if (id != userId)
{
return Unauthorized();
}

var messages = await _repo.GetMessageThread(userId, recipientId);

var messagesResource = _mapper.Map<IEnumerable<Message>, IEnumerable<MessageResource>>(messages);

return Ok(messagesResource);
}

[HttpPost]
public async Task<ActionResult> SendMessage(int userId, SendMessageResource sendMessageResource)
{
Expand Down
11 changes: 10 additions & 1 deletion Data/FriendRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,16 @@ public async Task<PagedList<Message>> GetMessages(MessageParameters messageParam

public async Task<IEnumerable<Message>> GetMessageThread(int userId, int recipientId)
{
throw new NotImplementedException();
var messages = await _context.Messages
.Include(u => u.Sender)
.ThenInclude(p => p.Photos)
.Include(u => u.Recipient)
.ThenInclude(p => p.Photos)
.Where(m => m.RecipientId == userId && m.SenderId == recipientId || m.RecipientId == recipientId && m.SenderId == userId)
.OrderByDescending(m => m.MessageSent)
.ToListAsync();

return messages;
}
}
}

0 comments on commit 277cddd

Please sign in to comment.