sonarr-repo-only/NzbDrone.Api/REST/RestModule.cs

93 lines
2.8 KiB
C#
Raw Normal View History

2013-04-20 00:05:28 +00:00
using System;
using System.Collections.Generic;
using Nancy;
using NzbDrone.Api.Extensions;
namespace NzbDrone.Api.REST
{
public abstract class RestModule<TResource> : NancyModule
2013-04-20 20:16:33 +00:00
where TResource : RestResource, new()
2013-04-20 00:05:28 +00:00
{
private const string ROOT_ROUTE = "/";
private const string ID_ROUTE = "/{id}";
protected RestModule()
: this(new TResource().ResourceName)
{
}
protected RestModule(string modulePath)
: base(modulePath)
{
Get[ROOT_ROUTE] = options =>
{
EnsureImplementation(GetResourceAll);
var resource = GetResourceAll();
return resource.AsResponse();
};
Get[ID_ROUTE] = options =>
{
EnsureImplementation(GetResourceById);
var resource = GetResourceById(options.Id);
return resource.AsResponse();
};
Post[ROOT_ROUTE] = options =>
{
EnsureImplementation(CreateResource);
var resource = CreateResource(ReadFromRequest());
return resource.AsResponse(HttpStatusCode.Created);
};
Put[ROOT_ROUTE] = options =>
{
EnsureImplementation(UpdateResource);
var resource = UpdateResource(ReadFromRequest());
return resource.AsResponse(HttpStatusCode.Accepted);
};
Delete[ID_ROUTE] = options =>
{
EnsureImplementation(DeleteResource);
DeleteResource(options.Id);
return new Response { StatusCode = HttpStatusCode.OK };
};
2013-04-20 20:16:33 +00:00
2013-04-20 00:05:28 +00:00
}
protected Action<int> DeleteResource { get; set; }
protected Func<int, TResource> GetResourceById { get; set; }
protected Func<List<TResource>> GetResourceAll { get; set; }
protected Func<TResource, TResource> CreateResource { get; set; }
protected Func<TResource, TResource> UpdateResource { get; set; }
private void EnsureImplementation(Delegate implementation)
{
if (implementation == null)
{
throw new NotImplementedException();
}
}
private TResource ReadFromRequest()
{
var resource = Request.Body.FromJson<TResource>();
if (Request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
{
2013-04-20 20:16:33 +00:00
//resource.ValidateForPost();
2013-04-20 00:05:28 +00:00
}
else if (Request.Method.Equals("PUT", StringComparison.InvariantCultureIgnoreCase))
{
2013-04-20 20:16:33 +00:00
//resource.ValidateForPut();
2013-04-20 00:05:28 +00:00
}
return resource;
}
}
}