Skip to content

Instantly share code, notes, and snippets.

@AlessioGr
Created July 26, 2023 21:04
Show Gist options
  • Save AlessioGr/7af8ad7d9ec5a9d9578003f33311dd04 to your computer and use it in GitHub Desktop.
Save AlessioGr/7af8ad7d9ec5a9d9578003f33311dd04 to your computer and use it in GitHub Desktop.
simplifyWhereQuery.ts
import type { Where } from '../../../../types';
export const simplifyWhereQuery = (whereQuery: Where): Where => {
if (!whereQuery?.or) {
return whereQuery;
}
// Filter out {} values from 'or' array.
const orArray = whereQuery.or.filter((obj) => Object.keys(obj).length !== 0);
// If 'or' array has one element and 'and' field has only one element, return the single 'WhereField' from the 'and' array.
if (orArray.length === 1 && orArray[0].and?.length === 1) {
return orArray[0].and[0];
}
// If 'or' array has one element and 'and' field has multiple elements, return the 'and' array.
if (orArray.length === 1 && orArray[0].and?.length > 1) {
return { and: orArray[0].and };
}
// If 'whereQuery' doesn't fit the above conditions, return it as it is.
return whereQuery;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment