Add category module and require post category

This commit is contained in:
Tim
2025-06-30 23:07:15 +08:00
parent 4f24934a45
commit 5dd29239c9
10 changed files with 163 additions and 7 deletions

View File

@@ -2,8 +2,10 @@ package com.openisle.service;
import com.openisle.model.Post;
import com.openisle.model.User;
import com.openisle.model.Category;
import com.openisle.repository.PostRepository;
import com.openisle.repository.UserRepository;
import com.openisle.repository.CategoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -14,14 +16,18 @@ import java.util.List;
public class PostService {
private final PostRepository postRepository;
private final UserRepository userRepository;
private final CategoryRepository categoryRepository;
public Post createPost(String username, String title, String content) {
public Post createPost(String username, Long categoryId, String title, String content) {
User author = userRepository.findByUsername(username)
.orElseThrow(() -> new IllegalArgumentException("User not found"));
Category category = categoryRepository.findById(categoryId)
.orElseThrow(() -> new IllegalArgumentException("Category not found"));
Post post = new Post();
post.setTitle(title);
post.setContent(content);
post.setAuthor(author);
post.setCategory(category);
return postRepository.save(post);
}