1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2024-11-01 00:12:30 +01:00
Sonarr/NzbDrone.Api/REST/RestModule.cs

93 lines
2.8 KiB
C#
Raw Normal View History

2013-04-20 02:05:28 +02: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 22:16:33 +02:00
where TResource : RestResource, new()
2013-04-20 02:05:28 +02: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 22:16:33 +02:00
2013-04-20 02:05:28 +02: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 22:16:33 +02:00
//resource.ValidateForPost();
2013-04-20 02:05:28 +02:00
}
else if (Request.Method.Equals("PUT", StringComparison.InvariantCultureIgnoreCase))
{
2013-04-20 22:16:33 +02:00
//resource.ValidateForPut();
2013-04-20 02:05:28 +02:00
}
return resource;
}
}
}