aboutsummaryrefslogtreecommitdiff
path: root/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/EntityJsonHelper.cs
blob: 1265fe910967837abf937febcc6f34618bef2f86 (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
using System.Text.Json;
using Microsoft.Extensions.Options;

namespace CrupestApi.Commons.Crud;

/// <summary>
/// Contains all you need to do with json.
/// </summary>
public class EntityJsonHelper<TEntity> where TEntity : class
{
    private readonly TableInfo _table;
    private readonly IOptionsMonitor<JsonSerializerOptions> _jsonSerializerOptions;

    public EntityJsonHelper(TableInfoFactory tableInfoFactory, IOptionsMonitor<JsonSerializerOptions> jsonSerializerOptions)
    {
        _table = tableInfoFactory.Get(typeof(TEntity));
        _jsonSerializerOptions = jsonSerializerOptions;
    }

    public virtual Dictionary<string, object?> ConvertEntityToDictionary(TEntity entity, bool includeNonColumnProperties = false)
    {
        var result = new Dictionary<string, object?>();

        foreach (var column in _table.PropertyColumns)
        {
            var value = column.PropertyInfo!.GetValue(entity);
            var realValue = column.ColumnType.ConvertToDatabase(value);
            result[column.ColumnName] = realValue;
        }

        if (includeNonColumnProperties)
        {
            foreach (var propertyInfo in _table.NonColumnProperties)
            {
                var value = propertyInfo.GetValue(entity);
                result[propertyInfo.Name] = value;
            }
        }

        return result;
    }

    public virtual string ConvertEntityToJson(TEntity entity, bool includeNonColumnProperties = false)
    {
        var dictionary = ConvertEntityToDictionary(entity, includeNonColumnProperties);
        return JsonSerializer.Serialize(dictionary, _jsonSerializerOptions.CurrentValue);
    }

    public virtual IInsertClause ConvertJsonElementToInsertClauses(JsonElement rootElement)
    {
        var insertClause = InsertClause.Create();

        if (rootElement.ValueKind != JsonValueKind.Object)
        {
            throw new UserException("The root element must be an object.");
        }

        foreach (var column in _table.PropertyColumns)
        {
            object? value = null;
            if (rootElement.TryGetProperty(column.ColumnName, out var propertyElement))
            {
                value = propertyElement.ValueKind switch
                {
                    JsonValueKind.Null or JsonValueKind.Undefined => null,
                    JsonValueKind.Number => propertyElement.GetDouble(),
                    JsonValueKind.True => true,
                    JsonValueKind.False => false,
                    JsonValueKind.String => propertyElement.GetString(),
                    _ => throw new Exception($"Bad json value of property {column.ColumnName}.")
                };
            }

            if (column.IsGenerated && value is not null)
            {
                throw new UserException($"The property {column.ColumnName} is generated. You cannot specify its value.");
            }

            if (column.IsNotNull && !column.CanBeGenerated && value is null)
            {
                throw new UserException($"The property {column.ColumnName} can't be null or generated. But you specify a null value.");
            }

            insertClause.Add(column.ColumnName, value);
        }

        return insertClause;
    }

    public IInsertClause ConvertJsonToInsertClauses(string json)
    {
        var document = JsonSerializer.Deserialize<JsonDocument>(json, _jsonSerializerOptions.CurrentValue)!;
        return ConvertJsonElementToInsertClauses(document.RootElement);
    }

    public IUpdateClause ConvertJsonElementToUpdateClause(JsonElement rootElement, bool saveNull)
    {
        var updateClause = UpdateClause.Create();

        if (rootElement.ValueKind != JsonValueKind.Object)
        {
            throw new UserException("The root element must be an object.");
        }

        foreach (var column in _table.PropertyColumns)
        {
            object? value = null;

            if (rootElement.TryGetProperty(column.ColumnName, out var propertyElement))
            {
                value = propertyElement.ValueKind switch
                {
                    JsonValueKind.Null or JsonValueKind.Undefined => null,
                    JsonValueKind.Number => propertyElement.GetDouble(),
                    JsonValueKind.True => true,
                    JsonValueKind.False => false,
                    JsonValueKind.String => propertyElement.GetString(),
                    _ => throw new Exception($"Bad json value of property {column.ColumnName}.")
                };

                if (column.IsNoUpdate && (value is not null || saveNull))
                {
                    throw new UserException($"The property {column.ColumnName} is not updatable. You cannot specify its value.");
                }
            }

            if (value is null && !saveNull)
            {
                continue;
            }

            updateClause.Add(column.ColumnName, value ?? DbNullValue.Instance);
        }

        return updateClause;
    }

    public IUpdateClause ConvertJsonElementToUpdateClause(JsonElement rootElement)
    {
        var updateClause = UpdateClause.Create();

        if (rootElement.ValueKind != JsonValueKind.Object)
        {
            throw new UserException("The root element must be an object.");
        }

        bool saveNull = false;

        if (rootElement.TryGetProperty("$saveNull", out var propertyElement))
        {
            if (propertyElement.ValueKind is not JsonValueKind.True or JsonValueKind.False)
            {
                throw new UserException("$saveNull can only be true or false.");
            }

            if (propertyElement.ValueKind is JsonValueKind.True)
            {
                saveNull = true;
            }
        }

        return ConvertJsonElementToUpdateClause(rootElement, saveNull);
    }

    public IUpdateClause ConvertJsonToUpdateClause(string json)
    {
        var document = JsonSerializer.Deserialize<JsonDocument>(json, _jsonSerializerOptions.CurrentValue)!;
        return ConvertJsonElementToUpdateClause(document.RootElement);
    }
}