bitwarden-android/src/Core/Services/LiteDbStorageService.cs

74 lines
2 KiB
C#
Raw Normal View History

2019-03-28 06:44:54 +03:00
using Bit.Core.Abstractions;
using LiteDB;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
2019-03-28 06:44:54 +03:00
using System.Linq;
using System.Threading.Tasks;
namespace Bit.Core.Services
{
public class LiteDbStorageService : IStorageService
{
private readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
2019-04-26 17:30:41 +03:00
private readonly string _dbPath;
private LiteCollection<JsonItem> _collection;
2019-03-28 06:44:54 +03:00
public LiteDbStorageService(string dbPath)
{
2019-04-26 17:30:41 +03:00
_dbPath = dbPath;
}
public void Init()
{
if(_collection == null)
{
var db = new LiteDatabase($"Filename={_dbPath};");
_collection = db.GetCollection<JsonItem>("json_items");
}
2019-03-28 06:44:54 +03:00
}
public Task<T> GetAsync<T>(string key)
{
2019-04-26 17:30:41 +03:00
Init();
2019-03-28 06:44:54 +03:00
var item = _collection.Find(i => i.Id == key).FirstOrDefault();
if(item == null)
{
return Task.FromResult(default(T));
}
return Task.FromResult(JsonConvert.DeserializeObject<T>(item.Value, _jsonSettings));
2019-03-28 06:44:54 +03:00
}
public Task SaveAsync<T>(string key, T obj)
{
2019-04-26 17:30:41 +03:00
Init();
var data = JsonConvert.SerializeObject(obj, _jsonSettings);
2019-03-28 06:44:54 +03:00
_collection.Upsert(new JsonItem(key, data));
return Task.FromResult(0);
}
public Task RemoveAsync(string key)
{
2019-04-26 17:30:41 +03:00
Init();
2019-03-28 06:44:54 +03:00
_collection.Delete(i => i.Id == key);
return Task.FromResult(0);
}
private class JsonItem
{
public JsonItem() { }
public JsonItem(string key, string value)
{
Id = key;
Value = value;
}
public string Id { get; set; }
public string Value { get; set; }
}
}
}