Skip to content

V0.1.4-beta #16

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 12 commits into from
Sep 2, 2016
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
19 changes: 10 additions & 9 deletions JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
using System;
using AutoMapper;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Controllers;
using JsonApiDotNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;

namespace JsonApiDotNetCore.Extensions
{
public static class IServiceCollectionExtensions
{
public static void AddJsonApi(this IServiceCollection services, Action<IJsonApiModelConfiguration> configurationAction)
public static class IServiceCollectionExtensions
{
var configBuilder = new JsonApiConfigurationBuilder(configurationAction);
var config = configBuilder.Build();
IRouter router = new Router(config, new RouteBuilder(config), new ControllerBuilder());
services.AddSingleton(_ => router);
public static void AddJsonApi(this IServiceCollection services, Action<IJsonApiModelConfiguration> configurationAction)
{
var configBuilder = new JsonApiConfigurationBuilder(configurationAction);
var config = configBuilder.Build();
services.AddTransient(_ =>
{
return (IRouter)new Router(config, new RouteBuilder(config), new ControllerBuilder());
});
}
}
}
}
15 changes: 13 additions & 2 deletions JsonApiDotNetCore/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,19 @@ public static string ToProperCase(this string str)
var chars = str.ToCharArray();
if (chars.Length > 0)
{
chars[0] = new string(chars[0], 1).ToUpper().ToCharArray()[0];
return new String(chars);
chars[0] = char.ToUpper(chars[0]);
var builder = new StringBuilder();
for(var i = 0; i < chars.Length; i++)
{
if((chars[i]) == '-') {
i = i + 1;
builder.Append(char.ToUpper(chars[i]));
}
else {
builder.Append(chars[i]);
}
}
return builder.ToString();
}
return str;
}
Expand Down
2 changes: 1 addition & 1 deletion JsonApiDotNetCore/Middleware/JsonApiMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public async Task Invoke(HttpContext context)
_logger.LogInformation("Passing request to JsonApiService: " + context.Request.Path);

if(IsJsonApiRequest(context)) {
var routeWasHandled = _router.HandleJsonApiRoute(context, _serviceProvider);
var routeWasHandled = await _router.HandleJsonApiRouteAsync(context, _serviceProvider);
if(!routeWasHandled)
RespondNotFound(context);
}
Expand Down
3 changes: 2 additions & 1 deletion JsonApiDotNetCore/Routing/IRouter.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace JsonApiDotNetCore.Routing
{
public interface IRouter
{
bool HandleJsonApiRoute(HttpContext context, IServiceProvider serviceProvider);
Task<bool> HandleJsonApiRouteAsync(HttpContext context, IServiceProvider serviceProvider);
}
}
126 changes: 62 additions & 64 deletions JsonApiDotNetCore/Routing/Router.cs
Original file line number Diff line number Diff line change
@@ -1,90 +1,88 @@
using System;
using System.Text;
using System.Threading.Tasks;
using JsonApiDotNetCore.Abstractions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Controllers;
using JsonApiDotNetCore.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace JsonApiDotNetCore.Routing
{
public class Router : IRouter
{
private readonly JsonApiModelConfiguration _jsonApiModelConfiguration;
private IServiceProvider _serviceProvider;
private JsonApiContext _jsonApiContext;
private IRouteBuilder _routeBuilder;
private IControllerBuilder _controllerBuilder;

public Router(JsonApiModelConfiguration configuration, IRouteBuilder routeBuilder, IControllerBuilder controllerBuilder)
public class Router : IRouter
{
_jsonApiModelConfiguration = configuration;
_routeBuilder = routeBuilder;
_controllerBuilder = controllerBuilder;
}
private readonly JsonApiModelConfiguration _jsonApiModelConfiguration;
private IServiceProvider _serviceProvider;
private IRouteBuilder _routeBuilder;
private IControllerBuilder _controllerBuilder;

public bool HandleJsonApiRoute(HttpContext context, IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
public Router(JsonApiModelConfiguration configuration, IRouteBuilder routeBuilder, IControllerBuilder controllerBuilder)
{
_jsonApiModelConfiguration = configuration;
_routeBuilder = routeBuilder;
_controllerBuilder = controllerBuilder;
}

var route = _routeBuilder.BuildFromRequest(context.Request);
if (route == null) return false;
public async Task<bool> HandleJsonApiRouteAsync(HttpContext context, IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;

InitializeContext(context, route);
CallController();
var route = _routeBuilder.BuildFromRequest(context.Request);
if (route == null) return false;

return true;
}
var jsonApiContext = InitializeContext(context, route);
await CallController(jsonApiContext);

private void InitializeContext(HttpContext context, Route route)
{
var dbContext = _serviceProvider.GetService(_jsonApiModelConfiguration.ContextType);
_jsonApiContext = new JsonApiContext(context, route, dbContext, _jsonApiModelConfiguration);
}
return true;
}

private void CallController()
{
var controller = _controllerBuilder.BuildController(_jsonApiContext);
private JsonApiContext InitializeContext(HttpContext context, Route route)
{
var dbContext = _serviceProvider.GetService(_jsonApiModelConfiguration.ContextType);
Console.WriteLine("InitializingContext");
return new JsonApiContext(context, route, dbContext, _jsonApiModelConfiguration);
}

var result = ActivateControllerMethod(controller);
private async Task CallController(JsonApiContext jsonApiContext)
{
var controller = _controllerBuilder.BuildController(jsonApiContext);

result.Value = SerializeResult(result.Value);
var result = ActivateControllerMethod(controller, jsonApiContext);

SendResponse(result);
}
result.Value = SerializeResult(result.Value, jsonApiContext);

private ObjectResult ActivateControllerMethod(IJsonApiController controller)
{
var route = _jsonApiContext.Route;
switch (route.RequestMethod)
{
case "GET":
return string.IsNullOrEmpty(route.ResourceId) ? controller.Get() : controller.Get(route.ResourceId);
case "POST":
return controller.Post(new JsonApiDeserializer(_jsonApiContext).GetEntityFromRequest());
case "PATCH":
return controller.Patch(route.ResourceId, new JsonApiDeserializer(_jsonApiContext).GetEntityPatch());
case "DELETE":
return controller.Delete(route.ResourceId);
default:
throw new ArgumentException("Request method not supported", nameof(route));
}
}
await SendResponse(jsonApiContext.HttpContext, result);
}

private object SerializeResult(object result)
{
return result == null ? null : new JsonApiSerializer(_jsonApiContext).ToJsonApiDocument(result);
}
private ObjectResult ActivateControllerMethod(IJsonApiController controller, JsonApiContext jsonApiContext)
{
var route = jsonApiContext.Route;
switch (route.RequestMethod)
{
case "GET":
return string.IsNullOrEmpty(route.ResourceId) ? controller.Get() : controller.Get(route.ResourceId);
case "POST":
return controller.Post(new JsonApiDeserializer(jsonApiContext).GetEntityFromRequest());
case "PATCH":
return controller.Patch(route.ResourceId, new JsonApiDeserializer(jsonApiContext).GetEntityPatch());
case "DELETE":
return controller.Delete(route.ResourceId);
default:
throw new ArgumentException("Request method not supported", nameof(route));
}
}

private void SendResponse(ObjectResult result)
{
var context = _jsonApiContext.HttpContext;
context.Response.StatusCode = result.StatusCode ?? 500;
context.Response.ContentType = "application/vnd.api+json";
context.Response.WriteAsync(result.Value == null ? "" : result.Value.ToString(), Encoding.UTF8);
context.Response.Body.Flush();
private object SerializeResult(object result, JsonApiContext jsonApiContext)
{
return result == null ? null : new JsonApiSerializer(jsonApiContext).ToJsonApiDocument(result);
}

private async Task SendResponse(HttpContext context, ObjectResult result)
{
context.Response.StatusCode = result.StatusCode ?? 500;
context.Response.ContentType = "application/vnd.api+json";
await context.Response.WriteAsync(result.Value == null ? "" : result.Value.ToString(), Encoding.UTF8);
}
}
}
}
17 changes: 15 additions & 2 deletions JsonApiDotNetCore/project.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
{
"version": "0.1.3",
"version": "0.1.4-beta-*",
"packOptions": {
"summary": "Complete JSONAPI Middleware, Routing, and Controller package for .Net Core",
"tags": [
"dotnetcore",
"jsonapi",
"emberjs"
],
"owners": [
"Jared Nance",
"Children's Research Institue"
],
"licenseUrl": "https://github.com/Research-Institute/json-api-dotnet-core/tree/master/JsonApiDotNetCore/LICENSE",
"projectUrl": "https://github.com/Research-Institute/json-api-dotnet-core/"
"projectUrl": "https://github.com/Research-Institute/json-api-dotnet-core",
"repository": {
"url": "https://github.com/Research-Institute/json-api-dotnet-core"
}
},
"dependencies": {
"NETStandard.Library": "1.6.0",
Expand Down
6 changes: 5 additions & 1 deletion JsonApiDotNetCoreExample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ public Startup(IHostingEnvironment env)
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCors();

services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration["Data:ConnectionString"]),
ServiceLifetime.Transient);
Expand All @@ -54,6 +55,9 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseCors(builder =>
builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials());

app.UseJsonApi();
}
}
Expand Down
2 changes: 1 addition & 1 deletion JsonApiDotNetCoreExample/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"JsonApiDotNetCore": "0.1.2",
"JsonApiDotNetCore": "0.1.4-beta-*",
"Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public void ToCamelCase_ConvertsString_ToCamelCase(string input, string expected

[Theory]
[InlineData("todoItem", "TodoItem")]
[InlineData("todo-items", "TodoItems")]
public void ToProperCase_ConvertsString_ToProperCase(string input, string expectedOutput)
{
// arrange
Expand Down
16 changes: 9 additions & 7 deletions JsonApiDotNetCoreTests/Helpers/TestRouter.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
using System;
using System.Threading.Tasks;
using JsonApiDotNetCore.Routing;
using Microsoft.AspNetCore.Http;

namespace JsonApiDotNetCoreTests.Helpers
{
public class TestRouter : IRouter
{
public bool DidHandleRoute { get; set; }
public bool HandleJsonApiRoute(HttpContext context, IServiceProvider serviceProvider)
public class TestRouter : IRouter
{
DidHandleRoute = true;
return true;
public bool DidHandleRoute { get; set; }

Task<bool> IRouter.HandleJsonApiRouteAsync(HttpContext context, IServiceProvider serviceProvider)
{
DidHandleRoute = true;
return Task.Run(() => true);
}
}
}
}
Loading