Bladeren bron

pagination for user posts

David Thornley 6 jaren geleden
bovenliggende
commit
b7fffbed91

+ 2
- 2
src/main/java/com/ziplinegreen/vault/Controller/PostController.java Bestand weergeven

@@ -51,8 +51,8 @@ public class PostController {
51 51
     }
52 52
 
53 53
     @GetMapping("/posts/id/{userId}")
54
-    public Collection<Post> getAllPostsByUserId(@PathVariable Long userId) {
55
-        return postService.findByUserId(userId);
54
+    public Page<Post> getAllPostsByUserId(@PathVariable Long userId, Pageable pageable) {
55
+        return postService.findByUserId(userId, pageable);
56 56
     }
57 57
 
58 58
     @DeleteMapping("/posts/delete")

+ 1
- 0
src/main/java/com/ziplinegreen/vault/Repository/PostRepository.java Bestand weergeven

@@ -10,5 +10,6 @@ import java.util.Collection;
10 10
 @RepositoryRestResource
11 11
 public interface PostRepository extends JpaRepository<Post,Long> {
12 12
     Collection<Post> findByUserId(Long userId);
13
+    Iterable<Post> findAllByUserId(Long userId);
13 14
 
14 15
 }

+ 13
- 3
src/main/java/com/ziplinegreen/vault/Service/PostService.java Bestand weergeven

@@ -44,17 +44,27 @@ public class PostService {
44 44
     }
45 45
 
46 46
     public ResponseEntity deleteAllPosts(Long userId){
47
-        Iterable<Post> posts = findByUserId(userId);
47
+        Iterable<Post> posts = postRepository.findByUserId(userId);
48 48
         for(Post post: posts){
49 49
             deletePost(post.getId());
50 50
         }
51 51
         return new ResponseEntity<>(HttpStatus.OK);
52 52
     }
53 53
 
54
-    public Collection<Post> findByUserId(Long userId) {
55
-        return postRepository.findByUserId(userId);
54
+    public Page<Post> findByUserId(Long userId, Pageable pageable) {
55
+        Iterable<Post> posts = postRepository.findByUserId(userId);
56
+        List<Post> postList = StreamSupport.stream(posts.spliterator(), false)
57
+                .collect(Collectors.toList());
58
+        Collections.reverse(postList);
59
+
60
+        int start = (int)pageable.getOffset();
61
+        int end = (start + pageable.getPageSize()) > postList.size() ? postList.size() : (start + pageable.getPageSize());
62
+
63
+        return new PageImpl<Post>(postList.subList(start,end),pageable, postList.size());
56 64
     }
57 65
 
66
+
67
+
58 68
     public Post updatePost(Long postId, String message){
59 69
         Post post = postRepository.findById(postId).get();
60 70
         post.setMessage(message);