mercredi 2 novembre 2022

Design pattern for validate request

What design patterns could you apply? My API deals with invoices or documents, it must perform validations of currency types, amounts and more. This API will be consumed by Frontend and sends the data to another API that will make modifications at Database level.

And it seems to me very coupled to validate the request body and then invoke the other API method.

class MapperTest {
    public static AnotherRequest convert(Request request){
        AnyType an1 = AnyType.builder()
                .field1(request.getAnyType().get(0).getField1())
                ... // more fields
                .build();
                
        AnyType an2 = AnyType.builder()
                .field1(request.getAnyType().get(1).getField1())
                ... // more fields
                .build();
                
        // more objects
        
        List<AnyType> list = Arrays.asList(an1, an2);
        
        return AnotherRequest.builder()
            .field1(request.getField1())
            .field2(request.getField2())
            ... // more fields
            .listField(list).build();
    }
}

@Component
@AllArgsConstructor
public class DaoImpl{
    
    private AnotherApi anotherApi;
    
    public Maybe<Response> doSomething(AnotherRequest anotherRequest) {
        return anotherApi.doSomething(anotherRequest);
    }
}

@Component
@AllArgsConstructor
public class ServiceImpl {
    
    private DaoImpl daoImpl;

    public Maybe<Response> doSomething(Request request){
        return validateRequest(request)
            .map(request -> daoImpl.doSomething(ConfirmingMapper.convert(request)));
            // If invalid, perform another operation.
    }
    
    private Maybe<Request> validateRequest(Request request) {
        // validations..
        // ..
        // ..
        return Maybe.just(request);
    }
}

Aucun commentaire:

Enregistrer un commentaire