Skip to content

feat: set up basiscs for ID fetching #640

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 7 commits into from
Nov 28, 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
146 changes: 118 additions & 28 deletions src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Internal.Contracts;
using JsonApiDotNetCore.Managers.Contracts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Primitives;

Expand All @@ -21,6 +23,7 @@ public class CurrentRequestMiddleware
private ICurrentRequest _currentRequest;
private IResourceGraph _resourceGraph;
private IJsonApiOptions _options;
private RouteValueDictionary _routeValues;
private IControllerResourceMapping _controllerResourceMapping;

public CurrentRequestMiddleware(RequestDelegate next)
Expand All @@ -39,12 +42,15 @@ public async Task Invoke(HttpContext httpContext,
_controllerResourceMapping = controllerResourceMapping;
_resourceGraph = resourceGraph;
_options = options;
_routeValues = httpContext.GetRouteData().Values;
var requestResource = GetCurrentEntity();
if (requestResource != null)
{
_currentRequest.SetRequestResource(GetCurrentEntity());
_currentRequest.SetRequestResource(requestResource);
_currentRequest.IsRelationshipPath = PathIsRelationship();
_currentRequest.BasePath = GetBasePath(_currentRequest.GetRequestResource().ResourceName);
_currentRequest.BasePath = GetBasePath(requestResource.ResourceName);
_currentRequest.BaseId = GetBaseId();
_currentRequest.RelationshipId = GetRelationshipId();
}

if (IsValid())
Expand All @@ -53,50 +59,127 @@ public async Task Invoke(HttpContext httpContext,
}
}

private string GetBasePath(string entityName)
private string GetBaseId()
{
var r = _httpContext.Request;
if (_options.RelativeLinks)
var resource = _currentRequest.GetRequestResource();
var individualComponents = SplitCurrentPath();
if (individualComponents.Length < 2)
{
return GetNamespaceFromPath(r.Path, entityName);
return null;
}
return $"{r.Scheme}://{r.Host}{GetNamespaceFromPath(r.Path, entityName)}";
var indexOfResource = individualComponents.ToList().FindIndex(c => c == resource.ResourceName);
var baseId = individualComponents.ElementAtOrDefault(indexOfResource + 1);
if (baseId == null)
{
return null;
}
CheckIdType(baseId, resource.IdentityType);
return baseId;
}
private string GetRelationshipId()
{
var resource = _currentRequest.GetRequestResource();
if (!_currentRequest.IsRelationshipPath)
{
return null;
}
var components = SplitCurrentPath();
var toReturn = components.ElementAtOrDefault(4);

internal static string GetNamespaceFromPath(string path, string entityName)
if (toReturn == null)
{
return null;
}
var relType = _currentRequest.RequestRelationship.RightType;
var relResource = _resourceGraph.GetResourceContext(relType);
var relIdentityType = relResource.IdentityType;
CheckIdType(toReturn, relIdentityType);
return toReturn;
}
private string[] SplitCurrentPath()
{
var entityNameSpan = entityName.AsSpan();
var pathSpan = path.AsSpan();
const char delimiter = '/';
for (var i = 0; i < pathSpan.Length; i++)
var path = _httpContext.Request.Path.Value;
var ns = $"/{GetNameSpace()}";
var nonNameSpaced = path.Replace(ns, "");
nonNameSpaced = nonNameSpaced.Trim('/');
var individualComponents = nonNameSpaced.Split('/');
return individualComponents;
}


private void CheckIdType(string value, Type idType)
{
try
{
if (pathSpan[i].Equals(delimiter))
var converter = TypeDescriptor.GetConverter(idType);
if (converter != null)
{
var nextPosition = i + 1;
if (pathSpan.Length > i + entityNameSpan.Length)
if (!converter.IsValid(value))
{
var possiblePathSegment = pathSpan.Slice(nextPosition, entityNameSpan.Length);
if (entityNameSpan.SequenceEqual(possiblePathSegment))
throw new JsonApiException(500, $"We could not convert the id '{value}'");
}
else
{
if (idType == typeof(int))
{
// check to see if it's the last position in the string
// or if the next character is a /
var lastCharacterPosition = nextPosition + entityNameSpan.Length;

if (lastCharacterPosition == pathSpan.Length || pathSpan.Length >= lastCharacterPosition + 2 && pathSpan[lastCharacterPosition].Equals(delimiter))
if ((int)converter.ConvertFromString(value) < 0)
{
return pathSpan.Slice(0, i).ToString();
throw new JsonApiException(500, "The base ID is an integer, and it is negative.");
}
}
}
}
}
catch (NotSupportedException)
{

}

return string.Empty;
}

private string GetBasePath(string resourceName = null)
{
var r = _httpContext.Request;
if (_options.RelativeLinks)
{
return GetNameSpace(resourceName);
}
var ns = GetNameSpace(resourceName);
var customRoute = GetCustomRoute(r.Path.Value, resourceName);
var toReturn = $"{r.Scheme}://{r.Host}/{ns}";
if(customRoute != null)
{
toReturn += $"/{customRoute}";
}
return toReturn;
}

private object GetCustomRoute(string path, string resourceName)
{
var ns = GetNameSpace();
var trimmedComponents = path.Trim('/').Split('/').ToList();
var resourceNameIndex = trimmedComponents.FindIndex(c => c == resourceName);
var newComponents = trimmedComponents.Take(resourceNameIndex ).ToArray();
var customRoute = string.Join('/', newComponents);
if(customRoute == ns)
{
return null;
}
else
{
return customRoute;
}
}

private string GetNameSpace(string resourceName = null)
{

return _options.Namespace;
}

protected bool PathIsRelationship()
{
var actionName = (string)_httpContext.GetRouteData().Values["action"];
var actionName = (string)_routeValues["action"];
return actionName.ToLower().Contains("relationships");
}

Expand Down Expand Up @@ -124,7 +207,9 @@ private bool IsValidAcceptHeader(HttpContext context)
foreach (var acceptHeader in acceptHeaders)
{
if (ContainsMediaTypeParameters(acceptHeader) == false)
{
continue;
}

FlushResponse(context, 406);
return false;
Expand Down Expand Up @@ -165,16 +250,21 @@ private void FlushResponse(HttpContext context, int statusCode)
/// <returns></returns>
private ResourceContext GetCurrentEntity()
{
var controllerName = (string)_httpContext.GetRouteValue("controller");
var controllerName = (string)_routeValues["controller"];
if (controllerName == null)
{
return null;
}
var resourceType = _controllerResourceMapping.GetAssociatedResource(controllerName);
var requestResource = _resourceGraph.GetResourceContext(resourceType);
if (requestResource == null)
{
return requestResource;
var rd = _httpContext.GetRouteData().Values;
if (rd.TryGetValue("relationshipName", out object relationshipName))
}
if (_routeValues.TryGetValue("relationshipName", out object relationshipName))
{
_currentRequest.RequestRelationship = requestResource.Relationships.Single(r => r.PublicRelationshipName == (string)relationshipName);
}
return requestResource;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ public interface ICurrentRequest
/// is the relationship attribute associated with the targeted relationship
/// </summary>
RelationshipAttribute RequestRelationship { get; set; }
string BaseId { get; set; }
string RelationshipId { get; set; }

/// <summary>
/// Sets the current context entity for this entire request
Expand Down
2 changes: 2 additions & 0 deletions src/JsonApiDotNetCore/RequestServices/CurrentRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ class CurrentRequest : ICurrentRequest
public string BasePath { get; set; }
public bool IsRelationshipPath { get; set; }
public RelationshipAttribute RequestRelationship { get; set; }
public string BaseId { get; set; }
public string RelationshipId { get; set; }

/// <summary>
/// The main resource of the request.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public async Task CustomRouteControllers_Creates_Proper_Relationship_Links()
var deserializedBody = JsonConvert.DeserializeObject<JObject>(body);

var result = deserializedBody["data"]["relationships"]["owner"]["links"]["related"].ToString();
Assert.EndsWith($"{route}/owner", deserializedBody["data"]["relationships"]["owner"]["links"]["related"].ToString());
Assert.EndsWith($"{route}/owner", result);
}
}
}
Loading