Validate registry data (spring-boot + angularjs)

0

Hello,

I'm implementing a web project in spring boot + data + angularjs. Where the client makes rest requests to the server. On the Spring side I'm using repositories to develop the database search with CrudRepository.

@RepositoryRestResource
public interface ClientRepository  extends CrudRepository< Client , Integer > { 

    List< Client > findAll( );

}

I just need to edit the save function of the repository. I tried to create a service layer that runs the save but it is not working.

@Component( "clientService" )
@Transactional
public class ClientRepositoryImpl implements ClientService{

    private final ClientRepository clientRepository;

    public ClientRepositoryImpl( ClientRepository clientRepository ) {
        this.clientRepository = clientRepository;
    }


    @Override
    public String addClient( Client saved ) {
            // ....
            if( this.clientRepository.save( saved ) != null )
                return "OK";
            else 
                return "NOK";

    }  

}

Can anyone give an idea how I can create some logic before invoking the repository save? I am making the accurate record of validating the data entered on the server side and I am not sure how to validate before the repository does save. Since on the client side I make a call rest (/ clients) with the parameters to insert.

    
asked by anonymous 15.08.2016 / 13:39

1 answer

1

I do not usually use spring-data-rest, because his approach is a bit different from the one I'm used to. I prefer to use spring-hateoas and develop the rest controllers on my own, this makes it possible to use several other features that the spring ecosystem has.

But since you are using this approach and I would like to help you, I suggest you create a Validator bean for your entity and register it to the BeforeCreate event.

Example:

@Component
class BeforeCreatePersonValidator implements Validator {

    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

Only this class named BeforeCreatePersonValidator and annotated with @Component should already be enough to validate an entity named Person, before it is persisted to the database, according to documentation .

If you want to have some more idea about client data validation, you can look at spring-framework documentation .

I hope I have helped.

    
28.09.2016 / 00:47