2017-05-30 10 views
0

私は新しいEmployeeを作成するためのREST APIを設計しています。Spring Validations + Swagger Documentation:他のフィールドの条件や値に基づいて

従業員タイプに基づいて、フィールドには必須のフィールドがあり、それ以外のフィールドは必須ではありません。 例:すべてAPIコールを作成するには、employeeNameを渡す必要があります。春の検証を使用してこのような制限を強制する方法

  1. :しかしcontractVendorName場合のみ、employeeType=contractor

    質問必須すべきですか?

  2. スワッガーでこのようなフィールドを文書化する方法は?
  3. 条件の検証がサポートされていない場合、それはContractEmployeeオブジェクトで
    • createEmpoyee(ContractEmployeeのCE)
    • createEmpoyee(RegularEmployee再)
      ごとに異なるAPIを持ってしても意味がないマークに春+闊歩注釈を行いますcontractVendorNameとして必須です。

は、ここで私はたとえば、contractVendorNameとしてただ一つのフィールドをとっています。私は従業員タイプに基づいてオプションまたは必須である5-6フィールドを持つことがあります。私は春のバリデーションを使用して、すべてのバリデーションを自分自身でチェックするための定型コードを書く必要はありません。複数の従業員タイプのオブジェクトの副作用は、APIの増加になります。各オブジェクトタイプは別々のAPIを必要とするためです。

個別のオブジェクトを持つアプローチ+ API以降のAPIとすべてのフィールドを持つ1つのオブジェクトと、従業員タイプに基づいて各フィールドの手動検証を行うための良い提案はありますか?

public class EmployeeDTO { 

     /** 
     * Employee Type: full-time, part-time, permanent, contractor 
     */ 
     @NotNull 
     @ApiModelProperty(required = true) 
     private String employeeType; 

     /** 
     * Mandatory field that is to be given by client 
     */ 
     @NotBlank 
     @ApiModelProperty(required = true) 
     private String employeeName; 


     /** 
     * How to make this field mandatory when employeeType = contractor ? 
     * Is this possible in Spring? 
     * How to document it in Swagger? 
     */ 
     private String contractVendorName; 

} 

答えて

0

これを実装するには、クラスレベルの制約が必要です。 Read​​

@Target({ TYPE, ANNOTATION_TYPE }) 
@Retention(RUNTIME) 
@Constraint(validatedBy = { VendorNameCheckValidator.class }) 
@Documented 
public @interface VendorNameCheck { 

    String message() default "{some.message}"; 

    Class<?>[] groups() default { }; 

    Class<? extends Payload>[] payload() default { }; 
} 



public class VendorNameCheckValidator 
     implements ConstraintValidator<ValidPassengerCount, EmployeeDTO> { 

    @Override 
    public void initialize(VendorNameCheck constraintAnnotation) { 
    } 

    @Override 
    public boolean isValid(EmployeeDTO dto, ConstraintValidatorContext context) { 
     if (dto == null) { 
      return true; 
     } 

     return !"contractor".equals(dto.getEmployeeType()) || isNotEmpty(dto.getContractVendorName()); 
    } 
} 
関連する問題