staff_data/packages/utils/src/safePrismaQuery.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-03-02 11:49:46 +08:00
type PrismaCondition = Record<string, any>;
type SafeOROptions = {
/**
*
* @default 'return-undefined' undefined ()
* 'throw-error'
* 'return-empty'
*/
emptyBehavior?: "return-undefined" | "throw-error" | "return-empty";
};
/**
* OR
* @param conditions
* @param options
* @returns Prisma WHERE
*/
export const safeOR = (
conditions: PrismaCondition[],
options?: SafeOROptions
): PrismaCondition | undefined => {
const { emptyBehavior = "return-undefined" } = options || {};
// 过滤空条件和无效值
const validConditions = conditions.filter(
(cond) => cond && Object.keys(cond).length > 0
);
// 处理全空情况
if (validConditions.length === 0) {
switch (emptyBehavior) {
case "throw-error":
throw new Error("No valid conditions provided to OR query");
case "return-empty":
return {};
case "return-undefined":
default:
return undefined;
}
}
// 优化单条件查询
return validConditions.length === 1
? validConditions[0]
: { OR: validConditions };
};