Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
services:
gateway:
build: gateway
image: shareit-gateway
container_name: shareit-gateway
ports:
- "8080:8080"
depends_on:
- server
environment:
- SHAREIT_SERVER_URL=http://server:9090

server:
build: server
image: shareit-server
container_name: shareit-server
ports:
- "9090:9090"
depends_on:
- db
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/shareit
- SPRING_DATASOURCE_USERNAME=shareit
- SPRING_DATASOURCE_PASSWORD=shareit

db:
image: postgres:16.1
container_name: postgres
ports:
- "6541:5432"
environment:
- POSTGRES_PASSWORD=shareit
- POSTGRES_USER=shareit
- POSTGRES_DB=shareit
healthcheck:
test: pg_isready -q -d $$POSTGRES_DB -U $$POSTGRES_USER
timeout: 5s
interval: 5s
retries: 10
5 changes: 5 additions & 0 deletions gateway/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM eclipse-temurin:21-jre-jammy
VOLUME /tmp
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["sh", "-c", "java ${JAVA_OPTS} -jar /app.jar"]
124 changes: 124 additions & 0 deletions gateway/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.practicum</groupId>
<artifactId>shareit</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

<artifactId>shareit-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>ShareIt Gateway</name>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>ru/practicum/shareit/**/dto/*</exclude>
<exclude>ru/practicum/shareit/ShareItGateway.class</exclude>
<exclude>ru/practicum/shareit/rest/*.class</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<destFile>${project.build.directory}/coverage-reports/jacoco.exec</destFile>
<propertyName>surefireArgLine</propertyName>
</configuration>
</execution>
<execution>
<id>default-report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${project.build.directory}/coverage-reports/jacoco.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
</configuration>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>COMPLEXITY</counter>
<value>COVEREDRATIO</value>
<minimum>0.70</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>
12 changes: 12 additions & 0 deletions gateway/src/main/java/ru/practicum/shareit/ShareItGateway.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ru.practicum.shareit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ShareItGateway {
public static void main(String[] args) {
SpringApplication.run(ShareItGateway.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package ru.practicum.shareit.booking;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.practicum.shareit.rest.RestQueryBuilder;
import ru.practicum.shareit.booking.dto.BookingDto;

@RestController
@RequestMapping(path = "/bookings")
@RequiredArgsConstructor
public class BookingController {
private final BookingService bookingService;

@GetMapping("/{id}")
public ResponseEntity<Object> getBooking(
@PathVariable long id,
@RequestHeader("X-Sharer-User-Id") long userId) {
var request = RestQueryBuilder.builder()
.method(HttpMethod.GET)
.path("/" + id)
.requestHead("X-Sharer-User-Id", String.valueOf(userId))
.build();

return bookingService.executeQuery(request);
}

@GetMapping
public ResponseEntity<Object> getBookingForUserId(
@RequestHeader("X-Sharer-User-Id") long userId) {
var request = RestQueryBuilder.builder()
.method(HttpMethod.GET)
.requestHead("X-Sharer-User-Id", String.valueOf(userId))
.build();

return bookingService.executeQuery(request);
}

@GetMapping("/owner")
public ResponseEntity<Object> getBookingForItemOwnerId(
@RequestHeader("X-Sharer-User-Id") long ownerId) {
var request = RestQueryBuilder.builder()
.method(HttpMethod.GET)
.path("/owner")
.requestHead("X-Sharer-User-Id", String.valueOf(ownerId))
.build();

return bookingService.executeQuery(request);
}

@PostMapping
public ResponseEntity<Object> postBooking(
@RequestHeader("X-Sharer-User-Id") long userId,
@Valid @RequestBody BookingDto bookingDto) {
var request = RestQueryBuilder.builder()
.method(HttpMethod.POST)
.requestHead("X-Sharer-User-Id", String.valueOf(userId))
.body(bookingDto)
.build();

return bookingService.executeQuery(request);
}

@PatchMapping("/{id}")
public ResponseEntity<Object> patchBooking(
@PathVariable long id,
@RequestParam(name = "approved") boolean approved,
@RequestHeader("X-Sharer-User-Id") long userId) {
var request = RestQueryBuilder.builder()
.method(HttpMethod.PATCH)
.path("/" + id + "?approved=" + (approved ? "true" : "false"))
.requestHead("X-Sharer-User-Id", String.valueOf(userId))
.build();

return bookingService.executeQuery(request);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package ru.practicum.shareit.booking;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.util.DefaultUriBuilderFactory;
import ru.practicum.shareit.rest.RestService;

@Service
public class BookingService extends RestService {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Эти классы не логично называть Service, т.к. в них нет никакой бизнес-логики по работе с сущностями. Лучше назвать RestClient и BookingClient и пометить аннотацией @Component

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сервис, потому что стоят за контроллером. А клиентом не хочу называть, т.к. клиент внутри используется.
И бизнес-логика подразумевалась в задании, в описании маршрутизации рест-запросов

Copy link

@VadimZharkov VadimZharkov Dec 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Классы получают аннотацию @Service потому что они принадлежат сервисному слою приложения, а не потому что стоят за контроллером. Маршрутизация -это не бизнес-логика. В задании как раз говорится, что "shareIt-server будет содержать всю основную логику ", а в shareIt-gateway нужно вынести "всю валидацию входных данных".

PS
Если хочешь подчеркнуть, что основная задача класса маршрутизация, то можно назвать Router

private static final String API_PREFIX = "/bookings";

@Autowired
public BookingService(
@Value("${shareit-server.url}") String serverUrl,
RestTemplateBuilder builder) {
super(
builder
.uriTemplateHandler(new DefaultUriBuilderFactory(serverUrl + API_PREFIX))
.requestFactory(() -> new HttpComponentsClientHttpRequestFactory())
.build()
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package ru.practicum.shareit.booking.dto;


import lombok.Builder;
import ru.practicum.shareit.item.dto.ItemDto;
import ru.practicum.shareit.user.dto.UserDto;

@Builder(toBuilder = true)
public record BookingDto(
Long id,
Long itemId,
BookingStatus status,
String start,
String end,
UserDto booker,
ItemDto item
){ }
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ru.practicum.shareit.booking.dto;

public enum BookingStatus {
WAITING,
APPROVED,
REJECTED,
CANCELED
}
Loading
Loading