review

 avatar
mbojdys
java
14 days ago
2.7 kB
15
Indexable
package com.videopoint.service;

import com.videopoint.repository.RegistryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("api/registry")
public class RegistryController {

    @Autowired
    private RegistryRepository registryRepository;

    @Autowired
    private NotificationService notificationService;

    @GetMapping
    private ResponseEntity<List<Registry>> getRegistry() {
        List<Registry> registries = registryRepository.findAll();
        return ResponseEntity.ok(registries);
    }

    @GetMapping("/{userId}")
    private ResponseEntity<List<Registry>> getByUserId(@PathVariable BigInteger userId) {
        List<Registry> registries = registryRepository.findByUserId(userId);
        return ResponseEntity.ok(registries);
    }

    @GetMapping("/{registryId}/{userId}")
    private ResponseEntity<Registry> getByRegistryIdAndUserId(@PathVariable BigInteger userId,
                                                              @PathVariable BigInteger registryId) {
        Optional<Registry> optionalRegistry = registryRepository.findByIdAndUserId(registryId, userId);
        if (optionalRegistry.isPresent())
            return ResponseEntity.ok(optionalRegistry.get());
        else
            return ResponseEntity.notFound().build();
    }

    @PostMapping("/{userId}")
    private ResponseEntity<Registry> createRegistryForUserId(@PathVariable BigInteger userId) {
        Registry registry = new Registry("registry", userId, 200);
        notificationService.publish("Registry created", registry);
        return ResponseEntity.ok(registryRepository.save(registry));
    }

    @PostMapping("/{registryId}/{userId}")
    private ResponseEntity<Registry> updateRegistryForUserId(@PathVariable BigInteger userId,
                                                             @PathVariable BigInteger registryId,
                                                             @RequestBody Registry registry) {
        Optional<Registry> optionalRegistry = registryRepository.findByIdAndUserId(registryId, userId);
        if (optionalRegistry.isPresent()) {
            var existingRegistry = optionalRegistry.get();
            existingRegistry.setAmount(registry.getAmount());
            existingRegistry.setLabel(registry.getLabel());
            registryRepository.save(existingRegistry);
            return ResponseEntity.ok(optionalRegistry.get());
        } else
            return ResponseEntity.notFound().build();
    }
}
Editor is loading...
Leave a Comment