Created
February 18, 2014 12:27
-
-
Save ShawInnes/9070055 to your computer and use it in GitHub Desktop.
CouchBase RepoositoryBase
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
using Couchbase; | |
using Couchbase.Extensions; | |
using Enyim.Caching.Memcached; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using System.Web; | |
using WebSite.Models; | |
namespace WebSite.Repository | |
{ | |
public abstract class RepositoryBase<T> where T : ModelBase | |
{ | |
protected static readonly CouchbaseClient _client = null; | |
private readonly string _designDoc; | |
static RepositoryBase() | |
{ | |
_client = new CouchbaseClient(); | |
} | |
public RepositoryBase() | |
{ | |
_designDoc = typeof(T).Name.ToLower(); | |
} | |
public virtual ulong Create(T model) | |
{ | |
return store(StoreMode.Add, model); | |
} | |
public virtual ulong Update(T model) | |
{ | |
return store(StoreMode.Replace, model); | |
} | |
public virtual ulong Save(T model) | |
{ | |
return store(StoreMode.Set, model); | |
} | |
private ulong store(StoreMode mode, T model) | |
{ | |
return _client.StoreJson(mode, BuildKey(model), model) ? (ulong)1 : 0; | |
} | |
public IEnumerable<T> GetAll(int limit = 0) | |
{ | |
var view = _client.GetView<T>(_designDoc, "all", true); | |
if (limit > 0) view.Limit(limit); | |
view.Stale(StaleMode.False); | |
return view; | |
} | |
public int Count() | |
{ | |
var view = _client.GetView<T>(_designDoc, "all", true); | |
view.Stale(StaleMode.False); | |
return view.Count(); | |
} | |
public virtual T Get(string id) | |
{ | |
var doc = _client.GetJson<T>(id); | |
//if (doc != null) doc.Id = id; //server doesn't pass back the _id in the JSON | |
return doc; | |
} | |
public virtual void Remove(string id) | |
{ | |
_client.Remove(id); | |
} | |
public IView<IViewRow> View(string viewName) | |
{ | |
return _client.GetView(_designDoc, viewName); | |
} | |
public IView<IViewRow> View(string designDoc, string viewName) | |
{ | |
return _client.GetView(designDoc, viewName); | |
} | |
protected virtual string BuildKey(T model) | |
{ | |
if (string.IsNullOrEmpty(model.Id)) | |
return Guid.NewGuid().ToString(); | |
return string.Concat(model.Type, "_", model.Id.Replace(" ", "_")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment