Skip to content

Not In Filter #361

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

Merged
merged 3 commits into from
Jul 31, 2018
Merged
Show file tree
Hide file tree
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
24 changes: 17 additions & 7 deletions src/JsonApiDotNetCore/Extensions/IQueryableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,10 @@ public static IQueryable<TSource> Filter<TSource>(this IQueryable<TSource> sourc

try
{
if (filterQuery.FilterOperation == FilterOperations.@in )
if (filterQuery.FilterOperation == FilterOperations.@in || filterQuery.FilterOperation == FilterOperations.nin)
{
string[] propertyValues = filterQuery.PropertyValue.Split(',');
var lambdaIn = ArrayContainsPredicate<TSource>(propertyValues, property.Name);
var lambdaIn = ArrayContainsPredicate<TSource>(propertyValues, property.Name, filterQuery.FilterOperation);

return source.Where(lambdaIn);
}
Expand Down Expand Up @@ -167,10 +167,10 @@ public static IQueryable<TSource> Filter<TSource>(this IQueryable<TSource> sourc

try
{
if (filterQuery.FilterOperation == FilterOperations.@in)
if (filterQuery.FilterOperation == FilterOperations.@in || filterQuery.FilterOperation == FilterOperations.nin)
{
string[] propertyValues = filterQuery.PropertyValue.Split(',');
var lambdaIn = ArrayContainsPredicate<TSource>(propertyValues, relatedAttr.Name, relation.Name);
var lambdaIn = ArrayContainsPredicate<TSource>(propertyValues, relatedAttr.Name, filterQuery.FilterOperation, relation.Name);

return source.Where(lambdaIn);
}
Expand Down Expand Up @@ -243,7 +243,7 @@ private static Expression GetFilterExpressionLambda(Expression left, Expression
return body;
}

private static Expression<Func<TSource, bool>> ArrayContainsPredicate<TSource>(string[] propertyValues, string fieldname, string relationName = null)
private static Expression<Func<TSource, bool>> ArrayContainsPredicate<TSource>(string[] propertyValues, string fieldname, FilterOperations op, string relationName = null)
{
ParameterExpression entity = Expression.Parameter(typeof(TSource), "entity");
MemberExpression member;
Expand All @@ -258,8 +258,18 @@ private static Expression<Func<TSource, bool>> ArrayContainsPredicate<TSource>(s
var method = ContainsMethod.MakeGenericMethod(member.Type);
var obj = TypeHelper.ConvertListType(propertyValues, member.Type);

var exprContains = Expression.Call(method, new Expression[] { Expression.Constant(obj), member });
return Expression.Lambda<Func<TSource, bool>>(exprContains, entity);
if (op == FilterOperations.@in)
{
// Where(i => arr.Contains(i.column))
var contains = Expression.Call(method, new Expression[] { Expression.Constant(obj), member });
return Expression.Lambda<Func<TSource, bool>>(contains, entity);
}
else
{
// Where(i => !arr.Contains(i.column))
var notContains = Expression.Not(Expression.Call(method, new Expression[] { Expression.Constant(obj), member }));
return Expression.Lambda<Func<TSource, bool>>(notContains, entity);
}
}

public static IQueryable<TSource> Select<TSource>(this IQueryable<TSource> source, List<string> columns)
Expand Down
1 change: 1 addition & 0 deletions src/JsonApiDotNetCore/Internal/Query/FilterOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ public enum FilterOperations
like = 5,
ne = 6,
@in = 7, // prefix with @ to use keyword
nin = 8
}
}
3 changes: 2 additions & 1 deletion src/JsonApiDotNetCore/Services/QueryParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ protected virtual List<FilterQuery> ParseFilterQuery(string key, string value)

// InArray case
string op = GetFilterOperation(value);
if (string.Equals(op, [email protected](), StringComparison.OrdinalIgnoreCase))
if (string.Equals(op, [email protected](), StringComparison.OrdinalIgnoreCase)
|| string.Equals(op, FilterOperations.nin.ToString(), StringComparison.OrdinalIgnoreCase))
{
(var operation, var filterValue) = ParseFilterOperation(value);
queries.Add(new FilterQuery(propertyName, filterValue, op));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,5 +209,45 @@ public async Task Can_Filter_On_Related_In_Array_Values()
Assert.Contains(item.Attributes["first-name"], ownerFirstNames);

}

[Fact]
public async Task Can_Filter_On_Not_In_Array_Values()
{
// arrange
var context = _fixture.GetService<AppDbContext>();
var todoItems = _todoItemFaker.Generate(5);
var guids = new List<Guid>();
var notInGuids = new List<Guid>();
foreach (var item in todoItems)
{
context.TodoItems.Add(item);
// Exclude 2 items
if (guids.Count < (todoItems.Count() - 2))
guids.Add(item.GuidProperty);
else
notInGuids.Add(item.GuidProperty);
}
context.SaveChanges();

var totalCount = context.TodoItems.Count();
var httpMethod = new HttpMethod("GET");
var route = $"/api/v1/todo-items?page[size]={totalCount}&filter[guid-property]=nin:{string.Join(",", notInGuids)}";
var request = new HttpRequestMessage(httpMethod, route);

// act
var response = await _fixture.Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
var deserializedTodoItems = _fixture
.GetService<IJsonApiDeSerializer>()
.DeserializeList<TodoItem>(body);

// assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(totalCount - notInGuids.Count(), deserializedTodoItems.Count());
foreach (var item in deserializedTodoItems)
{
Assert.DoesNotContain(item.GuidProperty, notInGuids);
}
}
}
}