aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.DataStore.LiteDB/LiteDBDataStoreCollection.cs
blob: e61385ab8be211af68b1aef149576ddf6374fd36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.DataStore.Lite
{
    public class LiteDBDataStoreCollection : IDataStoreCollection
    {
        private ILiteCollection<IDataStoreItem> _collection;

        public string Name { get; private set; }

        public LiteDBDataStoreCollection(ILiteCollection<IDataStoreItem> collection)
        {
            _collection = collection;
        }

        public void Put<T>(string key, T value)
        {
            Put(key, (object)value);
        }

        public void Put(string key, object value)
        {
            Put(key, DataStoreHelper.GetDataType(value), value);
        }

        public void Put(string key, DataType type, object value)
        {
            _collection.Upsert(new LiteDBDataStoreItem()
            {
                Key = key,
                Date = DateTime.UtcNow,
                Type = type,
                Value = value,
                IsSynchronized = false,
            });
        }

        public object Get(string key)
        {
            var item = _collection.FindById(key);

            if (item == null)
            {
                throw new KeyNotFoundException("The specified key was not found on the data store.");
            }

            return item.Value;
        }

        public T Get<T>(string key)
        {
            return (T)Convert.ChangeType(Get(key), typeof(T));
        }

        public List<IDataStoreItem> GetAll()
        {
            return _collection.FindAll().ToList();
        }

        public void Delete(string key)
        {
            _collection.Delete(key);
        }

        public void DeleteAll()
        {
            _collection.DeleteMany(x => true);
        }

        public int Count()
        {
            return _collection.Count();
        }

        public IDataStoreItem GetItem(string key)
        {
            return _collection.FindById(key);
        }

        public List<IDataStoreItem> GetUnsynchronized()
        {
            return _collection.Find(x => !x.IsSynchronized).ToList();
        }
    }
}