Passed
Push — master ( 676f65...74c283 )
by Huu-Phat
02:02 queued 13s
created

findBySlug(String)   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
cc 1
1
package com.dawn.jat.illuminati.post.service;
2
3
import com.dawn.jat.illuminati.core.convert.Converter;
4
import com.dawn.jat.illuminati.post.dto.PostDto;
5
import com.dawn.jat.illuminati.post.entity.PostEntity;
6
import com.dawn.jat.illuminati.post.entity.PostSummaryEntity;
7
import com.dawn.jat.illuminati.post.exception.PostNotFoundException;
8
import com.dawn.jat.illuminati.post.repository.PostRepository;
9
import com.dawn.jat.illuminati.post.repository.PostSummaryRepository;
10
11
import java.util.List;
12
import java.util.Map;
13
import java.util.Optional;
14
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.stereotype.Service;
17
import org.springframework.transaction.annotation.Transactional;
18
19
@Service
20
@Transactional
21
public class PostService {
22
    @Autowired
23
    private Converter converter;
24
25
    @Autowired
26
    private PostRepository postRepository;
27
28
    @Autowired
29
    private PostSummaryRepository postSummaryRepository;
30
31
    public List<PostSummaryEntity> findPostSummary() {
32
        return postSummaryRepository.findAll();
33
    }
34
35
    public Optional<PostEntity> findBySlug(String slug) {
36
        return postRepository.findBySlug(slug);
37
    }
38
39
    /**
40
     * Create new Entity from postDTO receive from client.
41
     * @param postDto PostDto
42
     * @return PostEntity
43
     */
44
    public PostEntity create(PostDto postDto) {
45
        PostEntity post = new PostEntity();
46
        post = converter.convertPostDtoToEntity(postDto, post);
47
        return postRepository.savePost(post);
48
    }
49
50
    private PostEntity findById(String id) {
51
        Optional<PostEntity> postObj = postRepository.findById(id);
52
        if (!postObj.isPresent()) {
53
            throw new PostNotFoundException("Saved post cannot be found!!!");
54
        }
55
        return postObj.get();
56
    }
57
58
    /**
59
     * Save a post info to an existing post.
60
     * @param postDto PostDto
61
     * @return PostEntity
62
     */
63
    public PostEntity save(PostDto postDto) {
64
        PostEntity savedPost = findById(postDto.getId());
65
        savedPost = converter.convertPostDtoToEntity(postDto, savedPost);
66
        return postRepository.savePost(savedPost);
67
    }
68
69
    public void deleteBySlug(String slug) {
70
        postRepository.deleteBySlug(slug);
71
    }
72
}
73