Skip to content
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

Generic interface support #70

Merged
merged 4 commits into from
Nov 3, 2014
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ namespace {{Namespace}}
using RefitInternalGenerated;

[Preserve]
public partial class AutoGenerated{{InterfaceName}} : {{InterfaceName}}
public partial class AutoGenerated{{InterfaceName}}{{#TypeParameters}}<{{.}}>{{/TypeParameters}} : {{InterfaceName}}{{#TypeParameters}}<{{.}}>{{/TypeParameters}}
{{#ConstraintClauses}}
{{.}}
{{/ConstraintClauses}}
{
public HttpClient Client { get; protected set; }
readonly Dictionary<string, Func<HttpClient, object[], object>> methodImpls;
Expand Down
10 changes: 9 additions & 1 deletion InterfaceStubGenerator/InterfaceStubGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ namespace Refit.Generator
// guess the class name based on our template
//
// What if the Interface is in another module? (since we copy usings, should be fine)
// What if the Interface itself is Generic? (fuck 'em)
public class InterfaceStubGenerator
{
public string GenerateInterfaceStubs(string[] paths)
Expand Down Expand Up @@ -104,6 +103,13 @@ public ClassTemplateInfo GenerateClassInfoForInterface(InterfaceDeclarationSynta
ret.Namespace = ns.Name.ToString();
ret.InterfaceName = interfaceTree.Identifier.ValueText;

if (interfaceTree.TypeParameterList != null) {
var typeParameters = interfaceTree.TypeParameterList.Parameters;
if (typeParameters.Any()) {
ret.TypeParameters = string.Join(", ", typeParameters.Select(p => p.Identifier.ValueText));
}
ret.ConstraintClauses = interfaceTree.ConstraintClauses.ToFullString().Trim();
}
ret.MethodList = interfaceTree.Members
.OfType<MethodDeclarationSyntax>()
.Select(x => new MethodTemplateInfo() {
Expand Down Expand Up @@ -147,6 +153,8 @@ public class ClassTemplateInfo
{
public string Namespace { get; set; }
public string InterfaceName { get; set; }
public string TypeParameters { get; set; }
public string ConstraintClauses { get; set; }
public List<MethodTemplateInfo> MethodList { get; set; }
}

Expand Down
2 changes: 1 addition & 1 deletion InterfaceStubGenerator/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ static void Main(string[] args)

var template = generator.GenerateInterfaceStubs(files.Select(x => x.FullName).ToArray());

int retryCount = 3;
retry:
int retryCount = 3;
var file = default(FileStream);

// NB: Parallel build weirdness means that we might get >1 person
Expand Down
24 changes: 22 additions & 2 deletions Refit-Tests/InterfaceStubGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ public void FindInterfacesSmokeTest()
input = IntegrationTestHelper.GetPath("InterfaceStubGenerator.cs");

result = fixture.FindInterfacesToGenerate(CSharpSyntaxTree.ParseFile(input));
Assert.AreEqual(1, result.Count);
Assert.AreEqual(2, result.Count);
Assert.True(result.Any(x => x.Identifier.ValueText == "IAmARefitInterfaceButNobodyUsesMe"));
Assert.True(result.Any(x => x.Identifier.ValueText == "IBoringCrudApi"));
Assert.True(result.All(x => x.Identifier.ValueText != "IAmNotARefitInterface"));
}

Expand All @@ -67,6 +68,7 @@ public void HasRefitHttpMethodAttributeSmokeTest()
Assert.IsTrue(result["AnotherRefitMethod"]);
Assert.IsFalse(result["NoConstantsAllowed"]);
Assert.IsFalse(result["NotARefitMethod"]);
Assert.IsTrue(result["ReadOne"]);
}

[Test]
Expand Down Expand Up @@ -97,7 +99,7 @@ public void GenerateTemplateInfoForInterfaceListSmokeTest()
.ToList();

var result = fixture.GenerateTemplateInfoForInterfaceList(input);
Assert.AreEqual(4, result.ClassList.Count);
Assert.AreEqual(5, result.ClassList.Count);
}

[Test]
Expand Down Expand Up @@ -136,4 +138,22 @@ public interface IAmNotARefitInterface
{
Task NotARefitMethod();
}

public interface IBoringCrudApi<T, in TKey> where T : class
{
[Post("")]
Task<T> Create([Body] T paylod);

[Get("")]
Task<List<T>> ReadAll();

[Get("/{key}")]
Task<T> ReadOne(TKey key);

[Put("/{key}")]
Task Update(TKey key, [Body]T payload);

[Delete("/{key}")]
Task Delete(TKey key);
}
}
77 changes: 77 additions & 0 deletions Refit-Tests/RefitStubs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,56 @@ public virtual Task NoConstantsAllowed()
}
}

namespace Refit.Tests
{
using RefitInternalGenerated;

[Preserve]
public partial class AutoGeneratedIBoringCrudApi<T, TKey> : IBoringCrudApi<T, TKey>
where T : class
{
public HttpClient Client { get; protected set; }
readonly Dictionary<string, Func<HttpClient, object[], object>> methodImpls;

public AutoGeneratedIBoringCrudApi(HttpClient client, IRequestBuilder requestBuilder)
{
methodImpls = requestBuilder.InterfaceHttpMethods.ToDictionary(k => k, v => requestBuilder.BuildRestResultFuncForMethod(v));
Client = client;
}

public virtual Task<T> Create(T paylod)
{
var arguments = new object[] { paylod };
return (Task<T>) methodImpls["Create"](Client, arguments);
}

public virtual Task<List<T>> ReadAll()
{
var arguments = new object[] { };
return (Task<List<T>>) methodImpls["ReadAll"](Client, arguments);
}

public virtual Task<T> ReadOne(TKey key)
{
var arguments = new object[] { key };
return (Task<T>) methodImpls["ReadOne"](Client, arguments);
}

public virtual Task Update(TKey key,T payload)
{
var arguments = new object[] { key,payload };
return (Task) methodImpls["Update"](Client, arguments);
}

public virtual Task Delete(TKey key)
{
var arguments = new object[] { key };
return (Task) methodImpls["Delete"](Client, arguments);
}

}
}

namespace Refit.Tests
{
using RefitInternalGenerated;
Expand Down Expand Up @@ -246,4 +296,31 @@ public virtual Task Get()
}
}

namespace Refit.Tests
{
using RefitInternalGenerated;

[Preserve]
public partial class AutoGeneratedIHttpBinApi<TResponse, TParam, THeader> : IHttpBinApi<TResponse, TParam, THeader>
where TResponse : class
where THeader : struct
{
public HttpClient Client { get; protected set; }
readonly Dictionary<string, Func<HttpClient, object[], object>> methodImpls;

public AutoGeneratedIHttpBinApi(HttpClient client, IRequestBuilder requestBuilder)
{
methodImpls = requestBuilder.InterfaceHttpMethods.ToDictionary(k => k, v => requestBuilder.BuildRestResultFuncForMethod(v));
Client = client;
}

public virtual Task<TResponse> Get(TParam param,THeader header)
{
var arguments = new object[] { param,header };
return (Task<TResponse>) methodImpls["Get"](Client, arguments);
}

}
}


28 changes: 28 additions & 0 deletions Refit-Tests/RestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,22 @@ public interface IAmHalfRefit
Task Get();
}

public interface IHttpBinApi<TResponse, in TParam, in THeader>
where TResponse : class
where THeader : struct
{
[Get("")]
Task<TResponse> Get(TParam param, [Header("X-Refit")] THeader header);
}

public class HttpBinGet
{
public Dictionary<string, string> Args { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Origin { get; set; }
public string Url { get; set; }
}

[TestFixture]
public class RestServiceIntegrationTests
{
Expand Down Expand Up @@ -221,5 +237,17 @@ public async Task NonRefitMethodsThrowMeaningfulExceptions()
StringAssert.Contains("no Refit HTTP method attribute", exception.Message);
}
}

[Test]
public async Task GenericsWork()
{
var fixture = RestService.For<IHttpBinApi<HttpBinGet, string, int>>("http://httpbin.org/get");

var result = await fixture.Get("foo", 99);

Assert.AreEqual("http://httpbin.org/get?param=foo", result.Url);
Assert.AreEqual("foo", result.Args["param"]);
Assert.AreEqual("99", result.Headers["X-Refit"]);
}
}
}
6 changes: 4 additions & 2 deletions Refit/RequestBuilderImplementation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,10 @@ public RestMethodInfo(Type targetInterface, MethodInfo methodInfo)
}
}

void verifyUrlPathIsSane(string relativePath)
{
void verifyUrlPathIsSane(string relativePath) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{ ⬇️

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops. I haven't yet figured out how to get R# to respect your conventions and sometimes I miss mistakes. Do you use it? Might be worth checking in a settings file if you have one.

if (relativePath == "")
return;

if (!relativePath.StartsWith("/")) {
goto bogusPath;
}
Expand Down