Validate log data (spring-boot + Angularjs)

Asked

Viewed 395 times

0

Hello,

I am 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 database research with Crudrepository.

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

    List< Client > findAll( );

}

Only I need to edit the save function of the repository. I tried to create a service layer that runs save but 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 to create some logic before invoking save from the repository ? I’m doing the log I need to validate the data entered on the server side and I’m not sure how to validate before the repository saves. Since on the client side I make a Rest call ( /clients ) with the parameters to insert.

1 answer

1

I don’t usually use spring-data-Rest, because its approach is a little 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 as Beforecreatepersonvalidator and annotated with @Component should already be enough to validate an entity called Pessoa, before it is persisted to the database, according to the documentation.

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

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.