import { ElMessage } from 'element-plus';
|
import { AxiosInstance, AxiosResponse } from 'axios';
|
import { Ref, unref } from 'vue';
|
import request from '/@/utils/request';
|
|
/**
|
* 获取检查唯一性的 validator,用于 formRules
|
* @param GetIsExist 检查唯一性接口
|
* @param initialValue 初始值 Ref
|
* @param keyword 检查的是什么(中文)
|
* @param targetKey 检查的是什么(英文)
|
* @param extraParams 检查唯一性接口时额外传送的参数,默认没有额外参数(传参 value 值可能需要 Ref,检查时需要动态获取该值)
|
* @param isNullable 该字段是否可以为空,默认不能为空,可以不传
|
* @param req 使用的 req,默认为 request
|
* @returns
|
*/
|
export const useValidateUniqueness = (
|
GetIsExist: (parameter: any, req?: AxiosInstance) => Promise<AxiosResponse<any, any>>,
|
initialValue: Ref<any>,
|
keyword: string,
|
targetKey: string,
|
extraParams: Record<string, any> = {},
|
isNullable = false,
|
req:any = request
|
) => {
|
const getIsExist = async (targetValue, req) => {
|
const rawExtraParams = {};
|
for (let key in extraParams) {
|
rawExtraParams[key] = unref(extraParams[key]);
|
}
|
const params = {
|
[targetKey]: targetValue,
|
...rawExtraParams,
|
};
|
const res = await GetIsExist(params, req);
|
if (res?.Code === 0) {
|
if (res.Data) {
|
return res.Data;
|
}
|
} else {
|
ElMessage.error(`检查${keyword}唯一性失败` + (res?.Message ? `,${JSON.stringify(res.Message)}` : ''));
|
}
|
};
|
const uniquenessValidator = async (rule, value, callback) => {
|
if (value === '' && !isNullable) {
|
callback(`请输入${keyword}`);
|
}
|
if (value !== initialValue.value) {
|
if (value === '') {
|
callback();
|
} else {
|
const isExist = await getIsExist(value, req);
|
if (!isExist) {
|
callback();
|
} else {
|
callback(`${keyword}已存在`);
|
}
|
}
|
}
|
|
callback();
|
};
|
|
return {
|
uniquenessValidator,
|
};
|
};
|