aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/com/terminaldweller/doc/DocService.java
blob: a885b9ace64f6c928cbf4cef34e257a45997bb27 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.terminaldweller.doc;

import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/** The document service class. */
@Service
public class DocService {
  private final DocRepository docRepository;

  @Autowired
  public DocService(DocRepository docRepository) {
    this.docRepository = docRepository;
  }

  /**
   * get a document by its id.
   *
   * @param id of the document to get.
   * @return returns the found doc if any.
   */
  public Optional<Doc> getDocs(Long id) {
    Optional<Doc> docOptional = docRepository.findById(id);
    if (docOptional.isPresent()) {
      return docOptional;
    }
    throw new IllegalStateException("Id does not exist");
  }

  /**
   * Adds a new Document to the data store.
   *
   * @param doc the new Document to add.
   * @param id the id of the document that's going to be created.
   */
  public void addNewDoc(Long id, Doc doc) {
    // Optional<Doc> docOptional = docRepository.findDocByName(doc.getName());
    Optional<Doc> docOptional = docRepository.findById(id);
    if (docOptional.isPresent()) {
      throw new IllegalStateException("Id is already taken");
    }
    doc.setId(id);
    docRepository.save(doc);
  }

  /**
   * Update a Document.
   *
   * @param doc the document to update.
   * @param id the id of the document to be updated.
   */
  public void updateDoc(Doc doc, Long id) {
    Optional<Doc> docOptional = docRepository.findById(id);
    if (!docOptional.isPresent()) {
      throw new IllegalStateException("Resource must be created before update");
    }
    doc.setId(id);
    doc.setLastModified(System.currentTimeMillis() / 1000L);
    doc.setBody(doc.getBody());
    docRepository.save(doc);
  }

  /**
   * Deletes a document from the data store.
   *
   * @param id The identifier for the document to be deleted.
   */
  public void deleteDoc(Long id) {
    boolean exists = docRepository.existsById(id);
    if (!exists) {
      throw new IllegalStateException("doc " + Long.toString(id) + " does not exitst");
    }
    docRepository.deleteById(id);
  }
}