Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement pagination #36

Merged
merged 5 commits into from
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.postrify.postrifybackend.config;

import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.data.web.config.EnableSpringDataWebSupport.PageSerializationMode;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@org.springframework.context.annotation.Configuration
@EnableSpringDataWebSupport(pageSerializationMode = PageSerializationMode.VIA_DTO)
public class WebConfig implements WebMvcConfigurer {

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
Expand All @@ -22,8 +26,10 @@ public class PostController {
@Autowired private UserService userService;

@GetMapping
public List<PostResponseDTO> getAllPosts() {
return postService.getAllPosts();
public Page<PostResponseDTO> getAllPosts(
@PageableDefault(page = 0, size = 10, sort = "updatedAt", direction = Sort.Direction.DESC)
final Pageable pageable) {
return postService.getAllPosts(pageable);
}

@GetMapping("/{id}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -20,16 +22,8 @@ public class PostService {
@Autowired private UserService userService;

@Transactional(readOnly = true)
public List<PostResponseDTO> getAllPosts() {
return postRepository.findAll().stream()
.map(this::convertToDTO)
.collect(
Collectors.collectingAndThen(
Collectors.toList(),
list -> {
java.util.Collections.reverse(list);
return list;
}));
public Page<PostResponseDTO> getAllPosts(final Pageable pageable) {
return postRepository.findAll(pageable).map(this::convertToDTO);
}

@Transactional(readOnly = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
Expand All @@ -41,6 +45,7 @@ void setUp() {
MockitoAnnotations.openMocks(this);
}

@SuppressWarnings("unchecked")
@Test
void getAllPosts_Success() {
UserDTO userDTO = new UserDTO(1L, "jordi", "[email protected]");
Expand All @@ -52,13 +57,16 @@ void getAllPosts_Success() {
2L, "Post 2", "Content 2", userDTO, LocalDateTime.now(), LocalDateTime.now());
List<PostResponseDTO> posts = Arrays.asList(post1, post2);

when(postService.getAllPosts()).thenReturn(posts);
Pageable pageable = PageRequest.of(0, 10);
Page<PostResponseDTO> page = new PageImpl<>(posts, pageable, posts.size());

List<PostResponseDTO> result = postController.getAllPosts();
when(postService.getAllPosts(pageable)).thenReturn(page);

Page<PostResponseDTO> result = postController.getAllPosts(pageable);

assertNotNull(result);
assertEquals(2, result.size());
verify(postService, times(1)).getAllPosts();
assertEquals(2, result.getContent().size());
verify(postService, times(1)).getAllPosts(pageable);
}

@Test
Expand Down
149 changes: 124 additions & 25 deletions postrify-frontend/src/app/components/home/home.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,55 @@ import { PostService } from '../../services/post.service';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import { CommonModule } from '@angular/common';
import { Page } from '../../models/page.model';

@Component({
selector: 'app-home',
standalone: true,
imports: [CommonModule],
template: `
<div class="home-container">
<div class="posts-grid">
@for (post of posts; track post.id) {
<div
class="post-card"
(click)="viewPost(post.id)"
role="button"
tabindex="0"
(keyup.enter)="viewPost(post.id)"
(keyup.space)="viewPost(post.id)"
>
<h3>{{ post.title }}</h3>
<p>
{{ post.content | slice: 0 : 100
}}{{ post.content.length > 100 ? '...' : '' }}
</p>
<div class="post-meta">
<span>By: {{ post.user.username }}</span>
<span>{{ post.createdAt | date: 'short' }}</span>
<div class="posts-grid-container">
<div class="posts-grid">
@for (post of posts; track post.id) {
<div
class="post-card"
(click)="viewPost(post.id)"
role="button"
tabindex="0"
(keyup.enter)="viewPost(post.id)"
(keyup.space)="viewPost(post.id)"
>
<h3>{{ post.title }}</h3>
<p>
{{ post.content | slice: 0 : 100
}}{{ post.content.length > 100 ? '...' : '' }}
</p>
<div class="post-meta">
<span>By: {{ post.user.username }}</span>
<span>{{ post.createdAt | date: 'short' }}</span>
</div>
</div>
</div>
}
}
</div>
</div>
<div class="pagination-controls" *ngIf="totalPages > 1">
<button (click)="previousPage()" [disabled]="currentPage === 0">
Back
</button>

<span *ngFor="let page of [].constructor(totalPages); let i = index">
<button (click)="goToPage(i)" [class.active]="i === currentPage">
{{ i + 1 }}
</button>
</span>

<button
(click)="nextPage()"
[disabled]="currentPage === totalPages - 1"
>
Next
</button>
</div>
@if (isLogged) {
<button
Expand All @@ -50,6 +71,10 @@ import { CommonModule } from '@angular/common';
position: relative;
}

.posts-grid-container {
min-height: 85vh;
}

.posts-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
Expand Down Expand Up @@ -96,11 +121,53 @@ import { CommonModule } from '@angular/common';
.floating-button:hover {
background-color: var(--primary-color-hover);
}

.pagination-controls {
display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
flex-wrap: wrap;
gap: 5px;
}

.pagination-controls button {
padding: 8px 12px;
margin: 0 2px;
border: 1px solid var(--border-color);
background-color: var(--header-bg);
color: var(--text-color);
border-radius: 4px;
cursor: pointer;
transition:
background-color 0.3s,
color 0.3s;
}

.pagination-controls button:hover:not([disabled]) {
background-color: var(--primary-color);
color: white;
}

.pagination-controls button.active {
background-color: var(--primary-color);
color: white;
border-color: var(--primary-color);
}

.pagination-controls button[disabled] {
cursor: not-allowed;
opacity: 0.5;
}
`,
})
export class HomeComponent implements OnInit {
posts: PostResponseDTO[] = [];
isLogged = false;
currentPage = 0;
pageSize = 10;
totalPages = 0;
totalElements = 0;

constructor(
private postService: PostService,
Expand All @@ -109,14 +176,18 @@ export class HomeComponent implements OnInit {
) {}

ngOnInit(): void {
this.fetchPosts();
this.fetchPosts(this.currentPage, this.pageSize);
this.isLogged = this.authService.isAuthenticated();
}

fetchPosts(): void {
this.postService.getAllPosts().subscribe({
next: (posts) => {
this.posts = posts;
fetchPosts(page: number, size: number): void {
this.postService.getAllPosts(page, size).subscribe({
next: (pageData: Page<PostResponseDTO>) => {
this.posts = pageData.content;
this.currentPage = pageData.page.number;
this.pageSize = pageData.page.size;
this.totalPages = pageData.page.totalPages;
this.totalElements = pageData.page.totalElements;
},
error: (err) => {
console.error(err);
Expand All @@ -131,4 +202,32 @@ export class HomeComponent implements OnInit {
createPost(): void {
this.router.navigate(['/create']);
}

goToPage(page: number): void {
if (page >= 0 && page < this.totalPages) {
this.fetchPosts(page, this.pageSize);
}
}

nextPage(): void {
if (this.currentPage < this.totalPages - 1) {
this.fetchPosts(this.currentPage + 1, this.pageSize);
}
}

previousPage(): void {
if (this.currentPage > 0) {
this.fetchPosts(this.currentPage - 1, this.pageSize);
}
}

getPages(): number[] {
return Array(this.totalPages)
.fill(0)
.map((x, i) => i);
}

trackById(index: number, post: PostResponseDTO): number {
return post.id;
}
}
9 changes: 9 additions & 0 deletions postrify-frontend/src/app/models/page.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface Page<T> {
content: T[];
page: {
size: number;
number: number;
totalElements: number;
totalPages: number;
};
}
10 changes: 7 additions & 3 deletions postrify-frontend/src/app/services/post.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Post } from '../models/post.model';
import { PostResponseDTO } from '../models/post-response.model';
import { environment } from '../../environments/environment';
import { Page } from '../models/page.model';

@Injectable({
providedIn: 'root',
Expand All @@ -13,8 +14,11 @@ export class PostService {

constructor(private http: HttpClient) {}

getAllPosts(): Observable<PostResponseDTO[]> {
return this.http.get<PostResponseDTO[]>(this.apiUrl);
getAllPosts(page: number, size: number): Observable<Page<PostResponseDTO>> {
const params = new HttpParams()
.set('page', page.toString())
.set('size', size.toString());
return this.http.get<Page<PostResponseDTO>>(this.apiUrl, { params });
}

getPostById(id: number): Observable<PostResponseDTO> {
Expand Down
Loading