Open conioX opened 7 months ago
This code is work for me:
import { FilteringQueryGroup } from 'nest-standard-response';
export function parseFilterGroupToPrisma(
filterGroup: FilteringQueryGroup,
): any {
if (filterGroup.allOf) {
return {
AND: filterGroup.allOf.map(parseFilterGroupToPrisma),
};
} else if (filterGroup.anyOf) {
return {
OR: filterGroup.anyOf.map(parseFilterGroupToPrisma),
};
} else {
const operation = filterGroup as any;
if (Object.keys(operation).length === 0) {
return {};
}
let { field, value } = operation;
value = parsePrismaValue(value);
switch (operation.operation) {
case '==':
return { [field]: value };
case '!=':
return { NOT: { [field]: value } };
case '>=':
return { [field]: { gte: value } };
case '>':
return { [field]: { gt: value } };
case '<=':
return { [field]: { lte: value } };
case '<':
return { [field]: { lt: value } };
case '=@':
return { [field]: { contains: value } };
case '!@':
return { NOT: { [field]: { contains: value } } };
case '=^':
return { [field]: { startsWith: value } };
case '=$':
return { [field]: { endsWith: value } };
default:
throw new Error(`Unsupported operation: ${operation.operation}`);
}
}
}
export function parseSortToPrisma(sort: string): any {
return sort.split(',').map((field) => {
if (field.startsWith('-')) {
return { [field.slice(1)]: 'desc' };
} else {
return { [field]: 'asc' };
}
});
}
function parsePrismaValue(value: string): any {
if (value === 'true') {
return true;
} else if (value === 'false') {
return false;
} else if (!isNaN(Number(value))) {
return Number(value);
} else if (new Date(value).toString() !== 'Invalid Date') {
return new Date(value);
} else {
return value;
}
}
Amazing library :) hopefully you have some recommendation to transform filter or sorting into prisma query.