[인프런 워밍업 클럽] 4일차 과제

진도표 4일차와 연결됩니다

우리는 GET API와 POST API를 만드는 방법을 배웠습니다. 👍 추가적인 API 들을 만들어 보며 API 개발에 익숙해져 봅시다!

CREATE TABLE fruits (
    id INT AUTO_INCREMENT,
    name VARCHAR(255),
    warehousingDate DATE,
    price BIGINT,
    PRIMARY KEY (id)
);
import java.time.LocalDate;

public class FruitCreateRequest {
    private String name;
    private LocalDate warehousingDate;
    private long price;

    public String getName() {
        return name;
    }

    public LocalDate getWarehousingDate() {
        return warehousingDate;
    }

    public long getPrice() {
        return price;
    }
}
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Date;

@RestController
public class FruitController {

    private final JdbcTemplate jdbcTemplate;

    public FruitController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @PostMapping("/api/v1/fruit")
    public void saveFruit(@RequestBody FruitCreateRequest request) {
        String sql = "INSERT INTO fruit(name, warehousingDate, price) VALUES(?, ?, ?)";
        jdbcTemplate.update(sql, request.getName(), Date.valueOf(request.getWarehousingDate()), request.getPrice());
    }

}

 

image

long을 사용하는 이유는 큰 숫자 범위를 처리하기 위해서이다.

    @PutMapping("/api/v1/fruit")
    public ResponseEntity<String> markAsSoldOut(@RequestBody Map<String, Long> body) {
        Long id = body.get("id");
        if (id == null) {
            
            return ResponseEntity.badRequest().body("id 누락");
        }
        String sql = "UPDATE fruits SET status = 'soldout' WHERE id = ?";
        jdbcTemplate.update(sql, id);

        return ResponseEntity.ok("'soldout'");
    }

 

image

 

    @GetMapping("/api/v1/fruit/stat")
    public Map<String, Long> getSalesStat() {
        String salesAmountSql = "SELECT SUM(price) FROM fruits WHERE status = 'soldout'";
        String naoSalesAmountSql = "SELECT SUM(price) FROM fruits WHERE status IS NULL OR status != 'soldout'";

        Long salesAmount = jdbcTemplate.queryForObject(salesAmountSql, Long.class);
        Long naoSalesAmount = jdbcTemplate.queryForObject(naoSalesAmountSql, Long.class);

        Map<String, Long> result = new HashMap<>();
        result.put("salesAmount", salesAmount != null ? salesAmount : 0);
        result.put("naoSalesAmount", naoSalesAmount != null ? naoSalesAmount : 0);

        return result;
    }

image

댓글을 작성해보세요.

채널톡 아이콘