Skip to content

feat: add support for more operators than contains #117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/utils/convert-filter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import escape from 'escape-regexp'
import mongoose from 'mongoose'

const OPERATOR_SEPARATOR = '~';

const MATCHING_PATTERNS = {
EQ: 'equals',
NE: 'notEquals',
CO: 'contains',
EW: 'endsWith',
SW: 'startsWith',
};

const OPERATORS = {
AND: 'and',
OR: 'or',
};

/**
* Changes AdminJS's {@link Filter} to an object acceptible by a mongoose query.
*
Expand All @@ -15,6 +30,54 @@ export const convertFilter = (filter) => {
const { property, value } = filterProperty
switch (property.type()) {
case 'string':
if (typeof value === 'object') {
if (value[MATCHING_PATTERNS.SW]) {
return {
[property.name()]: { $regex: `^${escape(value[MATCHING_PATTERNS.SW])}`, $options: 'i' },
...memo,
}
} else if (value[MATCHING_PATTERNS.EW]) {
return {
[property.name()]: { $regex: `${escape(value[MATCHING_PATTERNS.EW])}$`, $options: 'i' },
...memo,
}
} else if (value[MATCHING_PATTERNS.EQ]) {
return {
[property.name()]: value[MATCHING_PATTERNS.EQ],
...memo,
}
} else if (value[MATCHING_PATTERNS.NE]) {
return {
[property.name()]: { $ne: value[MATCHING_PATTERNS.NE] },
...memo,
}
} else {
let operatorExpression;
const orPrefix = `${OPERATORS.OR}${OPERATOR_SEPARATOR}`;
if (value[`${orPrefix}${MATCHING_PATTERNS.SW}`]) {
operatorExpression = { $regex: `^${escape(value[`${orPrefix}${MATCHING_PATTERNS.SW}`])}`, $options: 'i' }
} else if (value[`${orPrefix}${MATCHING_PATTERNS.EW}`]) {
operatorExpression = { $regex: `${escape(value[`${orPrefix}${MATCHING_PATTERNS.EW}`])}$`, $options: 'i' }
} else if (value[`${orPrefix}${MATCHING_PATTERNS.EQ}`]) {
operatorExpression = value[`${orPrefix}${MATCHING_PATTERNS.EQ}`]
} else if (value[`${orPrefix}${MATCHING_PATTERNS.NE}`]) {
operatorExpression = { $ne: value[`${orPrefix}${MATCHING_PATTERNS.NE}`] }
} else if (value[OPERATORS.OR]) {
operatorExpression = { $regex: escape(value[OPERATORS.OR]), $options: 'i' }
}

return {
...memo,
$or: [
...(memo['$or'] || []),
{
[property.name()]: operatorExpression,
},
],
};
}
}

return {
[property.name()]: { $regex: escape(value), $options: 'i' },
...memo,
Expand Down