aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/com/terminaldweller/doc/DocService.java
blob: 5a07c23e825bcd1e1399e10ccc0ce5f3d5b203a2 (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
package com.terminaldweller.doc;

import java.util.List;
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;
  }

  public List<Doc> getDocs() {
    return docRepository.findAll();
  }

  /**
   * Adds a new Document to the data store.
   *
   * @param doc the new Document to add.
   */
  public void addNewDoc(Doc doc) {
    Optional<Doc> docOptional = docRepository.findDocByName(doc.getName());
    if (docOptional.isPresent()) {
      throw new IllegalStateException("Id is already taken");
    }
    docRepository.save(doc);
  }

  /**
   * Update a Document.
   *
   * @param doc the document to update.
   */
  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 " + id + " does not exitst");
    }
    docRepository.deleteById(id);
  }
}