Skip to content

Commit

Permalink
mv PasteCleanupService to application layer
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan committed Feb 18, 2024
1 parent 170ce04 commit 493c292
Show file tree
Hide file tree
Showing 12 changed files with 68 additions and 53 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.github.binpastes.paste.api;

import com.github.binpastes.paste.api.model.CreateCmd;
import com.github.binpastes.paste.api.model.ListView;
import com.github.binpastes.paste.api.model.SearchView;
import com.github.binpastes.paste.api.model.SearchView.SearchItemView;
import com.github.binpastes.paste.api.model.SingleView;
import com.github.binpastes.paste.api.model.ListQuery;
import com.github.binpastes.paste.api.model.SearchQuery;
import com.github.binpastes.paste.api.model.SearchQuery.SearchItemView;
import com.github.binpastes.paste.api.model.DetailQuery;
import com.github.binpastes.paste.application.PasteService;
import com.github.binpastes.paste.domain.Paste;
import jakarta.validation.ConstraintViolationException;
Expand All @@ -28,7 +28,7 @@
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import static com.github.binpastes.paste.api.model.ListView.ListItemView;
import static com.github.binpastes.paste.api.model.ListQuery.ListItemQuery;

@Validated
@RestController
Expand All @@ -45,7 +45,7 @@ public PasteController(final PasteService pasteService) {
}

@GetMapping("/{pasteId:[a-zA-Z0-9]{40}}")
public Mono<SingleView> findPaste(@PathVariable("pasteId") String pasteId, ServerHttpRequest request, ServerHttpResponse response) {
public Mono<DetailQuery> findPaste(@PathVariable("pasteId") String pasteId, ServerHttpRequest request, ServerHttpResponse response) {
return pasteService
.find(pasteId)
.doOnNext(paste -> {
Expand All @@ -63,21 +63,21 @@ public Mono<SingleView> findPaste(@PathVariable("pasteId") String pasteId, Serve
CacheControl.maxAge(Duration.between(now, paste.getDateOfExpiry())));
}
})
.map(reference -> SingleView.of(reference, remoteAddress(request)))
.map(reference -> DetailQuery.of(reference, remoteAddress(request)))
.switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));
}

@GetMapping
public Mono<ListView> findPastes() {
public Mono<ListQuery> findPastes() {
return pasteService
.findAll()
.map(ListItemView::of)
.map(ListItemQuery::of)
.collectList()
.map(ListView::of);
.map(ListQuery::of);
}

@GetMapping("/search")
public Mono<SearchView> searchPastes(
public Mono<SearchQuery> searchPastes(
@RequestParam("term")
@NotBlank
@Pattern(regexp = "[\\pL\\pN\\p{P}\\s]{3,25}")
Expand All @@ -89,12 +89,12 @@ public Mono<SearchView> searchPastes(
.findByFullText(term)
.map(paste -> SearchItemView.of(paste, term))
.collectList()
.map(SearchView::of);
.map(SearchQuery::of);
}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Mono<SingleView> createPaste(@Valid @RequestBody Mono<CreateCmd> createCmd, ServerHttpRequest request) {
public Mono<DetailQuery> createPaste(@Valid @RequestBody Mono<CreateCmd> createCmd, ServerHttpRequest request) {
return createCmd
.flatMap(cmd -> pasteService.create(
cmd.title(),
Expand All @@ -104,7 +104,7 @@ public Mono<SingleView> createPaste(@Valid @RequestBody Mono<CreateCmd> createCm
cmd.pasteExposure(),
remoteAddress(request)
))
.map((Paste reference) -> SingleView.of(reference, remoteAddress(request)));
.map((Paste reference) -> DetailQuery.of(reference, remoteAddress(request)));
}

@DeleteMapping("/{pasteId:[a-zA-Z0-9]{40}}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import java.time.LocalDateTime;

public record SingleView(
public record DetailQuery(
String id,
String title,
String content,
Expand All @@ -18,8 +18,8 @@ public record SingleView(
LocalDateTime lastViewed,
long views
) {
public static SingleView of(final Paste reference, final String remoteAddress) {
return new SingleView(
public static DetailQuery of(final Paste reference, final String remoteAddress) {
return new DetailQuery(
reference.getId(),
reference.getTitle(),
reference.getContent(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,23 @@
import java.time.LocalDateTime;
import java.util.List;

public record ListView(
List<ListItemView> pastes
public record ListQuery(
List<ListItemQuery> pastes
) {
public static ListView of(final List<ListItemView> pastes) {
return new ListView(pastes);
public static ListQuery of(final List<ListItemQuery> pastes) {
return new ListQuery(pastes);
}

public record ListItemView (
public record ListItemQuery(
String id,
String title,
int sizeInBytes,
boolean isEncrypted,
LocalDateTime dateCreated,
LocalDateTime dateOfExpiry
) {
public static ListItemView of(final Paste reference) {
return new ListItemView(
public static ListItemQuery of(final Paste reference) {
return new ListItemQuery(
reference.getId(),
reference.getTitle(),
reference.getContent().getBytes().length,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
import java.time.LocalDateTime;
import java.util.List;

public record SearchView(
public record SearchQuery(
List<SearchItemView> pastes
) {

public static SearchView of(List<SearchItemView> pastes) {
return new SearchView(pastes);
public static SearchQuery of(List<SearchItemView> pastes) {
return new SearchQuery(pastes);
}

public record SearchItemView(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.github.binpastes.paste.domain;
package com.github.binpastes.paste.application;

import com.github.binpastes.paste.domain.PasteRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -9,14 +10,14 @@
import java.time.LocalDateTime;

@Component
class PasteCleanupService {
class PasteUpkeepService {

private static final Logger log = LoggerFactory.getLogger(PasteCleanupService.class);
private static final Logger log = LoggerFactory.getLogger(PasteUpkeepService.class);

private final PasteRepository pasteRepository;

@Autowired
public PasteCleanupService(final PasteRepository pasteRepository) {
public PasteUpkeepService(final PasteRepository pasteRepository) {
this.pasteRepository = pasteRepository;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static java.time.LocalDateTime.parse;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

@SpringBootTest
@AutoConfigureWebTestClient
Expand Down Expand Up @@ -146,10 +147,10 @@ void deleteOneTimePaste() {
.expectStatus().isNoContent()
.expectBody().isEmpty();

webClient.get()
await().untilAsserted(() -> webClient.get()
.uri("/api/v1/paste/" + oneTimePaste.getId())
.exchange()
.expectStatus().isNotFound();
.expectStatus().isNotFound());
}

private Paste givenOneTimePaste() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.github.binpastes.paste.domain.Paste;
import com.github.binpastes.paste.domain.Paste.PasteExposure;
import com.github.binpastes.paste.domain.PasteRepository;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
Expand All @@ -21,6 +22,7 @@
import static java.time.LocalDateTime.now;
import static java.time.LocalDateTime.parse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

@SpringBootTest
@AutoConfigureWebTestClient
Expand Down Expand Up @@ -176,11 +178,11 @@ void deletePublicPaste() {
.expectStatus().isNoContent()
.expectBody().isEmpty();

webClient.get()
await().untilAsserted(() -> webClient.get()
.uri("/api/v1/paste/" + paste.getId())
.header(HttpHeaders.CACHE_CONTROL, CacheControl.noCache().getHeaderValue())
.exchange()
.expectStatus().isNotFound();
.expectStatus().isNotFound());
}

private Paste givenPublicPaste() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import static java.time.LocalDateTime.parse;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

@SpringBootTest
@AutoConfigureWebTestClient
Expand Down Expand Up @@ -156,13 +157,11 @@ void deleteUnlistedPaste() throws InterruptedException {
.expectStatus().isNoContent()
.expectBody().isEmpty();

TimeUnit.MILLISECONDS.sleep(500);

webClient.get()
await().untilAsserted(() -> webClient.get()
.uri("/api/v1/paste/" + unlistedPaste.getId())
.header(HttpHeaders.CACHE_CONTROL, CacheControl.noCache().getHeaderValue())
.exchange()
.expectStatus().isNotFound();
.expectStatus().isNotFound());
}

private Paste givenUnlistedPaste() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.github.binpastes.paste.api.model;

import com.github.binpastes.paste.api.model.SearchView.SearchItemView;
import com.github.binpastes.paste.api.model.SearchQuery.SearchItemView;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
Expand Down
12 changes: 6 additions & 6 deletions frontend/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {PasteListView} from './model/PasteListView';
import {PasteView} from './model/PasteView';
import {PasteSearchView} from './model/PasteSearchView';

const apiBaseUrl = () => {
function apiBaseUrl() {
switch (window.location.host) {
case 'localhost:3000': // development
case 'localhost:4173': // development
Expand All @@ -13,7 +13,7 @@ const apiBaseUrl = () => {
}
}

const createPaste = (cmd: PasteCreateCmd): Promise<PasteView> => {
function createPaste(cmd: PasteCreateCmd): Promise<PasteView> {
const url = new URL('/api/v1/paste', apiBaseUrl());

return fetch(url, {
Expand All @@ -32,7 +32,7 @@ const createPaste = (cmd: PasteCreateCmd): Promise<PasteView> => {
});
}

const findOne = (id: string): Promise<PasteView> => {
function findOne(id: string): Promise<PasteView> {
const url = new URL('/api/v1/paste/' + id, apiBaseUrl());

return fetch(url)
Expand All @@ -45,15 +45,15 @@ const findOne = (id: string): Promise<PasteView> => {
})
}

const findAll = (): Promise<Array<PasteListView>> => {
function findAll(): Promise<Array<PasteListView>> {
const url = new URL('/api/v1/paste', apiBaseUrl());

return fetch(url)
.then(value => value.json())
.then(value => value.pastes);
}

const searchAll = (term: string): Promise<Array<PasteSearchView>> => {
function searchAll(term: string): Promise<Array<PasteSearchView>> {
const params = new URLSearchParams([['term', term]]);
const url = new URL('/api/v1/paste/search?' + encodeURI(params.toString()), apiBaseUrl());

Expand All @@ -63,7 +63,7 @@ const searchAll = (term: string): Promise<Array<PasteSearchView>> => {
.catch(_ => [])
}

const deletePaste = (id: string): Promise<void> => {
function deletePaste(id: string): Promise<void> {
const url = new URL('/api/v1/paste/' + id, apiBaseUrl());

return fetch(url, {
Expand Down
9 changes: 7 additions & 2 deletions frontend/src/crypto/CryptoUtil.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import AES from 'crypto-js/aes';
import CryptoJS from 'crypto-js/core';

export const encrypt = (clearText: string, key: string): string => {
function encrypt(clearText: string, key: string): string {
return AES.encrypt(clearText, key).toString();
}

export const decrypt = (cipherText: string, key: string): string | null => {
function decrypt(cipherText: string, key: string): string | null {
try {
const wordArray = AES.decrypt(cipherText, key);
return wordArray.toString(CryptoJS.enc.Utf8) || null;
} catch (_) {
return null;
}
}

export {
encrypt,
decrypt
}
17 changes: 12 additions & 5 deletions frontend/src/datetime/DateTimeUtil.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

export const toDateTimeString = (date: string | Date): string => {
function toDateTimeString(date: string | Date): string {
if (!date) {
return null;
}
Expand All @@ -8,7 +8,7 @@ export const toDateTimeString = (date: string | Date): string => {
return toTimeString(instant) + ' / ' + toDateString(instant);
}

export const toDateString = (date: string | Date): string => {
function toDateString(date: string | Date): string {
if (!date) {
return null;
}
Expand All @@ -17,7 +17,7 @@ export const toDateString = (date: string | Date): string => {
return instant.toLocaleDateString(navigator.language || 'en', {day: '2-digit', month: 'long', year: 'numeric'});
}

export const toTimeString = (date: string | Date): string => {
function toTimeString(date: string | Date): string {
if (!date) {
return null;
}
Expand All @@ -26,7 +26,7 @@ export const toTimeString = (date: string | Date): string => {
return instant.toLocaleTimeString(navigator.language || 'en', {hour: '2-digit', minute: '2-digit'});
}

export const relativeDiffLabel = (date: string | Date): string => {
function relativeDiffLabel(date: string | Date): string {
if (!date) {
return null;
}
Expand Down Expand Up @@ -75,10 +75,17 @@ export const relativeDiffLabel = (date: string | Date): string => {
}
};

const toDate = (date: string | Date): Date => {
function toDate(date: string | Date): Date {
if (date instanceof Date) {
return date;
}

return new Date(Date.parse(date));
}

export {
toDateTimeString,
toDateString,
toTimeString,
relativeDiffLabel
}

0 comments on commit 493c292

Please sign in to comment.