Compare commits
3 Commits
lab3-sb
...
lab6-branc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c80d1be3c5 | ||
|
|
e5f5540fe8 | ||
|
|
49c622ff69 |
3
.idea/.gitignore
generated
vendored
@@ -1,3 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
9
.idea/internetDev.iml
generated
@@ -1,9 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
.idea/misc.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="21" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
8
.idea/modules.xml
generated
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/internetDev.iml" filepath="$PROJECT_DIR$/.idea/internetDev.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
BIN
LabWork6Report.docx
Normal file
3
demo/.gitattributes
vendored
@@ -1,3 +0,0 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
37
demo/.gitignore
vendored
@@ -1,37 +0,0 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
564
demo/ANSWERS.md
@@ -1,564 +0,0 @@
|
||||
# Ответы на вопросы по персистентности, ORM, JPA и Hibernate
|
||||
|
||||
## 1. Что такое персистентность?
|
||||
|
||||
**Персистентность** — это способность данных сохраняться после завершения работы приложения. В нашем проекте данные сохраняются в файле базы данных H2.
|
||||
|
||||
**Пример из проекта:**
|
||||
- Файл `demo/src/main/resources/application.properties`, строки 6-11:
|
||||
```properties
|
||||
spring.datasource.url=jdbc:h2:file:./data
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
```
|
||||
Настройка `ddl-auto=update` позволяет сохранять данные между перезапусками приложения в файл `./data.mv.db`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Каким образом можно добавить поддержку персистентности в приложение?
|
||||
|
||||
В нашем проекте персистентность добавлена через:
|
||||
1. **Spring Data JPA** — зависимость в `build.gradle`
|
||||
2. **H2 Database** — встроенная БД
|
||||
3. **JPA аннотации** на сущностях
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/build.gradle`, строки 30-31:
|
||||
```gradle
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation "com.h2database:h2:${h2Version}"
|
||||
```
|
||||
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 9-10:
|
||||
```java
|
||||
@Entity
|
||||
@Table(name = "artists")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Что такое сущность и атрибут сущности?
|
||||
|
||||
**Сущность** — это объект предметной области, который имеет идентичность и может быть сохранен в БД. **Атрибут** — это свойство сущности.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`:
|
||||
- **Сущность**: `ArtistEntity` (строка 11)
|
||||
- **Атрибуты**: `name` (строка 13), `description` (строка 15), `epoch` (строка 20), `country` (строка 24)
|
||||
|
||||
---
|
||||
|
||||
## 4. Как сущности и их атрибуты представлены в реляционной модели данных?
|
||||
|
||||
В реляционной модели:
|
||||
- **Сущность** → **Таблица**
|
||||
- **Атрибут** → **Колонка**
|
||||
- **Связь** → **Внешний ключ (Foreign Key)**
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 9-24:
|
||||
```java
|
||||
@Entity
|
||||
@Table(name = "artists") // Таблица "artists"
|
||||
public class ArtistEntity extends BaseEntity {
|
||||
@Column(nullable = false) // Колонка "name"
|
||||
private String name;
|
||||
|
||||
@Column(columnDefinition = "text") // Колонка "description"
|
||||
private String description;
|
||||
|
||||
@JoinColumn(name = "epoch_id", nullable = false) // Внешний ключ "epoch_id"
|
||||
@ManyToOne
|
||||
private EpochEntity epoch;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Как сущности и их атрибуты представлены в ООП?
|
||||
|
||||
В ООП:
|
||||
- **Сущность** → **Класс**
|
||||
- **Атрибут** → **Поле класса**
|
||||
- **Связь** → **Ссылка на другой объект**
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 11-24:
|
||||
```java
|
||||
public class ArtistEntity extends BaseEntity { // Класс (сущность)
|
||||
private String name; // Поле (атрибут)
|
||||
private String description; // Поле (атрибут)
|
||||
private EpochEntity epoch; // Ссылка на другой объект (связь)
|
||||
private CountryEntity country; // Ссылка на другой объект (связь)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Как соотносятся понятия ООП и реляционной модели данных?
|
||||
|
||||
**ORM (Object-Relational Mapping)** преобразует:
|
||||
- Класс ↔ Таблица
|
||||
- Поле ↔ Колонка
|
||||
- Объект ↔ Строка таблицы
|
||||
- Ссылка ↔ Внешний ключ
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`:
|
||||
- Класс `ArtistEntity` → таблица `artists` (строка 10)
|
||||
- Поле `name` → колонка `name` (строка 12-13)
|
||||
- Поле `epoch` → внешний ключ `epoch_id` (строка 18-20)
|
||||
|
||||
---
|
||||
|
||||
## 7. Что такое ORM?
|
||||
|
||||
**ORM (Object-Relational Mapping)** — технология, которая автоматически преобразует объекты в записи БД и обратно.
|
||||
|
||||
**Пример из проекта:**
|
||||
- Используется через Spring Data JPA и Hibernate
|
||||
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строка 12:
|
||||
```java
|
||||
public interface ArtistRepository extends JpaRepository<ArtistEntity, Long>
|
||||
```
|
||||
JpaRepository автоматически реализует методы для работы с БД через ORM.
|
||||
|
||||
---
|
||||
|
||||
## 8. Когда следует использовать ORM?
|
||||
|
||||
ORM следует использовать когда:
|
||||
- Приложение использует ООП
|
||||
- Нужна быстрая разработка
|
||||
- Бизнес-логика сложная
|
||||
- Нужна переносимость между БД
|
||||
|
||||
**Пример из проекта:**
|
||||
- Проект использует Spring Boot с JPA для быстрой разработки
|
||||
- `demo/src/main/resources/application.properties`, строка 10:
|
||||
```properties
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
```
|
||||
Можно легко сменить БД, изменив только настройки.
|
||||
|
||||
---
|
||||
|
||||
## 9. Когда НЕ следует использовать ORM?
|
||||
|
||||
ORM НЕ следует использовать когда:
|
||||
- Критична производительность (высоконагруженные системы)
|
||||
- Нужны сложные SQL-запросы
|
||||
- Работа с большими объемами данных (batch-обработка)
|
||||
- Уже есть оптимизированные SQL-запросы
|
||||
|
||||
**Пример из проекта:**
|
||||
- Для статистики используются JPQL запросы, но для очень сложных запросов может понадобиться нативный SQL
|
||||
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строки 19-23:
|
||||
```java
|
||||
@Query("select count(a) as totalArtists, ...")
|
||||
ArtistStatsProjection getArtistsStatistics();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. Что такое ассоциации в ООП?
|
||||
|
||||
**Ассоциация** — это связь между классами, когда один объект ссылается на другой.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 18-24:
|
||||
```java
|
||||
@ManyToOne
|
||||
private EpochEntity epoch; // Ассоциация с EpochEntity
|
||||
|
||||
@ManyToOne
|
||||
private CountryEntity country; // Ассоциация с CountryEntity
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Перечислите свойства ассоциаций в ООП.
|
||||
|
||||
Свойства ассоциаций:
|
||||
- **Кратность** (1:1, 1:N, N:M)
|
||||
- **Направленность** (однонаправленная/двунаправленная)
|
||||
- **Обязательность** (обязательная/опциональная)
|
||||
- **Каскадность** (cascade)
|
||||
|
||||
**Пример из проекта:**
|
||||
- **Кратность**: `@ManyToOne` (строка 19) — многие артисты к одной эпохе
|
||||
- **Направленность**: Двунаправленная связь (ArtistEntity ↔ EpochEntity)
|
||||
- **Обязательность**: `nullable = false` (строка 18) — обязательная связь
|
||||
- **Каскадность**: Не используется (по умолчанию нет каскада)
|
||||
|
||||
---
|
||||
|
||||
## 12. Какими двумя способами можно представить связи между сущностями в реляционной БД?
|
||||
|
||||
1. **Внешний ключ (Foreign Key)** — в таблице "многих"
|
||||
2. **Связующая таблица (Join Table)** — для связи многие-ко-многим
|
||||
|
||||
**Пример из проекта:**
|
||||
- Используется внешний ключ:
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 18-20:
|
||||
```java
|
||||
@JoinColumn(name = "epoch_id", nullable = false) // Внешний ключ в таблице artists
|
||||
@ManyToOne
|
||||
private EpochEntity epoch;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 13. Что такое JPA?
|
||||
|
||||
**JPA (Java Persistence API)** — стандарт Java для работы с персистентностью, часть спецификации Jakarta EE.
|
||||
|
||||
**Пример из проекта:**
|
||||
- Используются JPA аннотации из пакета `jakarta.persistence`:
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 3-6:
|
||||
```java
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. Что такое Hibernate?
|
||||
|
||||
**Hibernate** — реализация JPA, ORM-фреймворк для Java.
|
||||
|
||||
**Пример из проекта:**
|
||||
- Hibernate используется через Spring Boot:
|
||||
- `demo/src/main/resources/application.properties`, строка 10:
|
||||
```properties
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 15. Чем JPA отличается от Hibernate?
|
||||
|
||||
- **JPA** — это спецификация (стандарт)
|
||||
- **Hibernate** — это реализация JPA
|
||||
|
||||
**Пример из проекта:**
|
||||
- Используются JPA аннотации (`@Entity`, `@Column`), но работает через Hibernate
|
||||
- `demo/src/main/java/com/example/demo/entity/BaseEntity.java`, строки 11-13:
|
||||
```java
|
||||
@Id // JPA аннотация
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE) // JPA
|
||||
@SequenceGenerator(name = "hibernate_sequence") // Hibernate
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 16. Что такое Spring Data?
|
||||
|
||||
**Spring Data** — проект Spring для упрощения работы с данными, предоставляет репозитории.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строка 12:
|
||||
```java
|
||||
public interface ArtistRepository extends JpaRepository<ArtistEntity, Long>
|
||||
```
|
||||
`JpaRepository` — часть Spring Data JPA, автоматически реализует CRUD операции.
|
||||
|
||||
---
|
||||
|
||||
## 17. Что такое соглашение по умолчанию (convention over configuration)?
|
||||
|
||||
**Convention over Configuration** — принцип, когда фреймворк использует разумные значения по умолчанию, уменьшая необходимость в конфигурации.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строки 13-17:
|
||||
```java
|
||||
List<ArtistEntity> findByEpochId(Long epochId);
|
||||
```
|
||||
Spring Data автоматически создает SQL-запрос по имени метода, не нужно писать реализацию.
|
||||
|
||||
---
|
||||
|
||||
## 18. Для чего используется аннотация @Entity?
|
||||
|
||||
`@Entity` помечает класс как JPA сущность, которая будет отображаться в таблицу БД.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строка 9:
|
||||
```java
|
||||
@Entity
|
||||
@Table(name = "artists")
|
||||
public class ArtistEntity extends BaseEntity {
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 19. Для чего используется аннотация @SecondaryTable?
|
||||
|
||||
`@SecondaryTable` используется для отображения сущности на несколько таблиц (в нашем проекте не используется).
|
||||
|
||||
---
|
||||
|
||||
## 20. Для чего используются аннотации @Embeddable и @Embedded?
|
||||
|
||||
`@Embeddable` и `@Embedded` используются для встраивания одного объекта в другой без отдельной таблицы (в нашем проекте не используется).
|
||||
|
||||
---
|
||||
|
||||
## 21. Для чего используются аннотации @Id и @GeneratedValue?
|
||||
|
||||
`@Id` помечает поле как первичный ключ, `@GeneratedValue` указывает стратегию генерации ID.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/BaseEntity.java`, строки 11-13:
|
||||
```java
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
@SequenceGenerator(name = "hibernate_sequence")
|
||||
protected Long id;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 22. Для чего используются аннотации @Embeddable и @EmbeddedId?
|
||||
|
||||
Используются для составных первичных ключей через встраиваемый класс (в нашем проекте не используется).
|
||||
|
||||
---
|
||||
|
||||
## 23. Для чего используется аннотация @IdClass?
|
||||
|
||||
`@IdClass` используется для составных первичных ключей через отдельный класс (в нашем проекте не используется).
|
||||
|
||||
---
|
||||
|
||||
## 24. В чем разница между @EmbeddedId и @IdClass?
|
||||
|
||||
- `@EmbeddedId` — составной ключ как встроенный объект
|
||||
- `@IdClass` — составной ключ как отдельный класс
|
||||
|
||||
В нашем проекте используется простой `@Id` (Long), составные ключи не используются.
|
||||
|
||||
---
|
||||
|
||||
## 25. Для чего используются аннотации @Basic и @Column?
|
||||
|
||||
`@Basic` указывает базовое отображение поля, `@Column` настраивает колонку в таблице.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 12-16:
|
||||
```java
|
||||
@Column(nullable = false) // Колонка не может быть null
|
||||
private String name;
|
||||
|
||||
@Column(columnDefinition = "text") // Тип колонки - text
|
||||
private String description;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 26. Для чего используются аннотации @Lob, @Basic, @Column, @Temporal и @Transient?
|
||||
|
||||
- `@Lob` — для больших объектов (BLOB/CLOB)
|
||||
- `@Basic` — базовое отображение
|
||||
- `@Column` — настройка колонки
|
||||
- `@Temporal` — для дат/времени
|
||||
- `@Transient` — поле не сохраняется в БД
|
||||
|
||||
**Пример из проекта:**
|
||||
- `@Column` используется в `ArtistEntity.java`, строка 15:
|
||||
```java
|
||||
@Column(columnDefinition = "text") // Текстовое поле
|
||||
private String description;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 27. Для чего используется аннотация @Enumerated?
|
||||
|
||||
`@Enumerated` используется для сохранения enum в БД (в нашем проекте не используется).
|
||||
|
||||
---
|
||||
|
||||
## 28. Для чего используется аннотация @Access?
|
||||
|
||||
`@Access` определяет способ доступа к полям (FIELD или PROPERTY) (в нашем проекте используется FIELD по умолчанию).
|
||||
|
||||
---
|
||||
|
||||
## 29. Какие аннотации используются для отображения разных типов связей?
|
||||
|
||||
- `@OneToOne` — один к одному
|
||||
- `@OneToMany` — один ко многим
|
||||
- `@ManyToOne` — многие к одному
|
||||
- `@ManyToMany` — многие ко многим
|
||||
|
||||
**Примеры из проекта:**
|
||||
- `@ManyToOne`: `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строка 19:
|
||||
```java
|
||||
@ManyToOne
|
||||
private EpochEntity epoch;
|
||||
```
|
||||
|
||||
- `@OneToMany`: `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строка 18:
|
||||
```java
|
||||
@OneToMany(mappedBy = "epoch")
|
||||
private Set<ArtistEntity> artists = new HashSet<>();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 30. Приведите пример реализации однонаправленной one to one связи.
|
||||
|
||||
В нашем проекте нет one-to-one связи. Пример был бы:
|
||||
```java
|
||||
@Entity
|
||||
public class ArtistEntity {
|
||||
@OneToOne
|
||||
@JoinColumn(name = "profile_id")
|
||||
private ProfileEntity profile;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 31. Приведите пример реализации однонаправленной one to many связи.
|
||||
|
||||
В нашем проекте все связи двунаправленные. Пример однонаправленной:
|
||||
```java
|
||||
@Entity
|
||||
public class EpochEntity {
|
||||
@OneToMany
|
||||
@JoinColumn(name = "epoch_id")
|
||||
private List<ArtistEntity> artists;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 32. Приведите пример реализации двунаправленной one to many связи.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строки 18-20:
|
||||
```java
|
||||
@OneToMany(mappedBy = "epoch")
|
||||
@OrderBy("id ASC")
|
||||
private Set<ArtistEntity> artists = new HashSet<>();
|
||||
```
|
||||
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 18-20:
|
||||
```java
|
||||
@JoinColumn(name = "epoch_id", nullable = false)
|
||||
@ManyToOne
|
||||
private EpochEntity epoch;
|
||||
```
|
||||
|
||||
Связь двунаправленная: `EpochEntity` имеет коллекцию `artists`, а `ArtistEntity` имеет ссылку `epoch`.
|
||||
|
||||
---
|
||||
|
||||
## 33. Приведите пример реализации двунаправленной many to many связи.
|
||||
|
||||
В нашем проекте нет many-to-many связи. Пример:
|
||||
```java
|
||||
@Entity
|
||||
public class ArtistEntity {
|
||||
@ManyToMany
|
||||
@JoinTable(name = "artist_genre",
|
||||
joinColumns = @JoinColumn(name = "artist_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "genre_id"))
|
||||
private Set<GenreEntity> genres;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 34. Какие стратегии выборки данных для связей можно использовать?
|
||||
|
||||
- **LAZY** — ленивая загрузка (по умолчанию для `@OneToMany`, `@ManyToMany`)
|
||||
- **EAGER** — жадная загрузка (по умолчанию для `@OneToOne`, `@ManyToOne`)
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строка 18:
|
||||
```java
|
||||
@OneToMany(mappedBy = "epoch") // LAZY по умолчанию
|
||||
private Set<ArtistEntity> artists;
|
||||
```
|
||||
|
||||
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строка 19:
|
||||
```java
|
||||
@ManyToOne // EAGER по умолчанию
|
||||
private EpochEntity epoch;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 35. Чем отличаются стратегии Lazy и Eager?
|
||||
|
||||
- **LAZY** — данные загружаются только при обращении (ленивая загрузка)
|
||||
- **EAGER** — данные загружаются сразу вместе с родительским объектом (жадная загрузка)
|
||||
|
||||
**Пример из проекта:**
|
||||
- При загрузке `ArtistEntity` эпоха загружается сразу (EAGER)
|
||||
- При загрузке `EpochEntity` артисты загружаются только при обращении к `getArtists()` (LAZY)
|
||||
|
||||
---
|
||||
|
||||
## 36. Как принимается решение об используемой стратегии выборки данных?
|
||||
|
||||
Решение принимается на основе:
|
||||
- Частоты использования связи
|
||||
- Производительности
|
||||
- Размера связанных данных
|
||||
|
||||
**Пример из проекта:**
|
||||
- `@ManyToOne` — EAGER, так как обычно нужна эпоха/страна артиста
|
||||
- `@OneToMany` — LAZY, так как коллекция может быть большой
|
||||
|
||||
---
|
||||
|
||||
## 37. Для чего используются аннотации @OrderBy и @OrderColumn?
|
||||
|
||||
`@OrderBy` сортирует коллекцию при загрузке, `@OrderColumn` сохраняет порядок в отдельной колонке.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строки 18-20:
|
||||
```java
|
||||
@OneToMany(mappedBy = "epoch")
|
||||
@OrderBy("id ASC") // Сортировка по id при загрузке
|
||||
private Set<ArtistEntity> artists = new HashSet<>();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 38. Когда для работы со связями следует использовать изменение данных в коллекции объекта?
|
||||
|
||||
Когда связь управляется владельцем (owner side), изменения в коллекции синхронизируются с БД.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строки 43-50:
|
||||
```java
|
||||
public void addArtist(ArtistEntity artist) {
|
||||
if (!artists.contains(artist)) {
|
||||
artists.add(artist); // Изменение коллекции
|
||||
if (artist.getEpoch() != this) {
|
||||
artist.setEpoch(this); // Синхронизация обратной связи
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 39. Когда для работы со связями следует использовать DAO?
|
||||
|
||||
DAO (Data Access Object) используется для сложных операций, которые нельзя выразить через методы сущности.
|
||||
|
||||
**Пример из проекта:**
|
||||
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строки 19-23:
|
||||
```java
|
||||
@Query("select count(a) as totalArtists, ...")
|
||||
ArtistStatsProjection getArtistsStatistics();
|
||||
```
|
||||
Сложные запросы со статистикой выполняются через репозиторий (аналог DAO), а не через методы сущности.
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
# Инструкция по запуску приложения
|
||||
|
||||
## Требования
|
||||
|
||||
- **Java 21** (JDK 21)
|
||||
- **Gradle** (обычно входит в проект через Gradle Wrapper)
|
||||
|
||||
Проверьте версию Java:
|
||||
```bash
|
||||
java -version
|
||||
```
|
||||
|
||||
Должно быть что-то вроде:
|
||||
```
|
||||
openjdk version "21.x.x"
|
||||
```
|
||||
|
||||
## Способы запуска
|
||||
|
||||
### 1. Через Gradle Wrapper (рекомендуется)
|
||||
|
||||
#### Windows:
|
||||
```bash
|
||||
cd demo
|
||||
.\gradlew.bat bootRun
|
||||
```
|
||||
|
||||
#### Linux/Mac:
|
||||
```bash
|
||||
cd demo
|
||||
./gradlew bootRun
|
||||
```
|
||||
|
||||
### 2. Через IDE (IntelliJ IDEA / Eclipse)
|
||||
|
||||
1. Откройте проект в IDE
|
||||
2. Найдите класс `DemoApplication.java` в пакете `com.example.demo`
|
||||
3. Правой кнопкой мыши → `Run 'DemoApplication'`
|
||||
|
||||
### 3. Сборка и запуск JAR файла
|
||||
|
||||
#### Сборка:
|
||||
```bash
|
||||
cd demo
|
||||
.\gradlew.bat bootJar # Windows
|
||||
# или
|
||||
./gradlew bootJar # Linux/Mac
|
||||
```
|
||||
|
||||
#### Запуск:
|
||||
```bash
|
||||
java -jar build/libs/demo-0.0.1-SNAPSHOT.jar
|
||||
```
|
||||
|
||||
## Что происходит при запуске
|
||||
|
||||
1. **Создается база данных H2** в файле `./data.mv.db` (в папке `demo`)
|
||||
2. **Автоматически создаются таблицы** (благодаря `ddl-auto=create`):
|
||||
- `epochs`
|
||||
- `countries`
|
||||
- `artists`
|
||||
3. **Автоматически создаются начальные данные** (если база пустая):
|
||||
- **Страны**: Россия, США, Великобритания, Германия, Франция, Япония
|
||||
- **Эпохи**: 1970-е, 1980-е, 1990-е, 2000-е, 2010-е, 2020-е
|
||||
4. **Приложение запускается** на порту **8080**
|
||||
|
||||
> **Примечание**: Начальные данные создаются только если база данных пустая. При последующих запусках данные сохраняются (если не удалить файл `data.mv.db`).
|
||||
|
||||
## Проверка работы
|
||||
|
||||
### 1. Проверка через браузер
|
||||
|
||||
Откройте в браузере:
|
||||
- **Swagger UI**: http://localhost:8080/swagger-ui.html
|
||||
- **API Docs**: http://localhost:8080/api-docs
|
||||
|
||||
### 2. Проверка через H2 Console
|
||||
|
||||
1. Откройте в браузере: http://localhost:8080/h2-console
|
||||
2. Настройки подключения:
|
||||
- **JDBC URL**: `jdbc:h2:file:./data`
|
||||
- **User Name**: `sa`
|
||||
- **Password**: `sa`
|
||||
3. Нажмите "Connect"
|
||||
4. Выполните SQL запрос:
|
||||
```sql
|
||||
SELECT * FROM artists;
|
||||
SELECT * FROM epochs;
|
||||
SELECT * FROM countries;
|
||||
```
|
||||
|
||||
### 3. Проверка через API
|
||||
|
||||
Используйте Swagger UI или любой HTTP клиент (Postman, curl):
|
||||
|
||||
#### Примеры запросов:
|
||||
|
||||
**Создать эпоху:**
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/api/epochs \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "1980-е"}'
|
||||
```
|
||||
|
||||
**Создать страну:**
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/api/countries \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "Россия"}'
|
||||
```
|
||||
|
||||
**Получить всех артистов:**
|
||||
```bash
|
||||
curl http://localhost:8080/api/artists
|
||||
```
|
||||
|
||||
## Запуск тестов
|
||||
|
||||
### Через Gradle:
|
||||
```bash
|
||||
cd demo
|
||||
.\gradlew.bat test # Windows
|
||||
# или
|
||||
./gradlew test # Linux/Mac
|
||||
```
|
||||
|
||||
### Через IDE:
|
||||
Правой кнопкой на папке `test` → `Run Tests`
|
||||
|
||||
## Структура базы данных
|
||||
|
||||
После первого запуска в папке `demo` появится файл:
|
||||
- `data.mv.db` - файл базы данных H2
|
||||
|
||||
**Важно**: При каждом запуске с `ddl-auto=create` таблицы пересоздаются заново, поэтому данные не сохраняются между перезапусками.
|
||||
|
||||
Если нужно сохранять данные между запусками, измените в `application.properties`:
|
||||
```properties
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
```
|
||||
|
||||
## Возможные проблемы
|
||||
|
||||
### 1. Порт 8080 занят
|
||||
|
||||
**Ошибка**: `Port 8080 is already in use`
|
||||
|
||||
**Решение**:
|
||||
- Измените порт в `application.properties`:
|
||||
```properties
|
||||
server.port=8081
|
||||
```
|
||||
- Или остановите процесс, использующий порт 8080
|
||||
|
||||
### 2. Java версия не подходит
|
||||
|
||||
**Ошибка**: `Unsupported class file major version`
|
||||
|
||||
**Решение**: Установите Java 21
|
||||
|
||||
### 3. База данных не создается
|
||||
|
||||
**Решение**:
|
||||
- Убедитесь, что у приложения есть права на запись в папку `demo`
|
||||
- Проверьте настройки в `application.properties`
|
||||
|
||||
### 4. Ошибки компиляции
|
||||
|
||||
**Решение**:
|
||||
```bash
|
||||
cd demo
|
||||
.\gradlew.bat clean build
|
||||
```
|
||||
|
||||
## Полезные команды
|
||||
|
||||
### Очистка проекта:
|
||||
```bash
|
||||
.\gradlew.bat clean
|
||||
```
|
||||
|
||||
### Пересборка:
|
||||
```bash
|
||||
.\gradlew.bat clean build
|
||||
```
|
||||
|
||||
### Просмотр зависимостей:
|
||||
```bash
|
||||
.\gradlew.bat dependencies
|
||||
```
|
||||
|
||||
### Запуск с отладкой:
|
||||
Добавьте в `application.properties`:
|
||||
```properties
|
||||
logging.level.com.example.demo=DEBUG
|
||||
```
|
||||
|
||||
## Остановка приложения
|
||||
|
||||
- В терминале: `Ctrl + C`
|
||||
- В IDE: нажмите кнопку "Stop" в панели запуска
|
||||
|
||||
## Следующие шаги
|
||||
|
||||
1. Откройте Swagger UI: http://localhost:8080/swagger-ui.html
|
||||
2. Протестируйте API через Swagger
|
||||
3. Проверьте данные в H2 Console
|
||||
4. Запустите тесты для проверки функциональности
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.2.5'
|
||||
id 'io.spring.dependency-management' version '1.1.5'
|
||||
}
|
||||
|
||||
group = 'com.example'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
description = 'Demo project for Spring Boot'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
ext {
|
||||
h2Version = "2.4.240"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation "com.h2database:h2:${h2Version}"
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
BIN
demo/data.mv.db
@@ -1,60 +0,0 @@
|
||||
2025-11-14 20:15:51.893939+04:00 jdbc[13]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "[*]DROPTABLE COUNTRIES"; ожидалось "DELETE, DROP"
|
||||
Syntax error in SQL statement "[*]DROPTABLE COUNTRIES"; expected "DELETE, DROP"; SQL statement:
|
||||
DROPTABLE COUNTRIES [42001-240]
|
||||
2025-11-14 20:16:02.103322+04:00 jdbc[13]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Невозможно удалить "COUNTRIES", пока существует зависимый объект "FK7SDOJ1330RH52SHDCVIL7SD4J"
|
||||
Cannot drop "COUNTRIES" because "FK7SDOJ1330RH52SHDCVIL7SD4J" depends on it; SQL statement:
|
||||
DROP TABLE COUNTRIES [90107-240]
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:644)
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
|
||||
at org.h2.message.DbException.get(DbException.java:223)
|
||||
at org.h2.command.ddl.DropTable.prepareDrop(DropTable.java:104)
|
||||
at org.h2.command.ddl.DropTable.update(DropTable.java:129)
|
||||
at org.h2.command.CommandContainer.update(CommandContainer.java:139)
|
||||
at org.h2.command.Command.executeUpdate(Command.java:306)
|
||||
at org.h2.command.Command.executeUpdate(Command.java:250)
|
||||
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:262)
|
||||
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
|
||||
at org.h2.server.web.WebApp.getResult(WebApp.java:1344)
|
||||
at org.h2.server.web.WebApp.query(WebApp.java:1142)
|
||||
at org.h2.server.web.WebApp.query(WebApp.java:1118)
|
||||
at org.h2.server.web.WebApp.process(WebApp.java:244)
|
||||
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
|
||||
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
|
||||
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:206)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
|
||||
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
|
||||
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
|
||||
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
|
||||
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
|
||||
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
|
||||
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
|
||||
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
|
||||
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
|
||||
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
|
||||
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736)
|
||||
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
|
||||
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)
|
||||
at java.base/java.lang.Thread.run(Thread.java:1583)
|
||||
BIN
demo/gradle/wrapper/gradle-wrapper.jar
vendored
@@ -1,7 +0,0 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
251
demo/gradlew
vendored
@@ -1,251 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
94
demo/gradlew.bat
vendored
@@ -1,94 +0,0 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -1 +0,0 @@
|
||||
rootProject.name = 'demo'
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.example.demo.config;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.info.Contact;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class OpenApiConfig {
|
||||
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("Punk Rock API")
|
||||
.version("1.0.0")
|
||||
.description("REST API для управления данными о панк-рок исполнителях")
|
||||
.contact(new Contact()
|
||||
.name("Developer")
|
||||
.email("developer@example.com")));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.example.demo.configuration;
|
||||
|
||||
public class Constants {
|
||||
public static final String DEV_ORIGIN = "http://localhost:5173";
|
||||
public static final String API_URL = "/api";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.example.demo.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry
|
||||
.addMapping(Constants.API_URL + "/**")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedOrigins("http://localhost:3000", "http://localhost:5173", Constants.DEV_ORIGIN)
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import com.example.demo.configuration.Constants;
|
||||
import com.example.demo.dto.ArtistRq;
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.service.ArtistService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + ArtistController.URL)
|
||||
public class ArtistController {
|
||||
public static final String URL = "/artists";
|
||||
private final ArtistService artistService;
|
||||
|
||||
public ArtistController(ArtistService artistService) {
|
||||
this.artistService = artistService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<ArtistRs> getAll() {
|
||||
return artistService.getAll();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ArtistRs get(@PathVariable Long id) {
|
||||
return artistService.get(id);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ArtistRs create(@RequestBody @Valid ArtistRq dto) {
|
||||
return artistService.create(dto);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ArtistRs update(@PathVariable Long id, @RequestBody @Valid ArtistRq dto) {
|
||||
return artistService.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ArtistRs delete(@PathVariable Long id) {
|
||||
return artistService.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import com.example.demo.configuration.Constants;
|
||||
import com.example.demo.dto.CountryRq;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.service.CountryService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + CountryController.URL)
|
||||
public class CountryController {
|
||||
public static final String URL = "/countries";
|
||||
private final CountryService countryService;
|
||||
|
||||
public CountryController(CountryService countryService) {
|
||||
this.countryService = countryService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<CountryRs> getAll() {
|
||||
return countryService.getAll();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public CountryRs get(@PathVariable Long id) {
|
||||
return countryService.get(id);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public CountryRs create(@RequestBody @Valid CountryRq dto) {
|
||||
return countryService.create(dto);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public CountryRs update(@PathVariable Long id, @RequestBody @Valid CountryRq dto) {
|
||||
return countryService.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public CountryRs delete(@PathVariable Long id) {
|
||||
return countryService.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import com.example.demo.configuration.Constants;
|
||||
import com.example.demo.dto.EpochRq;
|
||||
import com.example.demo.dto.EpochRs;
|
||||
import com.example.demo.service.EpochService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + EpochController.URL)
|
||||
public class EpochController {
|
||||
public static final String URL = "/epochs";
|
||||
private final EpochService epochService;
|
||||
|
||||
public EpochController(EpochService epochService) {
|
||||
this.epochService = epochService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<EpochRs> getAll() {
|
||||
return epochService.getAll();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public EpochRs get(@PathVariable Long id) {
|
||||
return epochService.get(id);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public EpochRs create(@RequestBody @Valid EpochRq dto) {
|
||||
return epochService.create(dto);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public EpochRs update(@PathVariable Long id, @RequestBody @Valid EpochRq dto) {
|
||||
return epochService.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public EpochRs delete(@PathVariable Long id) {
|
||||
return epochService.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class ArtistDto {
|
||||
private Integer id;
|
||||
private String name;
|
||||
private String description;
|
||||
private Integer epochId;
|
||||
private Integer countryId;
|
||||
|
||||
public ArtistDto() {}
|
||||
|
||||
public ArtistDto(Integer id, String name, String description, Integer epochId, Integer countryId) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.epochId = epochId;
|
||||
this.countryId = countryId;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Integer getEpochId() {
|
||||
return epochId;
|
||||
}
|
||||
|
||||
public void setEpochId(Integer epochId) {
|
||||
this.epochId = epochId;
|
||||
}
|
||||
|
||||
public Integer getCountryId() {
|
||||
return countryId;
|
||||
}
|
||||
|
||||
public void setCountryId(Integer countryId) {
|
||||
this.countryId = countryId;
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class ArtistRq {
|
||||
@NotBlank
|
||||
private String name;
|
||||
private String description;
|
||||
@NotNull
|
||||
private Long epochId;
|
||||
@NotNull
|
||||
private Long countryId;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Long getEpochId() {
|
||||
return epochId;
|
||||
}
|
||||
|
||||
public void setEpochId(Long epochId) {
|
||||
this.epochId = epochId;
|
||||
}
|
||||
|
||||
public Long getCountryId() {
|
||||
return countryId;
|
||||
}
|
||||
|
||||
public void setCountryId(Long countryId) {
|
||||
this.countryId = countryId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class ArtistRs {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private EpochRs epoch;
|
||||
private CountryRs country;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public EpochRs getEpoch() {
|
||||
return epoch;
|
||||
}
|
||||
|
||||
public void setEpoch(EpochRs epoch) {
|
||||
this.epoch = epoch;
|
||||
}
|
||||
|
||||
public CountryRs getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(CountryRs country) {
|
||||
this.country = country;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class CountryDto {
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
public CountryDto() {}
|
||||
|
||||
public CountryDto(Integer id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class CountryRq {
|
||||
@NotBlank
|
||||
private String name;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class CountryRs {
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class EpochDto {
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
public EpochDto() {}
|
||||
|
||||
public EpochDto(Integer id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class EpochRq {
|
||||
@NotBlank
|
||||
private String name;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class EpochRs {
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "artists")
|
||||
public class ArtistEntity extends BaseEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(columnDefinition = "text")
|
||||
private String description;
|
||||
|
||||
@JoinColumn(name = "epoch_id", nullable = false)
|
||||
@ManyToOne
|
||||
private EpochEntity epoch;
|
||||
|
||||
@JoinColumn(name = "country_id", nullable = false)
|
||||
@ManyToOne
|
||||
private CountryEntity country;
|
||||
|
||||
public ArtistEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ArtistEntity(String name, String description, EpochEntity epoch, CountryEntity country) {
|
||||
this();
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
setEpoch(epoch);
|
||||
setCountry(country);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public EpochEntity getEpoch() {
|
||||
return epoch;
|
||||
}
|
||||
|
||||
public void setEpoch(EpochEntity epoch) {
|
||||
if (this.epoch == epoch) {
|
||||
return;
|
||||
}
|
||||
if (this.epoch != null) {
|
||||
EpochEntity oldEpoch = this.epoch;
|
||||
this.epoch = null;
|
||||
oldEpoch.removeArtist(this);
|
||||
}
|
||||
this.epoch = epoch;
|
||||
if (epoch != null) {
|
||||
epoch.addArtist(this);
|
||||
}
|
||||
}
|
||||
|
||||
public CountryEntity getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(CountryEntity country) {
|
||||
if (this.country == country) {
|
||||
return;
|
||||
}
|
||||
if (this.country != null) {
|
||||
CountryEntity oldCountry = this.country;
|
||||
this.country = null;
|
||||
oldCountry.removeArtist(this);
|
||||
}
|
||||
this.country = country;
|
||||
if (country != null) {
|
||||
country.addArtist(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.SequenceGenerator;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
@SequenceGenerator(name = "hibernate_sequence")
|
||||
protected Long id;
|
||||
|
||||
protected BaseEntity() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "countries")
|
||||
public class CountryEntity extends BaseEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "country")
|
||||
@OrderBy("id ASC")
|
||||
private Set<ArtistEntity> artists = new HashSet<>();
|
||||
|
||||
public CountryEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public CountryEntity(String name) {
|
||||
this();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<ArtistEntity> getArtists() {
|
||||
return artists;
|
||||
}
|
||||
|
||||
public void addArtist(ArtistEntity artist) {
|
||||
if (!artists.contains(artist)) {
|
||||
artists.add(artist);
|
||||
if (artist.getCountry() != this) {
|
||||
artist.setCountry(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeArtist(ArtistEntity artist) {
|
||||
if (artists.contains(artist)) {
|
||||
artists.remove(artist);
|
||||
if (artist.getCountry() == this) {
|
||||
artist.setCountry(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "epochs")
|
||||
public class EpochEntity extends BaseEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "epoch")
|
||||
@OrderBy("id ASC")
|
||||
private Set<ArtistEntity> artists = new HashSet<>();
|
||||
|
||||
public EpochEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EpochEntity(String name) {
|
||||
this();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<ArtistEntity> getArtists() {
|
||||
return artists;
|
||||
}
|
||||
|
||||
public void addArtist(ArtistEntity artist) {
|
||||
if (!artists.contains(artist)) {
|
||||
artists.add(artist);
|
||||
if (artist.getEpoch() != this) {
|
||||
artist.setEpoch(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeArtist(ArtistEntity artist) {
|
||||
if (artists.contains(artist)) {
|
||||
artists.remove(artist);
|
||||
if (artist.getEpoch() == this) {
|
||||
artist.setEpoch(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.example.demo.entity.projection;
|
||||
|
||||
public interface ArtistStatsProjection {
|
||||
Long getTotalArtists();
|
||||
Long getArtistsWithDescription();
|
||||
Long getArtistsWithoutDescription();
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.example.demo.entity.projection;
|
||||
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
|
||||
public interface CountryStatsProjection {
|
||||
CountryEntity getCountry();
|
||||
Long getArtistsCount();
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.example.demo.entity.projection;
|
||||
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
|
||||
public interface EpochStatsProjection {
|
||||
EpochEntity getEpoch();
|
||||
Long getArtistsCount();
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.example.demo.error;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public <T> NotFoundException(Class<T> entClass, Long id) {
|
||||
super(String.format("%s with id %s is not found", entClass.getSimpleName(), id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.example.demo.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.example.demo.dto.ArtistRq;
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.entity.ArtistEntity;
|
||||
|
||||
@Component
|
||||
public class ArtistMapper {
|
||||
private final EpochMapper epochMapper;
|
||||
private final CountryMapper countryMapper;
|
||||
|
||||
public ArtistMapper(EpochMapper epochMapper, CountryMapper countryMapper) {
|
||||
this.epochMapper = epochMapper;
|
||||
this.countryMapper = countryMapper;
|
||||
}
|
||||
|
||||
public ArtistRq toRqDto(String name, String description, Long epochId, Long countryId) {
|
||||
final ArtistRq dto = new ArtistRq();
|
||||
dto.setName(name);
|
||||
dto.setDescription(description);
|
||||
dto.setEpochId(epochId);
|
||||
dto.setCountryId(countryId);
|
||||
return dto;
|
||||
}
|
||||
|
||||
public ArtistRs toRsDto(ArtistEntity entity) {
|
||||
final ArtistRs dto = new ArtistRs();
|
||||
dto.setId(entity.getId());
|
||||
dto.setName(entity.getName());
|
||||
dto.setDescription(entity.getDescription());
|
||||
if (entity.getEpoch() != null) {
|
||||
dto.setEpoch(epochMapper.toRsDto(entity.getEpoch()));
|
||||
}
|
||||
if (entity.getCountry() != null) {
|
||||
dto.setCountry(countryMapper.toRsDto(entity.getCountry()));
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<ArtistRs> toRsDtoList(Iterable<ArtistEntity> entities) {
|
||||
return StreamSupport.stream(entities.spliterator(), false)
|
||||
.map(this::toRsDto)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.example.demo.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.example.demo.dto.CountryRq;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
|
||||
@Component
|
||||
public class CountryMapper {
|
||||
public CountryRq toRqDto(String name) {
|
||||
final CountryRq dto = new CountryRq();
|
||||
dto.setName(name);
|
||||
return dto;
|
||||
}
|
||||
|
||||
public CountryRs toRsDto(CountryEntity entity) {
|
||||
final CountryRs dto = new CountryRs();
|
||||
dto.setId(entity.getId());
|
||||
dto.setName(entity.getName());
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<CountryRs> toRsDtoList(Iterable<CountryEntity> entities) {
|
||||
return StreamSupport.stream(entities.spliterator(), false)
|
||||
.map(this::toRsDto)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.example.demo.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.example.demo.dto.EpochRq;
|
||||
import com.example.demo.dto.EpochRs;
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
|
||||
@Component
|
||||
public class EpochMapper {
|
||||
public EpochRq toRqDto(String name) {
|
||||
final EpochRq dto = new EpochRq();
|
||||
dto.setName(name);
|
||||
return dto;
|
||||
}
|
||||
|
||||
public EpochRs toRsDto(EpochEntity entity) {
|
||||
final EpochRs dto = new EpochRs();
|
||||
dto.setId(entity.getId());
|
||||
dto.setName(entity.getName());
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<EpochRs> toRsDtoList(Iterable<EpochEntity> entities) {
|
||||
return StreamSupport.stream(entities.spliterator(), false)
|
||||
.map(this::toRsDto)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.demo.entity.ArtistEntity;
|
||||
import com.example.demo.entity.projection.ArtistStatsProjection;
|
||||
|
||||
public interface ArtistRepository extends JpaRepository<ArtistEntity, Long> {
|
||||
List<ArtistEntity> findByEpochId(Long epochId);
|
||||
|
||||
List<ArtistEntity> findByCountryId(Long countryId);
|
||||
|
||||
List<ArtistEntity> findByEpochIdAndCountryId(Long epochId, Long countryId);
|
||||
|
||||
@Query("select count(a) as totalArtists, " +
|
||||
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
|
||||
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
|
||||
"from ArtistEntity a")
|
||||
ArtistStatsProjection getArtistsStatistics();
|
||||
|
||||
@Query("select count(a) as totalArtists, " +
|
||||
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
|
||||
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
|
||||
"from ArtistEntity a " +
|
||||
"where a.epoch.id = :epochId")
|
||||
ArtistStatsProjection getArtistsStatisticsByEpoch(@Param("epochId") Long epochId);
|
||||
|
||||
@Query("select count(a) as totalArtists, " +
|
||||
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
|
||||
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
|
||||
"from ArtistEntity a " +
|
||||
"where a.country.id = :countryId")
|
||||
ArtistStatsProjection getArtistsStatisticsByCountry(@Param("countryId") Long countryId);
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
import com.example.demo.entity.projection.CountryStatsProjection;
|
||||
|
||||
public interface CountryRepository extends JpaRepository<CountryEntity, Long> {
|
||||
Optional<CountryEntity> findOneByNameIgnoreCase(String name);
|
||||
|
||||
@Query("select c as country, count(a) as artistsCount " +
|
||||
"from CountryEntity c left join c.artists a " +
|
||||
"group by c " +
|
||||
"order by c.id")
|
||||
List<CountryStatsProjection> getAllCountriesStatistics();
|
||||
|
||||
@Query("select c as country, count(a) as artistsCount " +
|
||||
"from CountryEntity c left join c.artists a " +
|
||||
"where c.id = :countryId " +
|
||||
"group by c")
|
||||
CountryStatsProjection getCountryStatistics(@Param("countryId") Long countryId);
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
import com.example.demo.entity.projection.EpochStatsProjection;
|
||||
|
||||
public interface EpochRepository extends JpaRepository<EpochEntity, Long> {
|
||||
Optional<EpochEntity> findOneByNameIgnoreCase(String name);
|
||||
|
||||
@Query("select e as epoch, count(a) as artistsCount " +
|
||||
"from EpochEntity e left join e.artists a " +
|
||||
"group by e " +
|
||||
"order by e.id")
|
||||
List<EpochStatsProjection> getAllEpochsStatistics();
|
||||
|
||||
@Query("select e as epoch, count(a) as artistsCount " +
|
||||
"from EpochEntity e left join e.artists a " +
|
||||
"where e.id = :epochId " +
|
||||
"group by e")
|
||||
EpochStatsProjection getEpochStatistics(@Param("epochId") Long epochId);
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.dto.ArtistRq;
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.entity.ArtistEntity;
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.ArtistMapper;
|
||||
import com.example.demo.repository.ArtistRepository;
|
||||
|
||||
@Service
|
||||
public class ArtistService {
|
||||
private final ArtistRepository repository;
|
||||
private final EpochService epochService;
|
||||
private final CountryService countryService;
|
||||
private final ArtistMapper mapper;
|
||||
|
||||
public ArtistService(ArtistRepository repository, EpochService epochService,
|
||||
CountryService countryService, ArtistMapper mapper) {
|
||||
this.repository = repository;
|
||||
this.epochService = epochService;
|
||||
this.countryService = countryService;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public ArtistEntity getEntity(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(ArtistEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ArtistRs> getAll() {
|
||||
return mapper.toRsDtoList(repository.findAll());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ArtistRs get(Long id) {
|
||||
final ArtistEntity entity = getEntity(id);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ArtistRs create(ArtistRq dto) {
|
||||
final EpochEntity epoch = epochService.getEntity(dto.getEpochId());
|
||||
final CountryEntity country = countryService.getEntity(dto.getCountryId());
|
||||
ArtistEntity entity = new ArtistEntity(
|
||||
dto.getName(),
|
||||
dto.getDescription(),
|
||||
epoch,
|
||||
country);
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ArtistRs update(Long id, ArtistRq dto) {
|
||||
ArtistEntity entity = getEntity(id);
|
||||
entity.setName(dto.getName());
|
||||
entity.setDescription(dto.getDescription());
|
||||
entity.setEpoch(epochService.getEntity(dto.getEpochId()));
|
||||
entity.setCountry(countryService.getEntity(dto.getCountryId()));
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ArtistRs delete(Long id) {
|
||||
final ArtistEntity entity = getEntity(id);
|
||||
repository.delete(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.dto.CountryRq;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.CountryMapper;
|
||||
import com.example.demo.repository.CountryRepository;
|
||||
|
||||
@Service
|
||||
public class CountryService {
|
||||
private final CountryRepository repository;
|
||||
private final CountryMapper mapper;
|
||||
|
||||
public CountryService(CountryRepository repository, CountryMapper mapper) {
|
||||
this.repository = repository;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public CountryEntity getEntity(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(CountryEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<CountryRs> getAll() {
|
||||
return mapper.toRsDtoList(repository.findAll());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public CountryRs get(Long id) {
|
||||
final CountryEntity entity = getEntity(id);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CountryRs create(CountryRq dto) {
|
||||
CountryEntity entity = new CountryEntity(dto.getName());
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CountryRs update(Long id, CountryRq dto) {
|
||||
CountryEntity entity = getEntity(id);
|
||||
entity.setName(dto.getName());
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CountryRs delete(Long id) {
|
||||
final CountryEntity entity = getEntity(id);
|
||||
repository.delete(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.dto.EpochRq;
|
||||
import com.example.demo.dto.EpochRs;
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.EpochMapper;
|
||||
import com.example.demo.repository.EpochRepository;
|
||||
|
||||
@Service
|
||||
public class EpochService {
|
||||
private final EpochRepository repository;
|
||||
private final EpochMapper mapper;
|
||||
|
||||
public EpochService(EpochRepository repository, EpochMapper mapper) {
|
||||
this.repository = repository;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public EpochEntity getEntity(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(EpochEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<EpochRs> getAll() {
|
||||
return mapper.toRsDtoList(repository.findAll());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public EpochRs get(Long id) {
|
||||
final EpochEntity entity = getEntity(id);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EpochRs create(EpochRq dto) {
|
||||
EpochEntity entity = new EpochEntity(dto.getName());
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EpochRs update(Long id, EpochRq dto) {
|
||||
EpochEntity entity = getEntity(id);
|
||||
entity.setName(dto.getName());
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EpochRs delete(Long id) {
|
||||
final EpochEntity entity = getEntity(id);
|
||||
repository.delete(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
spring.application.name=demo
|
||||
server.port=8080
|
||||
springdoc.api-docs.path=/api-docs
|
||||
springdoc.swagger-ui.path=/swagger-ui.html
|
||||
|
||||
spring.datasource.url=jdbc:h2:file:./data
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=sa
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.h2.console.enabled=true
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class DemoApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.ArtistMapper;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
public class ArtistServiceTests {
|
||||
@Autowired
|
||||
private ArtistService service;
|
||||
@Autowired
|
||||
private EpochService epochService;
|
||||
@Autowired
|
||||
private CountryService countryService;
|
||||
@Autowired
|
||||
private ArtistMapper mapper;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getAllTest() {
|
||||
Assertions.assertNotNull(service.getAll());
|
||||
Assertions.assertTrue(service.getAll().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createTest() {
|
||||
// Создаем необходимые зависимости
|
||||
final var epochRq1 = new com.example.demo.dto.EpochRq();
|
||||
epochRq1.setName("1980-е");
|
||||
final var epoch1 = epochService.create(epochRq1);
|
||||
|
||||
final var epochRq2 = new com.example.demo.dto.EpochRq();
|
||||
epochRq2.setName("1990-е");
|
||||
final var epoch2 = epochService.create(epochRq2);
|
||||
|
||||
final var countryRq1 = new com.example.demo.dto.CountryRq();
|
||||
countryRq1.setName("Россия");
|
||||
final var country1 = countryService.create(countryRq1);
|
||||
|
||||
final var countryRq2 = new com.example.demo.dto.CountryRq();
|
||||
countryRq2.setName("США");
|
||||
final var country2 = countryService.create(countryRq2);
|
||||
|
||||
final ArtistRs artist1 = service.create(mapper.toRqDto("Artist 1", "Description 1", epoch1.getId(), country1.getId()));
|
||||
final ArtistRs artist2 = service.create(mapper.toRqDto("Artist 2", "Description 2", epoch2.getId(), country2.getId()));
|
||||
final ArtistRs artist3 = service.create(mapper.toRqDto("Artist 3", "Description 3", epoch1.getId(), country1.getId()));
|
||||
|
||||
Assertions.assertEquals(3, service.getAll().size());
|
||||
Assertions.assertNotNull(artist1.getId());
|
||||
Assertions.assertNotNull(artist2.getId());
|
||||
Assertions.assertNotNull(artist3.getId());
|
||||
|
||||
final ArtistRs cmpEntity = service.get(artist3.getId());
|
||||
Assertions.assertEquals(artist3.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(artist3.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateTest() {
|
||||
final var allArtists = service.getAll();
|
||||
Assertions.assertFalse(allArtists.isEmpty());
|
||||
|
||||
final ArtistRs entity = allArtists.get(0);
|
||||
final Long entityId = entity.getId();
|
||||
final String oldName = entity.getName();
|
||||
final var epoch = entity.getEpoch();
|
||||
final var country = entity.getCountry();
|
||||
|
||||
final String test = "TEST ARTIST";
|
||||
final ArtistRs newEntity = service.update(entityId, mapper.toRqDto(test, "New Description", epoch.getId(), country.getId()));
|
||||
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
|
||||
final ArtistRs cmpEntity = service.get(entityId);
|
||||
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteTest() {
|
||||
final var allArtists = service.getAll();
|
||||
final int initialSize = allArtists.size();
|
||||
Assertions.assertTrue(initialSize > 0);
|
||||
|
||||
final ArtistRs toDelete = allArtists.get(0);
|
||||
final Long deleteId = toDelete.getId();
|
||||
|
||||
service.delete(deleteId);
|
||||
Assertions.assertEquals(initialSize - 1, service.getAll().size());
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.CountryMapper;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
public class CountryServiceTests {
|
||||
@Autowired
|
||||
private CountryService service;
|
||||
@Autowired
|
||||
private CountryMapper mapper;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getAllTest() {
|
||||
Assertions.assertNotNull(service.getAll());
|
||||
Assertions.assertTrue(service.getAll().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createTest() {
|
||||
final CountryRs country1 = service.create(mapper.toRqDto("Россия"));
|
||||
final CountryRs country2 = service.create(mapper.toRqDto("США"));
|
||||
final CountryRs country3 = service.create(mapper.toRqDto("Тайга"));
|
||||
|
||||
Assertions.assertEquals(3, service.getAll().size());
|
||||
Assertions.assertNotNull(country1.getId());
|
||||
Assertions.assertNotNull(country2.getId());
|
||||
Assertions.assertNotNull(country3.getId());
|
||||
|
||||
final CountryRs cmpEntity = service.get(country3.getId());
|
||||
Assertions.assertEquals(country3.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(country3.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateTest() {
|
||||
final var allCountries = service.getAll();
|
||||
Assertions.assertFalse(allCountries.isEmpty());
|
||||
|
||||
final CountryRs entity = allCountries.get(0);
|
||||
final Long entityId = entity.getId();
|
||||
final String oldName = entity.getName();
|
||||
|
||||
final String test = "TEST";
|
||||
final CountryRs newEntity = service.update(entityId, mapper.toRqDto(test));
|
||||
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
|
||||
final CountryRs cmpEntity = service.get(entityId);
|
||||
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteTest() {
|
||||
final var allCountries = service.getAll();
|
||||
final int initialSize = allCountries.size();
|
||||
Assertions.assertTrue(initialSize > 0);
|
||||
|
||||
final CountryRs toDelete = allCountries.get(0);
|
||||
final Long deleteId = toDelete.getId();
|
||||
|
||||
service.delete(deleteId);
|
||||
Assertions.assertEquals(initialSize - 1, service.getAll().size());
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import com.example.demo.dto.EpochRs;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.EpochMapper;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
public class EpochServiceTests {
|
||||
@Autowired
|
||||
private EpochService service;
|
||||
@Autowired
|
||||
private EpochMapper mapper;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getAllTest() {
|
||||
Assertions.assertNotNull(service.getAll());
|
||||
Assertions.assertTrue(service.getAll().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createTest() {
|
||||
final EpochRs epoch1 = service.create(mapper.toRqDto("1980-е"));
|
||||
final EpochRs epoch2 = service.create(mapper.toRqDto("1990-е"));
|
||||
final EpochRs epoch3 = service.create(mapper.toRqDto("2000-е"));
|
||||
|
||||
Assertions.assertEquals(3, service.getAll().size());
|
||||
Assertions.assertNotNull(epoch1.getId());
|
||||
Assertions.assertNotNull(epoch2.getId());
|
||||
Assertions.assertNotNull(epoch3.getId());
|
||||
|
||||
final EpochRs cmpEntity = service.get(epoch3.getId());
|
||||
Assertions.assertEquals(epoch3.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(epoch3.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateTest() {
|
||||
final var allEpochs = service.getAll();
|
||||
Assertions.assertFalse(allEpochs.isEmpty());
|
||||
|
||||
final EpochRs entity = allEpochs.get(0);
|
||||
final Long entityId = entity.getId();
|
||||
final String oldName = entity.getName();
|
||||
|
||||
final String test = "TEST";
|
||||
final EpochRs newEntity = service.update(entityId, mapper.toRqDto(test));
|
||||
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
|
||||
final EpochRs cmpEntity = service.get(entityId);
|
||||
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteTest() {
|
||||
final var allEpochs = service.getAll();
|
||||
final int initialSize = allEpochs.size();
|
||||
Assertions.assertTrue(initialSize > 0);
|
||||
|
||||
final EpochRs toDelete = allEpochs.get(0);
|
||||
final Long deleteId = toDelete.getId();
|
||||
|
||||
service.delete(deleteId);
|
||||
Assertions.assertEquals(initialSize - 1, service.getAll().size());
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
|
||||
46
punk-rock-app/README.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
114
punk-rock-app/db.json
Normal file
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"artists": [
|
||||
{
|
||||
"id": "6",
|
||||
"name": "The Clash",
|
||||
"description": "Pioneers of British punk rock, known for their political lyrics.",
|
||||
"epochId": "1",
|
||||
"countryId": "1"
|
||||
},
|
||||
{
|
||||
"id": "7",
|
||||
"name": "Sex Pistols",
|
||||
"description": "Notorious for their rebellious attitude and controversial lyrics.",
|
||||
"epochId": "1",
|
||||
"countryId": "1"
|
||||
},
|
||||
{
|
||||
"id": "8",
|
||||
"name": "The Ramones",
|
||||
"description": "Influential American punk rock band, known for their fast-paced music.",
|
||||
"epochId": "1",
|
||||
"countryId": "1"
|
||||
},
|
||||
{
|
||||
"id": "9",
|
||||
"name": "The Damned",
|
||||
"description": "First British punk band to release a single and an album.",
|
||||
"epochId": "1",
|
||||
"countryId": "1"
|
||||
},
|
||||
{
|
||||
"id": "11",
|
||||
"name": "Red Hot Chili Peppers",
|
||||
"description": "Known for their unique fusion of punk rock and funkf",
|
||||
"epochId": "2",
|
||||
"countryId": "2",
|
||||
"epoch": {
|
||||
"id": "2",
|
||||
"name": "1990s"
|
||||
},
|
||||
"country": {
|
||||
"id": "2",
|
||||
"name": "UK"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "7fd4c5fb-933a-4496-967a-8d6b92252603",
|
||||
"name": "ыфвфвы",
|
||||
"description": "аыввавы",
|
||||
"epochId": "2",
|
||||
"countryId": "2"
|
||||
},
|
||||
{
|
||||
"id": "ac9dfa68-fd2c-44d4-8c25-fd9b417c2821",
|
||||
"name": "fdfddf",
|
||||
"description": "efeffdas",
|
||||
"epochId": "2",
|
||||
"countryId": "1"
|
||||
},
|
||||
{
|
||||
"id": "b8a25883-51c4-4075-87d7-a1906a34962e",
|
||||
"name": "Green Day",
|
||||
"description": "дддд",
|
||||
"epochId": "1",
|
||||
"countryId": "1"
|
||||
}
|
||||
],
|
||||
"epochs": [
|
||||
{
|
||||
"id": "1",
|
||||
"name": "1970s"
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"name": "1990s"
|
||||
}
|
||||
],
|
||||
"countries": [
|
||||
{
|
||||
"id": "1",
|
||||
"name": "USA"
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"name": "UK"
|
||||
}
|
||||
],
|
||||
"subscriptions": [
|
||||
{
|
||||
"id": "2",
|
||||
"userId": "2",
|
||||
"type": "Premium",
|
||||
"price": 15,
|
||||
"active": true
|
||||
},
|
||||
{
|
||||
"id": "4d38",
|
||||
"type": "Premium",
|
||||
"price": 15,
|
||||
"userId": 1,
|
||||
"active": true
|
||||
}
|
||||
],
|
||||
"users": [
|
||||
{
|
||||
"id": "1",
|
||||
"name": "User1"
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"name": "User2"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,21 +1,26 @@
|
||||
{
|
||||
"name": "punkrock-react",
|
||||
"name": "punk-rock-app",
|
||||
"version": "0.1.0",
|
||||
"homepage": "/punkrock",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@testing-library/dom": "^10.4.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"@types/jest": "^27.5.2",
|
||||
"@types/node": "^16.18.126",
|
||||
"@types/react": "^19.1.6",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"@types/react-router-dom": "^5.3.3",
|
||||
"axios": "^1.9.0",
|
||||
"bootstrap": "^5.3.6",
|
||||
"bootstrap-icons": "^1.13.1",
|
||||
"react": "^18.2.0",
|
||||
"react-bootstrap-icons": "^1.11.6",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^7.6.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-router-dom": "^7.6.1",
|
||||
"react-scripts": "5.0.1",
|
||||
"typescript": "^4.9.5",
|
||||
"uuid": "^11.1.0",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
@@ -41,6 +46,5 @@
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"devDependencies": {}
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.8 KiB |
@@ -6,7 +6,7 @@
|
||||
<link href="/styles.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
|
||||
<title>Панкуха</title>
|
||||
<title>Punk Rock App</title>
|
||||
</head>
|
||||
<body class="bg-dark text-light">
|
||||
<div id="root"></div>
|
||||
|
Before Width: | Height: | Size: 5.2 KiB After Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 9.4 KiB |
25
punk-rock-app/public/manifest.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
|
Before Width: | Height: | Size: 80 KiB After Width: | Height: | Size: 80 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 91 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 240 KiB After Width: | Height: | Size: 240 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 969 KiB After Width: | Height: | Size: 969 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 40 KiB |
@@ -27,8 +27,6 @@ a:hover {
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
background-color: var(--punk-dark);
|
||||
@@ -79,14 +77,18 @@ h1 {
|
||||
box-shadow: 0 5px 15px rgba(138, 43, 226, 0.3);
|
||||
}
|
||||
.btn-punk {
|
||||
background-color: blueviolet;
|
||||
color: white;
|
||||
border: none;
|
||||
background-color: blueviolet !important; /* Увеличиваем специфичность */
|
||||
color: white !important;
|
||||
border: none !important;
|
||||
padding: 0.6em 1.2em; /* Убедимся, что есть отступы */
|
||||
display: inline-block; /* Убедимся, что кнопка видна */
|
||||
visibility: visible; /* Убедимся, что не скрыта */
|
||||
opacity: 1; /* Убедимся, что не прозрачна */
|
||||
}
|
||||
|
||||
.btn-punk:hover {
|
||||
background-color: #9d4edd;
|
||||
color: white;
|
||||
background-color: #9d4edd !important;
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
.artist-card {
|
||||
@@ -101,7 +103,7 @@ h1 {
|
||||
.bg-punk {
|
||||
background-color: blueviolet !important;
|
||||
}
|
||||
/* Стиль кнопок */
|
||||
|
||||
.btn-outline-punk {
|
||||
color: blueviolet;
|
||||
border-color: blueviolet;
|
||||
@@ -186,4 +188,4 @@ button:focus-visible {
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import App from './App';
|
||||
|
||||
53
punk-rock-app/src/App.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import React from 'react';
|
||||
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
|
||||
import Home from './pages/Home';
|
||||
import Catalog from './pages/Catalog';
|
||||
import ArtistPage from './pages/ArtistPage';
|
||||
import ArtistsPage from './pages/ArtistsPage';
|
||||
|
||||
const App: React.FC = () => {
|
||||
return (
|
||||
<Router>
|
||||
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
|
||||
<div className="container">
|
||||
<Link className="navbar-brand text-punk" to="/">Панкуха</Link>
|
||||
<button
|
||||
className="navbar-toggler"
|
||||
type="button"
|
||||
data-bs-toggle="collapse"
|
||||
data-bs-target="#navbarNav"
|
||||
aria-controls="navbarNav"
|
||||
aria-expanded="false"
|
||||
aria-label="Toggle navigation"
|
||||
>
|
||||
<span className="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div className="collapse navbar-collapse" id="navbarNav">
|
||||
<ul className="navbar-nav">
|
||||
<li className="nav-item">
|
||||
<Link className="nav-link" to="/">Главная</Link>
|
||||
</li>
|
||||
<li className="nav-item">
|
||||
<Link className="nav-link" to="/catalog">Каталог</Link>
|
||||
</li>
|
||||
<li className="nav-item">
|
||||
<Link className="nav-link" to="/artist">Исполнитель</Link>
|
||||
</li>
|
||||
<li className="nav-item">
|
||||
<Link className="nav-link" to="/artists">Список исполнителей</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/catalog" element={<Catalog />} />
|
||||
<Route path="/artist" element={<ArtistPage />} />
|
||||
<Route path="/artists" element={<ArtistsPage />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
@@ -1,14 +1,27 @@
|
||||
import React from 'react';
|
||||
import { Artist, Epoch, Country } from '../types';
|
||||
|
||||
interface ArtistCardProps {
|
||||
artist: Artist;
|
||||
epochs: Epoch[];
|
||||
countries: Country[];
|
||||
onEdit: (artist: Artist) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
const ArtistCard: React.FC<ArtistCardProps> = ({ artist, epochs, countries, onEdit, onDelete }) => {
|
||||
// Получаем имена эпохи и страны по идентификаторам
|
||||
const epochName = epochs.find(e => e.id === artist.epochId)?.name || 'Не указана';
|
||||
const countryName = countries.find(c => c.id === artist.countryId)?.name || 'Не указана';
|
||||
|
||||
const ArtistCard = ({ artist, onEdit, onDelete }) => {
|
||||
return (
|
||||
<div className="col-md-4 mb-4">
|
||||
<div className="card bg-dark border-punk">
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-punk">{artist.name}</h5>
|
||||
<p className="card-text text-light">{artist.description || 'Нет описания'}</p>
|
||||
<p className="card-text text-light"><small>Эпоха: {artist.epoch?.name || 'Не указана'}</small></p>
|
||||
<p className="card-text text-light"><small>Страна: {artist.country?.name || 'Не указана'}</small></p>
|
||||
<p className="card-text text-light"><small>Эпоха: {epochName}</small></p>
|
||||
<p className="card-text text-light"><small>Страна: {countryName}</small></p>
|
||||
<button
|
||||
className="btn btn-outline-primary edit-btn me-2"
|
||||
onClick={() => onEdit(artist)}
|
||||
@@ -17,11 +30,7 @@ const ArtistCard = ({ artist, onEdit, onDelete }) => {
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-outline-danger delete-btn"
|
||||
onClick={() => {
|
||||
if (window.confirm('Удалить исполнителя?')) {
|
||||
onDelete(artist.id);
|
||||
}
|
||||
}}
|
||||
onClick={() => onDelete(artist.id)}
|
||||
>
|
||||
<i className="bi bi-trash"></i> Удалить
|
||||
</button>
|
||||
161
punk-rock-app/src/components/ArtistForm.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import React, { useState, useEffect, ChangeEvent } from 'react';
|
||||
import { Artist, Epoch, Country } from '../types';
|
||||
|
||||
interface ArtistFormProps {
|
||||
countries: Country[];
|
||||
epochs: Epoch[];
|
||||
onSubmit: (artist: Artist) => Promise<void>;
|
||||
artist?: Artist | null;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
const ArtistForm: React.FC<ArtistFormProps> = ({ countries, epochs, onSubmit, artist, onCancel }) => {
|
||||
const [formData, setFormData] = useState<Artist>({
|
||||
id: '',
|
||||
name: '',
|
||||
description: '',
|
||||
epochId: '',
|
||||
countryId: '',
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
console.log('ArtistForm artist prop:', artist);
|
||||
if (artist) {
|
||||
setFormData({
|
||||
id: artist.id,
|
||||
name: artist.name,
|
||||
description: artist.description,
|
||||
epochId: artist.epochId,
|
||||
countryId: artist.countryId,
|
||||
});
|
||||
} else {
|
||||
setFormData({
|
||||
id: '',
|
||||
name: '',
|
||||
description: '',
|
||||
epochId: '',
|
||||
countryId: '',
|
||||
});
|
||||
}
|
||||
}, [artist]);
|
||||
|
||||
const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[name]: value,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!formData.name || !formData.description || !formData.epochId || !formData.countryId) {
|
||||
setError('Все поля обязательны!');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setError(null);
|
||||
if (artist) {
|
||||
// Если редактируем существующего артиста, передаем id
|
||||
await onSubmit({ ...formData, id: artist.id });
|
||||
} else {
|
||||
// Если добавляем нового артиста, id не передаем
|
||||
await onSubmit(formData);
|
||||
}
|
||||
setFormData({
|
||||
id: '',
|
||||
name: '',
|
||||
description: '',
|
||||
epochId: '',
|
||||
countryId: '',
|
||||
});
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Ошибка при добавлении/редактировании исполнителя');
|
||||
}
|
||||
};
|
||||
|
||||
console.log('Rendering form with formData:', formData);
|
||||
|
||||
return (
|
||||
<div className="card bg-dark border-punk">
|
||||
<div className="card-body">
|
||||
<h3 className="text-punk mb-4">
|
||||
<i className={`bi ${artist ? 'bi-pencil-square' : 'bi-person-plus'}`}></i>
|
||||
{artist ? 'Редактировать исполнителя' : 'Добавить исполнителя'}
|
||||
</h3>
|
||||
|
||||
{error && <div className="alert alert-danger">{error}</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="mb-3">
|
||||
<label className="form-label text-light">Название группы</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-control bg-dark text-light border-punk"
|
||||
name="name"
|
||||
value={formData.name}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="form-label text-light">Описание</label>
|
||||
<textarea
|
||||
className="form-control bg-dark text-light border-punk"
|
||||
name="description"
|
||||
value={formData.description}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="form-label text-light">Эпоха</label>
|
||||
<select
|
||||
className="form-select bg-dark text-light border-punk"
|
||||
name="epochId"
|
||||
value={formData.epochId}
|
||||
onChange={handleChange}
|
||||
required
|
||||
>
|
||||
<option value={0}>Выберите эпоху</option>
|
||||
{epochs.map(epoch => (
|
||||
<option key={epoch.id} value={epoch.id}>{epoch.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="form-label text-light">Страна</label>
|
||||
<select
|
||||
className="form-select bg-dark text-light border-punk"
|
||||
name="countryId"
|
||||
value={formData.countryId}
|
||||
onChange={handleChange}
|
||||
required
|
||||
>
|
||||
<option value={0}>Выберите страну</option>
|
||||
{countries.map(country => (
|
||||
<option key={country.id} value={country.id}>{country.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-punk mt-3"
|
||||
style={{ zIndex: 1000 }}
|
||||
>
|
||||
<i className={`bi ${artist ? 'bi-save' : 'bi-plus-circle'}`}></i>
|
||||
{artist ? 'Сохранить изменения' : 'Добавить исполнителя'}
|
||||
</button>
|
||||
{artist && <button type="button" className="btn btn-secondary mt-3 ms-2" onClick={onCancel}>Отмена</button>}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ArtistForm;
|
||||
30
punk-rock-app/src/components/ArtistList.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import React from 'react';
|
||||
import ArtistCard from './ArtistCard';
|
||||
import { Artist, Epoch, Country } from '../types';
|
||||
|
||||
interface ArtistListProps {
|
||||
artists: Artist[];
|
||||
epochs: Epoch[];
|
||||
countries: Country[];
|
||||
onEdit: (artist: Artist) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
const ArtistList: React.FC<ArtistListProps> = ({ artists, epochs, countries, onEdit, onDelete }) => {
|
||||
return (
|
||||
<div className="row row-cols-1 row-cols-md-3 g-4 mt-4">
|
||||
{artists.map(artist => (
|
||||
<ArtistCard
|
||||
key={artist.id}
|
||||
artist={artist}
|
||||
epochs={epochs}
|
||||
countries={countries}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ArtistList;
|
||||
@@ -1,7 +1,6 @@
|
||||
// Footer.jsx
|
||||
import React from 'react';
|
||||
|
||||
const Footer = () => {
|
||||
const Footer: React.FC = () => {
|
||||
return (
|
||||
<footer className="bg-black py-3 border-top border-punk mt-auto">
|
||||
<div className="container">
|
||||
@@ -1,25 +1,22 @@
|
||||
// Header.jsx
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
const Header = () => {
|
||||
const Header: React.FC = () => {
|
||||
return (
|
||||
<header className="sticky-top navbar navbar-expand-lg navbar-dark bg-black border-bottom border-punk px-0">
|
||||
<div className="container-fluid">
|
||||
<a href="/" className="navbar-brand d-flex align-items-center ms-3">
|
||||
|
||||
<Link to="/" className="navbar-brand d-flex align-items-center ms-3">
|
||||
<span className="text-punk fs-4 fw-bold">Панкуха</span>
|
||||
</a>
|
||||
|
||||
</Link>
|
||||
<button className="navbar-toggler me-3" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
|
||||
<span className="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
|
||||
<div className="collapse navbar-collapse bg-black" id="navbarContent">
|
||||
<ul className="navbar-nav w-100 justify-content-end pe-4">
|
||||
<li className="nav-item">
|
||||
<a className="nav-link text-punk fw-bold" href="https://vk.com/kadyshevever">
|
||||
<Link className="nav-link text-punk fw-bold" to="/contacts">
|
||||
<i className="bi bi-people-fill me-1"></i>Контакты
|
||||
</a>
|
||||
</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
40
punk-rock-app/src/components/SubscriptionForm.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import React, { useState, ChangeEvent } from 'react';
|
||||
import { Subscription } from '../types';
|
||||
|
||||
interface SubscriptionFormProps {
|
||||
onSubmit: (subscription: Omit<Subscription, 'id' | 'active' | 'userId'>) => Promise<void>;
|
||||
}
|
||||
|
||||
const SubscriptionForm: React.FC<SubscriptionFormProps> = ({ onSubmit }) => {
|
||||
const [subscriptionType, setSubscriptionType] = useState<string>('Basic');
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
await onSubmit({ type: subscriptionType, price: subscriptionType === 'Basic' ? 5 : 15 });
|
||||
};
|
||||
|
||||
const handleChange = (e: ChangeEvent<HTMLSelectElement>) => {
|
||||
setSubscriptionType(e.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card bg-dark border-punk m-2">
|
||||
<div className="card-body">
|
||||
<h5 className="text-punk">Оформить подписку</h5>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<select
|
||||
className="form-select bg-dark text-light border-punk mb-3"
|
||||
value={subscriptionType}
|
||||
onChange={handleChange}
|
||||
>
|
||||
<option value="Basic">Базовая ($5)</option>
|
||||
<option value="Premium">Премиум ($15)</option>
|
||||
</select>
|
||||
<button type="submit" className="btn btn-punk">Подписаться</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SubscriptionForm;
|
||||
138
punk-rock-app/src/hooks/useArtists.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { getArtists, createArtist, updateArtist, deleteArtist, getEpochs, getCountries } from '../services/api';
|
||||
import { Artist, Epoch, Country } from '../types';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
const useArtists = () => {
|
||||
const [artists, setArtists] = useState<Artist[]>([]);
|
||||
const [epochs, setEpochs] = useState<Epoch[]>([]);
|
||||
const [countries, setCountries] = useState<Country[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [artistsData, epochsData, countriesData] = await Promise.all([
|
||||
getArtists(),
|
||||
getEpochs(),
|
||||
getCountries(),
|
||||
]);
|
||||
console.log('Artists data:', artistsData.data);
|
||||
console.log('Epochs data:', epochsData.data);
|
||||
console.log('Countries data:', countriesData.data);
|
||||
|
||||
const enrichedArtists = artistsData.data.map((artist: Artist) => ({
|
||||
...artist,
|
||||
epoch: epochsData.data.find((e: Epoch) => e.id.toString() === artist.epochId.toString()),
|
||||
country: countriesData.data.find((c: Country) => c.id.toString() === artist.countryId.toString()),
|
||||
}));
|
||||
|
||||
const sortedArtists = [...enrichedArtists].sort((a, b) =>
|
||||
sortOrder === 'asc'
|
||||
? a.name.localeCompare(b.name)
|
||||
: b.name.localeCompare(a.name)
|
||||
);
|
||||
|
||||
setArtists(sortedArtists);
|
||||
setEpochs(epochsData.data);
|
||||
setCountries(countriesData.data);
|
||||
setLoading(false);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [sortOrder]);
|
||||
|
||||
|
||||
|
||||
const addArtist = async (artist: Omit<Artist, 'id'>) => {
|
||||
const nameExists = artists.some(a => a.name.toLowerCase() === artist.name.toLowerCase());
|
||||
if (nameExists) {
|
||||
throw new Error('Исполнитель с таким именем уже существует!');
|
||||
}
|
||||
|
||||
// Генерируем уникальный id на клиентской стороне
|
||||
const uniqueId = uuidv4();
|
||||
|
||||
// Создаем новый объект артиста с id
|
||||
const artistWithId: Artist = {
|
||||
...artist,
|
||||
id: uniqueId,
|
||||
epochId: artist.epochId.toString(),
|
||||
countryId: artist.countryId.toString(),
|
||||
};
|
||||
|
||||
// Отправляем объект на сервер
|
||||
const response = await createArtist(artistWithId);
|
||||
|
||||
const newArtist = {
|
||||
...response.data,
|
||||
epoch: epochs.find(e => e.id.toString() === response.data.epochId.toString()),
|
||||
country: countries.find(c => c.id.toString() === response.data.countryId.toString()),
|
||||
};
|
||||
|
||||
const updatedArtists = [...artists, newArtist].sort((a, b) =>
|
||||
sortOrder === 'asc'
|
||||
? a.name.localeCompare(b.name)
|
||||
: b.name.localeCompare(a.name)
|
||||
);
|
||||
|
||||
setArtists(updatedArtists);
|
||||
};
|
||||
|
||||
const editArtist = async (id: string, artistData: Partial<Artist>) => {
|
||||
if (artistData.name !== undefined) {
|
||||
const nameExists = artists.some(a => a.id !== id && a.name.toLowerCase() === artistData.name!.toLowerCase());
|
||||
if (nameExists) {
|
||||
throw new Error('Исполнитель с таким именем уже существует!');
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await updateArtist(id, artistData);
|
||||
const updatedArtist = {
|
||||
...response.data,
|
||||
epoch: epochs.find(e => e.id.toString() === response.data.epochId.toString()),
|
||||
country: countries.find(c => c.id.toString() === response.data.countryId.toString()),
|
||||
};
|
||||
const updatedArtists = artists.map(a => a.id === id ? updatedArtist : a);
|
||||
setArtists(updatedArtists.sort(((a, b) =>
|
||||
sortOrder === 'asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
|
||||
)));
|
||||
} catch (err: any) {
|
||||
setError(`Ошибка при изменении: ${err.message}. Сервер ответил ${err.response?.status}`);
|
||||
console.error('Edit error:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const removeArtist = async (id: string) => {
|
||||
console.log(`Attempting to delete artist with id: ${id}`);
|
||||
console.log('Current artists:', artists);
|
||||
const artistExists = artists.find(a => a.id.toString() === id.toString());
|
||||
if (!artistExists) {
|
||||
setError(`Ошибка: Исполнитель с id ${id} не найден в текущем списке!`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await deleteArtist(id);
|
||||
// Повторно загружаем данные с сервера после удаления
|
||||
await fetchData();
|
||||
} catch (err: any) {
|
||||
setError(`Ошибка при удалении: ${err.message}. Сервер ответил ${err.response?.status}`);
|
||||
console.error('Delete error:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleSortOrder = () => {
|
||||
setSortOrder(prev => (prev === 'asc' ? 'desc' : 'asc'));
|
||||
};
|
||||
|
||||
return { artists, epochs, countries, loading, error, addArtist, editArtist, removeArtist, toggleSortOrder, sortOrder };
|
||||
};
|
||||
|
||||
export default useArtists;
|
||||
46
punk-rock-app/src/hooks/useSubscriptions.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { getSubscriptions, createSubscription, deleteSubscription, getUsers } from '../services/api';
|
||||
import { Subscription, User } from '../types';
|
||||
|
||||
const useSubscriptions = (userId: number) => {
|
||||
const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const [subscriptionsData, usersData] = await Promise.all([
|
||||
getSubscriptions(),
|
||||
getUsers(),
|
||||
]);
|
||||
setSubscriptions(subscriptionsData.data);
|
||||
setUsers(usersData.data);
|
||||
setLoading(false);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const addSubscription = async (subscription: Omit<Subscription, 'id' | 'active' | 'userId'>) => {
|
||||
const response = await createSubscription({ ...subscription, userId, active: true });
|
||||
setSubscriptions([...subscriptions, response.data]);
|
||||
};
|
||||
|
||||
const cancelSubscription = async (id: number) => {
|
||||
await deleteSubscription(id);
|
||||
setSubscriptions(subscriptions.filter(s => s.id !== id));
|
||||
};
|
||||
|
||||
const getUserSubscription = (): Subscription | undefined => {
|
||||
return subscriptions.find(s => s.userId === userId);
|
||||
};
|
||||
|
||||
return { subscriptions, users, loading, error, addSubscription, cancelSubscription, getUserSubscription };
|
||||
};
|
||||
|
||||
export default useSubscriptions;
|
||||
15
punk-rock-app/src/index.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
import 'bootstrap-icons/font/bootstrap-icons.css';
|
||||
import App from './App';
|
||||
|
||||
const container = document.getElementById('root');
|
||||
if (container) {
|
||||
const root = createRoot(container);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
}
|
||||
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
77
punk-rock-app/src/pages/ArtistPage.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React from 'react';
|
||||
|
||||
const ArtistPage: React.FC = () => {
|
||||
return (
|
||||
<div className="container my-5 flex-grow-1">
|
||||
<div className="row">
|
||||
<div className="col-lg-8 mx-auto">
|
||||
<h1 className="display-4 text-punk mb-4">
|
||||
<i className="bi bi-person-badge"></i> Гражданская Оборона
|
||||
</h1>
|
||||
|
||||
{/* Изображение (путь /res/grob.jpg из public) */}
|
||||
<div className="text-center mb-5">
|
||||
<img
|
||||
src="/res/grob.jpg"
|
||||
alt="Гражданская Оборона"
|
||||
className="img-fluid rounded border border-punk"
|
||||
style={{ maxWidth: '100%', height: 'auto' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="lead text-punk">
|
||||
Здесь можно почитать инфу про исполнителя и перейти на песню
|
||||
</p>
|
||||
|
||||
<div className="card bg-dark border-punk mb-4">
|
||||
<div className="card-body">
|
||||
<div className="descriptionForSong">
|
||||
<p className="text-light">
|
||||
«Гражданская Оборона» — культовая советская и российская рок-группа, основанная в 1984 году в Омске Егором Летовым.
|
||||
Коллектив стал одним из самых влиятельных в андеграундной среде.
|
||||
</p>
|
||||
<p className="text-light">
|
||||
Музыка «Гражданской Обороны» сочетает в себе элементы панк-рока, гаражного рока и лоу-фая.
|
||||
Несмотря на минималистичный подход к звучанию, группа смогла создать уникальный стиль.
|
||||
</p>
|
||||
<p className="text-light">
|
||||
Среди самых известных альбомов группы — «Тоталитаризм», «Мышеловка», «Здорово и вечно»,
|
||||
«Русское поле экспериментов» и «Инструкция по выживанию». Творчество «Гражданской Обороны»
|
||||
остается актуальным и по сей день, а Егор Летов считается одной из ключевых фигур в истории
|
||||
русской рок-музыки.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card bg-dark border-punk">
|
||||
<div className="card-body">
|
||||
<h3 className="text-punk mb-3">
|
||||
<i className="bi bi-music-note-list"></i> Популярные песни:
|
||||
</h3>
|
||||
<ul className="list-group list-group-flush">
|
||||
<li className="list-group-item bg-dark text-punk border-punk">
|
||||
<a href="#" className="text-punk text-decoration-none">
|
||||
<i className="bi bi-file-music me-2"></i> Кайф или больше
|
||||
</a>
|
||||
</li>
|
||||
<li className="list-group-item bg-dark text-punk border-punk">
|
||||
<a href="#" className="text-punk text-decoration-none">
|
||||
<i className="bi bi-file-music me-2"></i> Зоопарк
|
||||
</a>
|
||||
</li>
|
||||
<li className="list-group-item bg-dark text-punk border-punk">
|
||||
<a href="#" className="text-punk text-decoration-none">
|
||||
<i className="bi bi-file-music me-2"></i> Новая патриотическая
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ArtistPage;
|
||||
168
punk-rock-app/src/pages/ArtistsPage.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
import React, { useState } from 'react';
|
||||
import useArtists from '../hooks/useArtists';
|
||||
import ArtistList from '../components/ArtistList';
|
||||
import { Artist, Epoch, Country } from '../types';
|
||||
|
||||
const ArtistsPage: React.FC = () => {
|
||||
const { artists, loading, error, removeArtist, editArtist, epochs, countries, sortOrder } = useArtists();
|
||||
const [editingArtist, setEditingArtist] = useState<Artist | null>(null);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [sortConfig, setSortConfig] = useState<{ field: 'name' | 'epoch' | 'country'; direction: 'asc' | 'desc' }>({
|
||||
field: 'name',
|
||||
direction: 'asc'
|
||||
});
|
||||
|
||||
// Константы для пагинации
|
||||
const artistsPerPage = 6;
|
||||
const indexOfLastArtist = currentPage * artistsPerPage;
|
||||
const indexOfFirstArtist = indexOfLastArtist - artistsPerPage;
|
||||
|
||||
|
||||
const sortedArtists = [...artists].sort((a, b) => {
|
||||
const getFieldValue = (artist: Artist) => {
|
||||
if (sortConfig.field === 'name') return artist.name;
|
||||
if (sortConfig.field === 'epoch') return artist.epoch?.name || '';
|
||||
return artist.country?.name || '';
|
||||
};
|
||||
|
||||
const valueA = getFieldValue(a);
|
||||
const valueB = getFieldValue(b);
|
||||
|
||||
if (valueA < valueB) return sortConfig.direction === 'asc' ? -1 : 1;
|
||||
if (valueA > valueB) return sortConfig.direction === 'asc' ? 1 : -1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
// Текущие артисты для отображения
|
||||
const currentArtists = sortedArtists.slice(indexOfFirstArtist, indexOfLastArtist);
|
||||
|
||||
if (loading) return <p className="text-center text-punk my-5">Загрузка...</p>;
|
||||
if (error) return <p className="text-center text-danger my-5">Ошибка: {error}</p>;
|
||||
|
||||
const handleEdit = (artist: Artist) => {
|
||||
setEditingArtist(artist);
|
||||
};
|
||||
|
||||
const handleDelete = (id: string) => {
|
||||
removeArtist(id);
|
||||
// Сброс страницы при удалении
|
||||
if (currentArtists.length === 1 && currentPage > 1) {
|
||||
setCurrentPage(currentPage - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (editingArtist) {
|
||||
await editArtist(editingArtist.id, editingArtist);
|
||||
setEditingArtist(null);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleSort = (field: 'name' | 'epoch' | 'country') => {
|
||||
setSortConfig(prev => ({
|
||||
field,
|
||||
direction: prev.field === field && prev.direction === 'asc' ? 'desc' : 'asc'
|
||||
}));
|
||||
};
|
||||
|
||||
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
|
||||
|
||||
return (
|
||||
<div className="container py-4">
|
||||
<h1 className="text-punk mb-3">Список исполнителей</h1>
|
||||
|
||||
{/* Кнопки сортировки */}
|
||||
<div className="d-flex gap-2 mb-3">
|
||||
<button
|
||||
className={`btn btn-outline-punk text-light ${sortConfig.field === 'name' ? 'active' : ''}`}
|
||||
onClick={() => toggleSort('name')}
|
||||
>
|
||||
По имени {sortConfig.field === 'name' && (sortConfig.direction === 'asc' ? '↑' : '↓')}
|
||||
</button>
|
||||
<button
|
||||
className={`btn btn-outline-punk text-light ${sortConfig.field === 'epoch' ? 'active' : ''}`}
|
||||
onClick={() => toggleSort('epoch')}
|
||||
>
|
||||
По эпохе {sortConfig.field === 'epoch' && (sortConfig.direction === 'asc' ? '↑' : '↓')}
|
||||
</button>
|
||||
<button
|
||||
className={`btn btn-outline-punk text-light ${sortConfig.field === 'country' ? 'active' : ''}`}
|
||||
onClick={() => toggleSort('country')}
|
||||
>
|
||||
По стране {sortConfig.field === 'country' && (sortConfig.direction === 'asc' ? '↑' : '↓')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ArtistList artists={currentArtists} onEdit={handleEdit} onDelete={handleDelete} epochs={epochs} countries={countries} />
|
||||
|
||||
{/* Пагинация */}
|
||||
<nav className="mt-4">
|
||||
<ul className="pagination justify-content-center">
|
||||
{Array.from({ length: Math.ceil(artists.length / artistsPerPage) }).map((_, index) => (
|
||||
<li key={index} className={`page-item ${currentPage === index + 1 ? 'active' : ''}`}>
|
||||
<button
|
||||
className="page-link bg-dark text-punk border-punk"
|
||||
onClick={() => paginate(index + 1)}
|
||||
>
|
||||
{index + 1}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
{/* Модальное окно редактирования */}
|
||||
{editingArtist && (
|
||||
<div className="modal show" style={{ display: 'block', backgroundColor: 'rgba(0,0,0,0.7)' }}>
|
||||
<div className="modal-dialog modal-dialog-centered">
|
||||
<div className="modal-content bg-dark border-punk">
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title text-punk">Редактировать исполнителя</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close btn-close-white"
|
||||
onClick={() => setEditingArtist(null)}
|
||||
></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<div className="mb-3">
|
||||
<label className="form-label text-light">Имя</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-control bg-dark text-light border-punk"
|
||||
value={editingArtist.name}
|
||||
onChange={(e) => setEditingArtist({...editingArtist, name: e.target.value})}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label text-light">Описание</label>
|
||||
<textarea
|
||||
className="form-control bg-dark text-light border-punk"
|
||||
value={editingArtist.description}
|
||||
onChange={(e) => setEditingArtist({...editingArtist, description: e.target.value})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setEditingArtist(null)}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-punk"
|
||||
onClick={handleSave}
|
||||
>
|
||||
Сохранить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ArtistsPage;
|
||||
107
punk-rock-app/src/pages/Catalog.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import React, { useState } from 'react';
|
||||
import useArtists from '../hooks/useArtists';
|
||||
import useSubscriptions from '../hooks/useSubscriptions';
|
||||
import SubscriptionForm from '../components/SubscriptionForm';
|
||||
import { Subscription, Artist } from '../types';
|
||||
|
||||
const Catalog: React.FC = () => {
|
||||
const { artists, loading: artistsLoading, error: artistsError } = useArtists();
|
||||
const {
|
||||
getUserSubscription,
|
||||
addSubscription,
|
||||
cancelSubscription,
|
||||
loading: subsLoading,
|
||||
error: subsError
|
||||
} = useSubscriptions(1); // Пример userId = 1
|
||||
const subscription: Subscription | undefined = getUserSubscription();
|
||||
const [subscriptionStartDate, setSubscriptionStartDate] = useState<Date | null>(null);
|
||||
|
||||
if (artistsLoading || subsLoading) return <p className="text-center text-punk my-5">Загрузка...</p>;
|
||||
if (artistsError || subsError) return <p className="text-center text-danger my-5">Ошибка: {artistsError || subsError}</p>;
|
||||
|
||||
const handleAddSubscription = async (subscriptionData: Omit<Subscription, 'id' | 'active' | 'userId'>) => {
|
||||
const response = await addSubscription(subscriptionData);
|
||||
setSubscriptionStartDate(new Date()); // Установите текущую дату как дату начала подписки
|
||||
};
|
||||
|
||||
const handleCancelSubscription = async () => {
|
||||
if (subscription) {
|
||||
await cancelSubscription(subscription.id);
|
||||
setSubscriptionStartDate(null); // Сбросить дату начала подписки
|
||||
}
|
||||
};
|
||||
|
||||
const calculateEndDate = (startDate: Date): Date => {
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setMonth(endDate.getMonth() + 1);
|
||||
return endDate;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container py-4">
|
||||
<h1 className="text-punk mb-3">Каталог</h1>
|
||||
|
||||
|
||||
{subscription ? (
|
||||
<div className="alert bg-dark border-punk">
|
||||
<h5>
|
||||
{subscription.type === 'Premium' ? '💎 Премиум' : '🔹 Базовая'} подписка (${subscription.price})
|
||||
</h5>
|
||||
{subscriptionStartDate && (
|
||||
<p className="text-light">
|
||||
Подписка действует до: {calculateEndDate(subscriptionStartDate).toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
className="btn btn-outline-danger btn-sm mt-2"
|
||||
onClick={handleCancelSubscription}
|
||||
>
|
||||
Отменить подписку
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="alert bg-dark border-punk">
|
||||
<h5>У вас нет подписки</h5>
|
||||
<p>Оформите подписку для доступа к каталогу!</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Форма подписки (если нет активной) */}
|
||||
{!subscription && <SubscriptionForm onSubmit={handleAddSubscription} />}
|
||||
|
||||
{/* Контент в зависимости от подписки */}
|
||||
{subscription?.type === 'Premium' ? (
|
||||
<div>
|
||||
<h2 className="text-punk mt-4">Полный каталог артистов</h2>
|
||||
{artists.map((artist) => (
|
||||
<div key={artist.id} className="card bg-dark border-punk my-2">
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-punk">{artist.name}</h5>
|
||||
<p className="card-text text-light">{artist.description}</p>
|
||||
<small className="text-light">Эпоха: {artist.epoch?.name || 'Не указана'}</small>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : subscription?.type === 'Basic' ? (
|
||||
<div>
|
||||
<h2 className="text-punk mt-4">Базовый каталог</h2>
|
||||
<p className="text-light mb-3">Доступны только названия групп. Для полного доступа оформите Premium.</p>
|
||||
{artists.map((artist) => (
|
||||
<div key={artist.id} className="card bg-dark border-punk my-2">
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-punk">{artist.name}</h5>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="alert bg-dark border-punk mt-4">
|
||||
<p>🔒 Чтобы увидеть каталог, оформите подписку.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Catalog;
|
||||
12
punk-rock-app/src/pages/Contacts.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
|
||||
const Contacts: React.FC = () => {
|
||||
return (
|
||||
<div className="container py-4">
|
||||
<h1 className="text-punk mb-3">Контакты</h1>
|
||||
<p className="text-light">Свяжитесь с нами: <a href="https://vk.com/kadyshevever" target="_blank" rel="noopener noreferrer">vk.com/kadyshevever</a></p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Contacts;
|
||||
52
punk-rock-app/src/pages/Home.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import React from 'react';
|
||||
import useArtists from '../hooks/useArtists';
|
||||
import ArtistList from '../components/ArtistList';
|
||||
import ArtistForm from '../components/ArtistForm';
|
||||
import { Artist, Epoch, Country } from '../types';
|
||||
|
||||
const Home: React.FC = () => {
|
||||
const { artists, epochs, countries, loading, error, addArtist, editArtist, removeArtist, toggleSortOrder, sortOrder } = useArtists();
|
||||
const [editingArtist, setEditingArtist] = React.useState<Artist | null>(null);
|
||||
|
||||
if (loading) return <p className="text-center text-punk my-5">Загрузка...</p>;
|
||||
if (error) return <p className="text-center text-danger my-5">Ошибка: {error}</p>;
|
||||
|
||||
const handleSubmit = async (artist: Artist) => {
|
||||
if (editingArtist && editingArtist.id) {
|
||||
await editArtist(editingArtist.id, artist);
|
||||
} else {
|
||||
await addArtist(artist);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container py-4">
|
||||
<div className="d-flex justify-content-between align-items-center mb-3">
|
||||
<h1 className="text-punk mb-0">Главная</h1>
|
||||
<button
|
||||
className="btn btn-punk"
|
||||
onClick={toggleSortOrder}
|
||||
>
|
||||
<i className={`bi bi-sort-alpha-${sortOrder === 'asc' ? 'down' : 'up'}`}></i>
|
||||
{sortOrder === 'asc' ? 'Я → А' : 'А → Я'}
|
||||
</button>
|
||||
</div>
|
||||
<ArtistForm
|
||||
countries={countries}
|
||||
epochs={epochs}
|
||||
onSubmit={handleSubmit}
|
||||
artist={editingArtist}
|
||||
onCancel={() => setEditingArtist(null)}
|
||||
/>
|
||||
<ArtistList
|
||||
artists={artists}
|
||||
epochs={epochs}
|
||||
countries={countries}
|
||||
onEdit={setEditingArtist}
|
||||
onDelete={removeArtist}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Home;
|
||||
12
punk-rock-app/src/pages/SongPage.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
|
||||
const SongPage: React.FC = () => {
|
||||
return (
|
||||
<div className="container py-4">
|
||||
<h1 className="text-punk mb-3">Песня</h1>
|
||||
<p className="text-light">Здесь будет список песен (пока заглушка).</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SongPage;
|
||||
1
punk-rock-app/src/react-app-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="react-scripts" />
|
||||
@@ -1,4 +1,6 @@
|
||||
const reportWebVitals = onPerfEntry => {
|
||||
import { ReportHandler } from 'web-vitals';
|
||||
|
||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||
getCLS(onPerfEntry);
|
||||
21
punk-rock-app/src/services/api.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import axios from 'axios';
|
||||
import { Artist, Epoch, Country, Subscription, User } from '../types';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: 'http://localhost:3001',
|
||||
});
|
||||
|
||||
export const getArtists = () => api.get<Artist[]>('/artists');
|
||||
export const createArtist = (artist: Omit<Artist, 'id'>) => api.post<Artist>('/artists', artist);
|
||||
export const updateArtist = (id: string, artist: Partial<Artist>) => api.put<Artist>(`/artists/${id}`, artist);
|
||||
export const deleteArtist = (id: string) => api.delete(`/artists/${id}`);
|
||||
|
||||
export const getEpochs = () => api.get<Epoch[]>('/epochs');
|
||||
export const getCountries = () => api.get<Country[]>('/countries');
|
||||
|
||||
export const getSubscriptions = () => api.get<Subscription[]>('/subscriptions');
|
||||
export const createSubscription = (subscription: Omit<Subscription, 'id'>) => api.post<Subscription>('/subscriptions', subscription);
|
||||
export const updateSubscription = (id: number, subscription: Partial<Subscription>) => api.put<Subscription>(`/subscriptions/${id}`, subscription);
|
||||
export const deleteSubscription = (id: number) => api.delete(`/subscriptions/${id}`);
|
||||
|
||||
export const getUsers = () => api.get<User[]>('/users');
|
||||