Last active
September 2, 2015 13:25
-
-
Save jchannon/2db8829f26145cf62baf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Cache : ICache | |
{ | |
private ConcurrentDictionary<int, Response> cachedResponses = new ConcurrentDictionary<int,Response>(); //Use Redis in Production | |
public Response GetOrInvalidate(NancyContext ctx) | |
{ | |
Response resp; | |
if(ctx.Request.Method == "GET") | |
{ | |
if (!cache.TryGetValue(ctx.Request.Headers.IfNoneMatch.Value, out resp) | |
{ | |
return null; | |
} | |
return resp; | |
} | |
this.Invalidate(ctx.Request.Headers.IfNoneMatch.Value); | |
return null; | |
} | |
public Invalidate(NancyContext ctx) | |
{ | |
cachedResponse.Remove(ctx.Request.Headers.IfNoneMatch.Value); | |
} | |
public Add(int Id, Response resp) | |
{ | |
cache.Add(id,resp); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Nancy.ETag | |
{ | |
using System; | |
using Nancy; | |
public class MainModule : NancyModule | |
{ | |
public MainModule(ICache cache, ISomeRepoOrServiceOrOtherLayerYouLove someRepoOrServiceOrOtherLayerYouLove) | |
{ | |
Get["/{int:id}"] = x => { | |
return someRepoOrServiceOrOtherLayerYouLove.Get(x.id); | |
}; | |
Put["/{int:id}"] = x => { | |
var model = this.BindAndValidate<MyModel>(); | |
someRepoOrServiceOrOtherLayerYouLove.Update(x.id,model); | |
return 204; | |
}; | |
Before += ctx => { | |
return cache.GetOrInvalidate(ctx); | |
}; | |
After += ctx => { | |
if (ctx.Request.Method == "GET") | |
{ | |
var id = GenerateUniqueId(); | |
ctx.Response.Headers.ETag = id; | |
cache.Add(id, ctx.Response); //Get response body | |
} | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment