Browse Source

pagination for user posts

David Thornley 6 years ago
parent
commit
b7fffbed91

+ 2
- 2
src/main/java/com/ziplinegreen/vault/Controller/PostController.java View File

51
     }
51
     }
52
 
52
 
53
     @GetMapping("/posts/id/{userId}")
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
     @DeleteMapping("/posts/delete")
58
     @DeleteMapping("/posts/delete")

+ 1
- 0
src/main/java/com/ziplinegreen/vault/Repository/PostRepository.java View File

10
 @RepositoryRestResource
10
 @RepositoryRestResource
11
 public interface PostRepository extends JpaRepository<Post,Long> {
11
 public interface PostRepository extends JpaRepository<Post,Long> {
12
     Collection<Post> findByUserId(Long userId);
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 View File

44
     }
44
     }
45
 
45
 
46
     public ResponseEntity deleteAllPosts(Long userId){
46
     public ResponseEntity deleteAllPosts(Long userId){
47
-        Iterable<Post> posts = findByUserId(userId);
47
+        Iterable<Post> posts = postRepository.findByUserId(userId);
48
         for(Post post: posts){
48
         for(Post post: posts){
49
             deletePost(post.getId());
49
             deletePost(post.getId());
50
         }
50
         }
51
         return new ResponseEntity<>(HttpStatus.OK);
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
     public Post updatePost(Long postId, String message){
68
     public Post updatePost(Long postId, String message){
59
         Post post = postRepository.findById(postId).get();
69
         Post post = postRepository.findById(postId).get();
60
         post.setMessage(message);
70
         post.setMessage(message);