You are viewing an old version of this page. View the current version.
Compare with Current
View Page History
« Previous
Version 7
Next »
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import reactor.core.publisher.Mono;
@RestController
@RequiredArgsConstructor
public class LinkController {
private final LinkService linkService;
@PostMapping("/link")
Mono<CreateLinkResponse> create(@RequestBody CreateLinkRequest requestLink) {
return linkService.shortenLink(requestLink.getLink())
.map(CreateLinkResponse::new);
}
@GetMapping("/link/{key}")
Mono<ResponseEntity<Object>> getLink(@PathVariable String key) {
return linkService.getOriginalLink(key)
.map(link -> ResponseEntity.status(HttpStatus.PERMANENT_REDIRECT)
.header("Location", link.getOriginalLink())
.build())
.defaultIfEmpty(ResponseEntity.notFound().build());
}
@Value
public static class CreateLinkRequest {
private String link;
}
@Value
public static class CreateLinkResponse {
private String shortenedLink;
}
}
package com.example.demo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class LinkService {
private final LinkRepository linkRepository;
public LinkService(LinkRepository linkRepository) {
this.linkRepository = linkRepository;
}
Mono<String> shortenLink(String link) {
String randomKey = RandomStringUtils.randomAlphabetic(6);
return linkRepository.save(new Link(link, randomKey))
.map(result -> result.getKey());
}
Mono<Link> getOriginalLink(String key) {
return linkRepository.findByKey(key);
}
}
package com.example.demo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
@RequiredArgsConstructor
public class WebController {
@GetMapping("/home")
public String home(Model model) {
return "home";
}
}