Skip to content

Fix sparse fields with DefaultEntityRepository.Get() override #476

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 2 commits into from
Apr 25, 2019
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
3 changes: 2 additions & 1 deletion JsonApiDotnetCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ Global
{6DFA30D7-1679-4333-9779-6FB678E48EF5}.Release|x64.ActiveCfg = Release|Any CPU
{6DFA30D7-1679-4333-9779-6FB678E48EF5}.Release|x64.Build.0 = Release|Any CPU
{6DFA30D7-1679-4333-9779-6FB678E48EF5}.Release|x86.ActiveCfg = Release|Any CPU
{6DFA30D7-1679-4333-9779-6FB678E48EF5}.Release|x86.Build.0 = Release|Any CPU\
{6DFA30D7-1679-4333-9779-6FB678E48EF5}.Release|x86.Build.0 = Release|Any CPU
{09C0C8D8-B721-4955-8889-55CB149C3B5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{09C0C8D8-B721-4955-8889-55CB149C3B5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{09C0C8D8-B721-4955-8889-55CB149C3B5C}.Debug|x64.ActiveCfg = Debug|Any CPU
Expand All @@ -203,6 +203,7 @@ Global
{09C0C8D8-B721-4955-8889-55CB149C3B5C}.Release|x64.Build.0 = Release|Any CPU
{09C0C8D8-B721-4955-8889-55CB149C3B5C}.Release|x86.ActiveCfg = Release|Any CPU
{09C0C8D8-B721-4955-8889-55CB149C3B5C}.Release|x86.Build.0 = Release|Any CPU
{DF9BFD82-D937-4907-B0B4-64670417115F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
19 changes: 16 additions & 3 deletions src/JsonApiDotNetCore/Data/DefaultEntityRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ public DefaultEntityRepository(
_resourceDefinition = resourceDefinition;
}

/// <inheritdoc />


public virtual IQueryable<TEntity> Get()
{
if (_jsonApiContext.QuerySet?.Fields != null && _jsonApiContext.QuerySet.Fields.Count > 0)
Expand All @@ -87,6 +88,18 @@ public virtual IQueryable<TEntity> Get()
return _dbSet;
}

/// <inheritdoc />
public virtual IQueryable<TEntity> GetQueryable()
=> _dbSet;

public virtual IQueryable<TEntity> Select(IQueryable<TEntity> entities, List<string> fields)
{
if (fields?.Count > 0)
return entities.Select(fields);

return entities;
}

/// <inheritdoc />
public virtual IQueryable<TEntity> Filter(IQueryable<TEntity> entities, FilterQuery filterQuery)
{
Expand Down Expand Up @@ -127,15 +140,15 @@ public virtual IQueryable<TEntity> Sort(IQueryable<TEntity> entities, List<SortQ
/// <inheritdoc />
public virtual async Task<TEntity> GetAsync(TId id)
{
return await Get().SingleOrDefaultAsync(e => e.Id.Equals(id));
return await GetQueryable().SingleOrDefaultAsync(e => e.Id.Equals(id));
}

/// <inheritdoc />
public virtual async Task<TEntity> GetAndIncludeAsync(TId id, string relationshipName)
{
_logger?.LogDebug($"[JADN] GetAndIncludeAsync({id}, {relationshipName})");

var includedSet = Include(Get(), relationshipName);
var includedSet = Include(GetQueryable(), relationshipName);
var result = await includedSet.SingleOrDefaultAsync(e => e.Id.Equals(id));

return result;
Expand Down
9 changes: 9 additions & 0 deletions src/JsonApiDotNetCore/Data/IEntityReadRepository.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
Expand All @@ -18,8 +19,16 @@ public interface IEntityReadRepository<TEntity, in TId>
/// The base GET query. This is a good place to apply rules that should affect all reads,
/// such as authorization of resources.
/// </summary>
IQueryable<TEntity> GetQueryable();

[Obsolete("This method has been deprecated, use GetQueryable() instead")]
IQueryable<TEntity> Get();

/// <summary>
/// Apply fields to the provided queryable
/// </summary>
IQueryable<TEntity> Select(IQueryable<TEntity> entities,List<string> fields);

/// <summary>
/// Include a relationship in the query
/// </summary>
Expand Down
7 changes: 5 additions & 2 deletions src/JsonApiDotNetCore/Services/EntityResourceService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public virtual async Task<bool> DeleteAsync(TId id)

public virtual async Task<IEnumerable<TResource>> GetAsync()
{
var entities = _entities.Get();
var entities = _entities.GetQueryable();

entities = ApplySortAndFilterQuery(entities);

Expand All @@ -108,6 +108,9 @@ public virtual async Task<IEnumerable<TResource>> GetAsync()
if (_jsonApiContext.Options.IncludeTotalRecordCount)
_jsonApiContext.PageManager.TotalRecords = await _entities.CountAsync(entities);

if (_jsonApiContext.QuerySet?.Fields?.Count > 0)
entities = _entities.Select(entities, _jsonApiContext.QuerySet.Fields);

// pagination should be done last since it will execute the query
var pagedEntities = await ApplyPageQueryAsync(entities);
return pagedEntities;
Expand Down Expand Up @@ -240,7 +243,7 @@ protected virtual IQueryable<TEntity> IncludeRelationships(IQueryable<TEntity> e

private async Task<TResource> GetWithRelationshipsAsync(TId id)
{
var query = _entities.Get().Where(e => e.Id.Equals(id));
var query = _entities.GetQueryable().Where(e => e.Id.Equals(id));

_jsonApiContext.QuerySet.IncludedRelationships.ForEach(r =>
{
Expand Down
2 changes: 0 additions & 2 deletions test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System;
using GettingStarted.Models;
using GettingStarted.ResourceDefinitionExample;
using JsonApiDotNetCore.Builders;
Expand All @@ -7,7 +6,6 @@
using JsonApiDotNetCore.Models;
using JsonApiDotNetCore.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,42 @@ public async Task Total_Record_Count_Included()
foreach(var item in deserializedBody)
Assert.Equal(person.Id, item.OwnerId);
}

[Fact]
public async Task Sparse_Fields_Works_With_Get_Override()
{
// arrange
var builder = new WebHostBuilder()
.UseStartup<AuthorizedStartup>();
var server = new TestServer(builder);
var client = server.CreateClient();
var context = (AppDbContext)server.Host.Services.GetService(typeof(AppDbContext));
var jsonApiContext = (IJsonApiContext)server.Host.Services.GetService(typeof(IJsonApiContext));

var person = new Person();
context.People.Add(person);
var todoItem = new TodoItem();
todoItem.Owner = person;
context.TodoItems.Add(todoItem);
context.SaveChanges();

var authService = (IAuthorizationService)server.Host.Services.GetService(typeof(IAuthorizationService));
authService.CurrentUserId = person.Id;

var httpMethod = new HttpMethod("GET");
var route = $"/api/v1/todo-items/{todoItem.Id}?fields[todo-items]=description";

var request = new HttpRequestMessage(httpMethod, route);

// act
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
var deserializedBody = _fixture.GetService<IJsonApiDeSerializer>().Deserialize<TodoItem>(responseBody);

// assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(todoItem.Description, deserializedBody.Description);

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ public AuthorizedTodoItemsRepository(
_authService = authService;
}

public override IQueryable<TodoItem> Get()
public override IQueryable<TodoItem> GetQueryable()
{
return base.Get().Where(todoItem => todoItem.OwnerId == _authService.CurrentUserId);
return base.GetQueryable().Where(todoItem => todoItem.OwnerId == _authService.CurrentUserId);
}
}
}