Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

정주찬 api코드 작성 #14

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
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/
Binary file added gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
7 changes: 7 additions & 0 deletions gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'GDSC_Backend'
11 changes: 11 additions & 0 deletions src/main/java/com/example/GDSC_Backend/GdscBackendApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.GDSC_Backend;

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

@SpringBootApplication
public class GdscBackendApplication {
public static void main(String[] args) {
SpringApplication.run(GdscBackendApplication.class, args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.example.GDSC_Backend.controller;

import com.example.GDSC_Backend.model.Task;
import com.example.GDSC_Backend.repository.TaskRepository;
import com.example.GDSC_Backend.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Controller
Copy link
Member

Choose a reason for hiding this comment

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

@responsebody 보다는
해당 애너테이션을 @RestController 로 수정하면 됩니다 !

@RequestMapping("/tasks")
public class TaskController {
private final TaskService taskService;

@Autowired
Copy link
Member

Choose a reason for hiding this comment

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

음?... 이건 조금 이상하네요... 인터넷에 생성자 주입으로 Spring관련해서 검색해보시면 좋을 것 같아요.

public TaskController(TaskService taskService) {
this.taskService = new TaskService();
}

@PostMapping
@ResponseBody
public Task createTask(@RequestParam String title, @RequestParam String description, @RequestParam LocalDate dueDate, @RequestParam boolean status) {
Copy link
Member

Choose a reason for hiding this comment

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

Post라면 body에 담아서 보내는게 어떨까요?

return taskService.createTask(title, description, dueDate, status);
}

@GetMapping("/{id}")
@ResponseBody
public Task getTask(@PathVariable Long id) {
Optional<Task> task = taskService.getTask(id);
return task.orElse(null);
}

@GetMapping
@ResponseBody
public List<Task> getAllTasks() {
return taskService.getAllTasks();
}

@PutMapping("/{id}")
@ResponseBody
public Task updateTask(@PathVariable Long id, @RequestParam String title, @RequestParam String description, @RequestParam LocalDate dueDate, @RequestParam boolean status) {
return taskService.updateTask(id, title, description, dueDate, status);
}

@DeleteMapping("/{id}")
@ResponseBody
public void deleteTask(@PathVariable Long id) {
taskService.deleteTask(id);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.example.GDSC_Backend.controller;

import com.example.GDSC_Backend.model.User;
import com.example.GDSC_Backend.repository.UserRepository;
import com.example.GDSC_Backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;

@Controller
@RequestMapping("/users")
public class UserController {
private final UserService userService;

@Autowired
public UserController(UserService userService) {
this.userService = new UserService();
}

@PostMapping
@ResponseBody
public User createUser(@RequestParam String name, @RequestParam String email, @RequestParam String password) {
Copy link
Contributor

Choose a reason for hiding this comment

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

requestParam 대신 post 요청에서는 requestBody를 사용하는 편이 더 적절할 것 같아요.
보통 코딩을 하다 파라미터가 3개 이상 나열되기 시작한다면(책 - 클린코드) 다른 방법이 없을지 고민해보면 좋을 것 같아요.
바디를 사용하면 바인딩을 통해 원하는 객체(예: UserCreateRequest)로 곧바로 변환해 활용할 수 있습니당

return userService.createUser(name, email, password);
}

@GetMapping("/{id}")
@ResponseBody
public User getUser(@PathVariable Long id) {
Optional<User> user = userService.getUser(id);
return user.orElse(null);
}

@PutMapping("/{id}")
Copy link
Contributor

Choose a reason for hiding this comment

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

patch put 모두 수정에 사용되는 메서드인데요, 둘은 어떤 차이가 있을까요? 그렇다면 현재는 어떤 메서드를 사용하는 것이 좀 더 적절할까요? 답변 남겨주시면 감사하겠습니다!

@ResponseBody
public User updateUser(@PathVariable Long id, @RequestParam String name, @RequestParam String email, @RequestParam String password) {
return userService.updateUser(id, name, email, password);
}

@DeleteMapping("/{id}")
@ResponseBody
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
62 changes: 62 additions & 0 deletions src/main/java/com/example/GDSC_Backend/model/Task.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.example.GDSC_Backend.model;

import java.time.LocalDate;

public class Task {
private Long id;
private String title;
private String description;
private LocalDate dueDate;
private boolean status;

// Constructors
public Task() {}
Copy link
Contributor

Choose a reason for hiding this comment

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

기본 생성자가 필요한 이유, 해당 코드에서 기본 생성자를 직접 명시해준 이유가 무엇일까요?


public Task(String title, String description, LocalDate dueDate, boolean status) {
this.title = title;
this.description = description;
this.dueDate = dueDate;
this.status = status;
}

// Getters and setters
Copy link
Contributor

Choose a reason for hiding this comment

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

자동 생성이라면 사용하지 않는 게터 세터는 삭제하는 편이 좋아요. 캡슐화와 정보 은닉에서 객체지향의 장점을 어떻게 살릴 수 있을지 고민해보면 좋을 듯 합니다

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public LocalDate getDueDate() {
return dueDate;
}

public void setDueDate(LocalDate dueDate) {
this.dueDate = dueDate;
}

public boolean isStatus() {
return status;
}

public void setStatus(boolean status) {
this.status = status;
}
}
50 changes: 50 additions & 0 deletions src/main/java/com/example/GDSC_Backend/model/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.example.GDSC_Backend.model;

public class User {
private Long id;
private String name;
private String email;
private String password;

// Constructors
public User() {}
Copy link
Member

Choose a reason for hiding this comment

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

해당 생성자는 왜 만드셨을까요?


public User(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}

// Getters and setters
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 getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.example.GDSC_Backend.repository;

import com.example.GDSC_Backend.model.Task;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

public class TaskRepository {
private List<Task> tasks = new ArrayList<>();
private AtomicLong nextId = new AtomicLong(1);

public Task save(Task task){
if (task.getId() == null){
task.setId(nextId.getAndIncrement());
}
tasks.add(task);
return task;
}

public Optional<Task> findById(Long id) {
return tasks.stream().filter(task -> task.getId().equals(id)).findFirst();
}

public List<Task> findAll() {
return new ArrayList<>(tasks);
}

public void deleteById(Long id) {
tasks.removeIf(task -> task.getId().equals(id));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.example.GDSC_Backend.repository;

import com.example.GDSC_Backend.model.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

public class UserRepository {
private List<User> users = new ArrayList<>();
private AtomicLong nextId = new AtomicLong(1);
Copy link
Contributor

Choose a reason for hiding this comment

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

데이터베이스 연동없이 레포지토리 계층 만들기위해 필드로 임시로 메모리 저장을 시도해주셨네요👍


public User save(User user){
if (user.getId() == null){
user.setId((nextId.getAndIncrement()));
}
users.add(user);
return user;
}

public Optional<User> findById(Long id){
return users.stream().filter(user -> user.getId().equals(id)).findFirst();
}

public List<User> findAll(){
return new ArrayList<>(users);
}

public void deleteById(long id){
users.removeIf(user -> user.getId().equals(id));
}
}
Loading