Skip to content

Instantly share code, notes, and snippets.

@jchannon
Last active September 2, 2015 13:25
Show Gist options
  • Save jchannon/2db8829f26145cf62baf to your computer and use it in GitHub Desktop.
Save jchannon/2db8829f26145cf62baf to your computer and use it in GitHub Desktop.
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);
}
}
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