package com.changhu.common.utils;

import cn.hutool.core.collection.CollUtil;
import com.changhu.common.exception.MessageException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * author: luozhun
 * desc: ValidatorUtil
 * createTime: 2023/8/22 9:39
 */
public class ValidatorUtil {
    /**
     * 手动校验
     */
    public static <T> void manual(T params) {
        try (ValidatorFactory vf = Validation.buildDefaultValidatorFactory()) {
            Validator validator = vf.getValidator();
            Set<ConstraintViolation<T>> validateResult = validator.validate(params);
            if (CollUtil.isNotEmpty(validateResult)) {
                String errMessage = validateResult.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
                throw new MessageException(errMessage);
            }
        }
    }
}
