Skip to content

feat(AttrAttribute): add isSortable and isFilterable #215

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
Jan 3, 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
4 changes: 1 addition & 3 deletions benchmarks/Query/QueryParser_Benchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ public QueryParser_Benchmarks() {
var controllerContextMock = new Mock<IControllerContext>();
controllerContextMock.Setup(m => m.RequestEntity).Returns(new ContextEntity {
Attributes = new List<AttrAttribute> {
new AttrAttribute(ATTRIBUTE) {
InternalAttributeName = ATTRIBUTE
}
new AttrAttribute(ATTRIBUTE, ATTRIBUTE)
}
});
var options = new JsonApiOptions();
Expand Down
2 changes: 1 addition & 1 deletion src/Examples/JsonApiDotNetCoreExample/Models/TodoItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public TodoItem()
[Attr("created-date")]
public DateTime CreatedDate { get; set; }

[Attr("achieved-date")]
[Attr("achieved-date", isFilterable: false, isSortable: false)]
public DateTime? AchievedDate { get; set; }

public int? OwnerId { get; set; }
Expand Down
5 changes: 5 additions & 0 deletions src/JsonApiDotNetCore/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("UnitTests")]
[assembly:InternalsVisibleTo("JsonApiDotNetCoreExampleTests")]
[assembly:InternalsVisibleTo("NoEntityFrameworkTests")]
[assembly:InternalsVisibleTo("Benchmarks")]
14 changes: 10 additions & 4 deletions src/JsonApiDotNetCore/Internal/Query/AttrFilterQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,20 @@ public AttrFilterQuery(

var attribute = GetAttribute(filterQuery.Attribute);

FilteredAttribute = attribute ?? throw new JsonApiException(400, $"'{filterQuery.Attribute}' is not a valid attribute.");
if(attribute == null)
throw new JsonApiException(400, $"'{filterQuery.Attribute}' is not a valid attribute.");

if(attribute.IsFilterable == false)
throw new JsonApiException(400, $"Filter is not allowed for attribute '{attribute.PublicAttributeName}'.");

FilteredAttribute = attribute;
PropertyValue = filterQuery.Value;
FilterOperation = GetFilterOperation(filterQuery.Operation);
}

public AttrAttribute FilteredAttribute { get; set; }
public string PropertyValue { get; set; }
public FilterOperations FilterOperation { get; set; }
public AttrAttribute FilteredAttribute { get; }
public string PropertyValue { get; }
public FilterOperations FilterOperation { get; }

private AttrAttribute GetAttribute(string attribute) =>
_jsonApiContext.RequestEntity.Attributes.FirstOrDefault(
Expand Down
10 changes: 8 additions & 2 deletions src/JsonApiDotNetCore/Internal/Query/RelatedAttrFilterQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,18 @@ public RelatedAttrFilterQuery(

var relationship = GetRelationship(relationshipArray[0]);
if (relationship == null)
throw new JsonApiException(400, $"{relationshipArray[0]} is not a valid relationship.");
throw new JsonApiException(400, $"{relationshipArray[1]} is not a valid relationship on {relationshipArray[0]}.");

var attribute = GetAttribute(relationship, relationshipArray[1]);

if(attribute == null)
throw new JsonApiException(400, $"'{filterQuery.Attribute}' is not a valid attribute.");

if(attribute.IsFilterable == false)
throw new JsonApiException(400, $"Filter is not allowed for attribute '{attribute.PublicAttributeName}'.");

FilteredRelationship = relationship;
FilteredAttribute = attribute ?? throw new JsonApiException(400, $"{relationshipArray[1]} is not a valid attribute on {relationshipArray[0]}.");
FilteredAttribute = attribute;
PropertyValue = filterQuery.Value;
FilterOperation = GetFilterOperation(filterQuery.Operation);
}
Expand Down
15 changes: 9 additions & 6 deletions src/JsonApiDotNetCore/Models/AttrAttribute.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
using System;
using System.Reflection;
using JsonApiDotNetCore.Internal;

namespace JsonApiDotNetCore.Models
{
public class AttrAttribute : Attribute
{
public AttrAttribute(string publicName, bool isImmutable = false)
public AttrAttribute(string publicName, bool isImmutable = false, bool isFilterable = true, bool isSortable = true)
{
PublicAttributeName = publicName;
IsImmutable = isImmutable;
IsFilterable = isFilterable;
IsSortable = isSortable;
}

public AttrAttribute(string publicName, string internalName, bool isImmutable = false)
internal AttrAttribute(string publicName, string internalName, bool isImmutable = false)
{
PublicAttributeName = publicName;
InternalAttributeName = internalName;
IsImmutable = isImmutable;
}

public string PublicAttributeName { get; set; }
public string InternalAttributeName { get; set; }
public bool IsImmutable { get; set; }
public string PublicAttributeName { get; }
public string InternalAttributeName { get; internal set; }
public bool IsImmutable { get; }
public bool IsFilterable { get; }
public bool IsSortable { get; }

public object GetValue(object entity)
{
Expand Down
6 changes: 1 addition & 5 deletions src/JsonApiDotNetCore/Models/HasManyAttribute.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
using System.Reflection;

namespace JsonApiDotNetCore.Models
{
public class HasManyAttribute : RelationshipAttribute
{
public HasManyAttribute(string publicName, Link documentLinks = Link.All)
: base(publicName, documentLinks)
{
PublicRelationshipName = publicName;
}
{ }

public override void SetValue(object entity, object newValue)
{
Expand Down
6 changes: 1 addition & 5 deletions src/JsonApiDotNetCore/Models/HasOneAttribute.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
using System.Reflection;

namespace JsonApiDotNetCore.Models
{
public class HasOneAttribute : RelationshipAttribute
{
public HasOneAttribute(string publicName, Link documentLinks = Link.All)
: base(publicName, documentLinks)
{
PublicRelationshipName = publicName;
}
{ }

public override void SetValue(object entity, object newValue)
{
Expand Down
8 changes: 4 additions & 4 deletions src/JsonApiDotNetCore/Models/RelationshipAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ protected RelationshipAttribute(string publicName, Link documentLinks)
DocumentLinks = documentLinks;
}

public string PublicRelationshipName { get; set; }
public string InternalRelationshipName { get; set; }
public Type Type { get; set; }
public string PublicRelationshipName { get; }
public string InternalRelationshipName { get; internal set; }
public Type Type { get; internal set; }
public bool IsHasMany => GetType() == typeof(HasManyAttribute);
public bool IsHasOne => GetType() == typeof(HasOneAttribute);
public Link DocumentLinks { get; set; } = Link.All;
public Link DocumentLinks { get; } = Link.All;

public abstract void SetValue(object entity, object newValue);

Expand Down
3 changes: 3 additions & 0 deletions src/JsonApiDotNetCore/Services/QueryParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ protected virtual List<SortQuery> ParseSortParameters(string value)

var attribute = GetAttribute(propertyName);

if(attribute.IsSortable == false)
throw new JsonApiException(400, $"Sort is not allowed for attribute '{attribute.PublicAttributeName}'.");

sortParameters.Add(new SortQuery(direction, attribute));
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Linq;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
Expand All @@ -8,8 +9,6 @@
using JsonApiDotNetCoreExample;
using JsonApiDotNetCoreExample.Data;
using JsonApiDotNetCoreExample.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Xunit;
using Person = JsonApiDotNetCoreExample.Models.Person;
Expand Down Expand Up @@ -44,17 +43,13 @@ public async Task Can_Filter_On_Guid_Properties()
var todoItem = _todoItemFaker.Generate();
context.TodoItems.Add(todoItem);
await context.SaveChangesAsync();

var builder = new WebHostBuilder()
.UseStartup<Startup>();

var httpMethod = new HttpMethod("GET");
var route = $"/api/v1/todo-items?filter[guid-property]={todoItem.GuidProperty}";
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(httpMethod, route);

// act
var response = await client.SendAsync(request);
var response = await _fixture.Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
var deserializedBody = _fixture
.GetService<IJsonApiDeSerializer>()
Expand All @@ -68,7 +63,6 @@ public async Task Can_Filter_On_Guid_Properties()
Assert.Equal(todoItem.GuidProperty, todoItemResponse.GuidProperty);
}


[Fact]
public async Task Can_Filter_On_Related_Attrs()
{
Expand All @@ -79,17 +73,13 @@ public async Task Can_Filter_On_Related_Attrs()
todoItem.Owner = person;
context.TodoItems.Add(todoItem);
await context.SaveChangesAsync();

var builder = new WebHostBuilder()
.UseStartup<Startup>();

var httpMethod = new HttpMethod("GET");
var route = $"/api/v1/todo-items?include=owner&filter[owner.first-name]={person.FirstName}";
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(httpMethod, route);

// act
var response = await client.SendAsync(request);
var response = await _fixture.Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
var documents = JsonConvert.DeserializeObject<Documents>(await response.Content.ReadAsStringAsync());
var included = documents.Included;
Expand All @@ -101,5 +91,20 @@ public async Task Can_Filter_On_Related_Attrs()
foreach(var item in included)
Assert.Equal(person.FirstName, item.Attributes["first-name"]);
}

[Fact]
public async Task Cannot_Filter_If_Explicitly_Forbidden()
{
// arrange
var httpMethod = new HttpMethod("GET");
var route = $"/api/v1/todo-items?include=owner&filter[achieved-date]={DateTime.UtcNow.Date}";
var request = new HttpRequestMessage(httpMethod, route);

// act
var response = await _fixture.Client.SendAsync(request);

// assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using JsonApiDotNetCoreExample;
using Xunit;

namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec
{
[Collection("WebHostCollection")]
public class AttributeSortTests
{
private TestFixture<Startup> _fixture;

public AttributeSortTests(TestFixture<Startup> fixture)
{
_fixture = fixture;
}

[Fact]
public async Task Cannot_Sort_If_Explicitly_Forbidden()
{
// arrange
var httpMethod = new HttpMethod("GET");
var route = $"/api/v1/todo-items?include=owner&sort=achieved-date";
var request = new HttpRequestMessage(httpMethod, route);

// act
var response = await _fixture.Client.SendAsync(request);

// assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
}
}