appointments-software / src / main / java / odera / projects / appointmentssoftware / controllers / AppointmentsController.java
AppointmentsController.java
Raw
package odera.projects.appointmentssoftware.controllers;

import odera.projects.appointmentssoftware.models.Appointment;
import odera.projects.appointmentssoftware.repositories.AppointmentRepository;
import odera.projects.appointmentssoftware.repositories.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping("/api/v1/appointments")
public class AppointmentsController {
    @Autowired
    private AppointmentRepository appointmentRepository;
    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List<Appointment> list() {
        return appointmentRepository.findAll();
    }

    @GetMapping
    @RequestMapping(value = "{appointmentId}")
    public Appointment getAppointment(@PathVariable long appointmentId) {
        return appointmentRepository.findById(appointmentId).get();
    }

    @GetMapping
    @RequestMapping(value = "/all/{userId}")
    public List<Appointment> getAppointmentsForUser(@PathVariable long userId) {
        return userRepository.findById(userId).get().getAppointments();
    }

    @PostMapping
    public Appointment createAppointment(@RequestBody Appointment appointment) {
        Appointment newAppointment = new Appointment(appointment.getDate(), appointment.getTime(), appointment.getFirstName(), appointment.getLastName(), appointment.getPhone(), appointment.getEmail(), appointment.getUserId());
        newAppointment.setConfirmed(true);
        return appointmentRepository.saveAndFlush(newAppointment);
    }

    @PutMapping(value = "{appointmentId}")
    public void updateAppointment(@PathVariable long appointmentId, @RequestBody Appointment update) {
        Appointment appointment = appointmentRepository.findById(appointmentId).get();
        BeanUtils.copyProperties(update, appointment, "appointmentId");
        appointmentRepository.saveAndFlush(appointment);
    }

    @DeleteMapping(value = "{appointmentId}")
    public void deleteAppointment(@PathVariable long appointmentId) {
        appointmentRepository.deleteById(appointmentId);
    }
}