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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
|
public class FirestoreCrud : IFirestoreCrud
{
private readonly FirestoreDb _db;
private const string MasterSchemaCollection = "MasterSchema";
private readonly TimeSpan _schemaCacheTtl = TimeSpan.FromMinutes(5);
public FirestoreCrud(FirestoreDb db)
{
_db = db ?? throw new ArgumentNullException(nameof(db));
}
#region Schema Management & Caching
/// <summary>
/// Returns master schema(s). If collectionName is null/empty or "*" fetches all schema documents.
/// Otherwise returns a dictionary with a single entry for the requested collection (if exists).
/// This method retrieves schema definitions from the MasterSchema collection in Firestore.
/// </summary>
public async Task<Dictionary<string, MasterSchema>> GetMasterSchemaAsync(string collectionName)
{
try
{
var result = new Dictionary<string, MasterSchema>(StringComparer.OrdinalIgnoreCase);
QuerySnapshot snapshot = await _db.Collection(MasterSchemaCollection).GetSnapshotAsync();
foreach (var doc in snapshot.Documents)
{
var collectionSchema = new CollectionSchema
{
Name = doc.Id,
Properties = new Dictionary<string, PropertySchema>(StringComparer.OrdinalIgnoreCase)
};
var dict = doc.ToDictionary();
if (dict.TryGetValue("Properties", out var propsObj) && propsObj is Dictionary<string, object> propsDict)
{
foreach (var propEntry in propsDict)
{
if (propEntry.Value is Dictionary<string, object> propDetails)
{
var propSchema = new PropertySchema
{
Type = propDetails.ContainsKey("Type") ? propDetails["Type"] as string : null,
Collection = propDetails.ContainsKey("Collection") ? propDetails["Collection"] as string : null
};
collectionSchema.Properties[propEntry.Key] = propSchema;
}
}
}
var ms = new MasterSchema();
ms.Master[doc.Id] = collectionSchema;
result[doc.Id] = ms;
}
if (string.IsNullOrWhiteSpace(collectionName) || collectionName == "*") return result;
return result.Where(kv => kv.Key.Equals(collectionName, StringComparison.OrdinalIgnoreCase))
.ToDictionary(k => k.Key, k => k.Value);
}
catch (Exception ex)
{
return null;
}
}
public async Task<string> CreateMasterSchemaTypeByCollectionNameIfNotExistAsync(string collectionName, Dictionary<string, CollectionSchema> masterSchema)
{
if (string.IsNullOrWhiteSpace(collectionName)) throw new ArgumentNullException(nameof(collectionName));
try
{
var docRef = _db.Collection(MasterSchemaCollection).Document(collectionName);
var snapshot = await docRef.GetSnapshotAsync();
if (snapshot.Exists)
{
return collectionName;
}
// Convert to plain dictionary for Firestore
var properties = masterSchema?.Values.FirstOrDefault()?.Properties ?? new Dictionary<string, PropertySchema>();
var propsForFirestore = properties.ToDictionary(k => k.Key, k => (object)new Dictionary<string, object>
{
{ "Type", k.Value.Type },
{ "Collection", k.Value.Collection }
});
var payload = new Dictionary<string, object>
{
{"Name", collectionName},
{"Properties", propsForFirestore}
};
await docRef.SetAsync(payload);
return collectionName;
}
catch (Exception ex)
{
return null;
}
}
public async Task<string> UpdateMasterSchemaTypeByCollectionNameAsync(string collectionName, Dictionary<string, CollectionSchema> masterSchema)
{
if (string.IsNullOrWhiteSpace(collectionName)) throw new ArgumentNullException(nameof(collectionName));
try
{
var docRef = _db.Collection(MasterSchemaCollection).Document(collectionName);
var snapshot = await docRef.GetSnapshotAsync();
if (!snapshot.Exists)
{
return await CreateMasterSchemaTypeByCollectionNameIfNotExistAsync(collectionName, masterSchema);
}
var properties = masterSchema?.Values.FirstOrDefault()?.Properties ?? new Dictionary<string, PropertySchema>();
var propsForFirestore = properties.ToDictionary(k => k.Key, k => (object)new Dictionary<string, object>
{
{ "Type", k.Value.Type },
{ "Collection", k.Value.Collection }
});
var payload = new Dictionary<string, object>
{
{"Name", collectionName},
{"Properties", propsForFirestore}
};
await docRef.SetAsync(payload, SetOptions.Overwrite);
return collectionName;
}
catch (Exception ex)
{
return null;
}
}
#endregion
#region CRUD Methods
/// <summary>
/// CREATE: Adds a new document to a collection with automatic type conversion and validation.
/// Returns the auto-generated document ID on success.
/// </summary>
public async Task<string> AddAsync(string collectionName, Dictionary<string, object> data)
{
if (string.IsNullOrWhiteSpace(collectionName)) throw new ArgumentNullException(nameof(collectionName));
if (data == null) throw new ArgumentNullException(nameof(data));
// validate and normalize
if (!await ValidateDataAsync(collectionName, data, isPartialUpdate: false)) return null;
try
{
var converted = await ConvertToFirestoreCompatibleAsync(collectionName, data);
var docRef = await _db.Collection(collectionName).AddAsync(converted);
return docRef.Id;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// READ: Retrieves a single document by its ID from the specified collection.
/// Returns the document data as a dictionary with automatic type conversion.
/// </summary>
public async Task<Dictionary<string, object>> GetByDocumentIdAsync(string collectionName, string documentId)
{
if (string.IsNullOrWhiteSpace(collectionName) || string.IsNullOrWhiteSpace(documentId)) return null;
try
{
var snapshot = await _db.Collection(collectionName).Document(documentId).GetSnapshotAsync();
if (!snapshot.Exists) return null;
var dict = snapshot.ToDictionary();
var normalized = ConvertFromFirestoreTypes(dict);
normalized["_id"] = snapshot.Id;
return normalized;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// READ (All): Retrieves all documents in a collection.
/// Returns a dictionary mapping document IDs to their data.
/// Note: Be careful with large collections as this fetches all documents.
/// </summary>
public async Task<Dictionary<string, object>> GetCollectionAsync(string collectionName)
{
var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
try
{
var snapshot = await _db.Collection(collectionName).GetSnapshotAsync();
foreach (var doc in snapshot.Documents)
{
var d = ConvertFromFirestoreTypes(doc.ToDictionary());
d["_id"] = doc.Id;
result[doc.Id] = d;
}
return result;
}
catch (Exception ex)
{
return result;
}
}
/// <summary>
/// READ (Paginated): Retrieves documents with pagination, sorting, and filtering support.
/// Parameters:
/// - limit: Maximum number of documents to retrieve (default: 15)
/// - orderBy: Field name to sort by (optional)
/// - descending: Sort in descending order (default: false)
/// - startAfterDocumentId: Document ID to start after for pagination
/// Returns a dictionary mapping document IDs to their data.
/// </summary>
public async Task<Dictionary<string, Dictionary<string, object>>> GetCollectionAsync(string collectionName, int limit = 15, string pageToken = null, string orderBy = null, bool descending = false, string startAfterDocumentId = null)
{
var result = new Dictionary<string, Dictionary<string, object>>(StringComparer.OrdinalIgnoreCase);
try
{
Query query = _db.Collection(collectionName);
if (!string.IsNullOrWhiteSpace(orderBy))
{
query = descending ? query.OrderByDescending(orderBy) : query.OrderBy(orderBy);
}
if (limit > 0) query = query.Limit(limit);
if (!string.IsNullOrWhiteSpace(startAfterDocumentId))
{
var startDoc = await _db.Collection(collectionName).Document(startAfterDocumentId).GetSnapshotAsync();
if (startDoc.Exists)
{
query = query.StartAfter(startDoc);
}
}
var snapshot = await query.GetSnapshotAsync();
foreach (var doc in snapshot.Documents)
{
var d = ConvertFromFirestoreTypes(doc.ToDictionary());
d["_id"] = doc.Id;
result[doc.Id] = d;
}
return result;
}
catch (Exception ex)
{
return result;
}
}
/// <summary>
/// UPDATE: Modifies an existing document with partial data (only specified fields are updated).
/// Other fields remain unchanged. Returns the document ID on success.
/// </summary>
public async Task<string> UpdateByDocumentIdAsync(string collectionName, string documentId, Dictionary<string, object> data)
{
if (string.IsNullOrWhiteSpace(collectionName) || string.IsNullOrWhiteSpace(documentId)) throw new ArgumentNullException("collectionName/documentId");
if (data == null) throw new ArgumentNullException(nameof(data));
if (!await ValidateDataAsync(collectionName, data, isPartialUpdate: true)) return null;
try
{
var converted = await ConvertToFirestoreCompatibleAsync(collectionName, data);
await _db.Collection(collectionName).Document(documentId).UpdateAsync(converted);
return documentId;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// DELETE: Removes a document from a collection by its ID.
/// Returns the document ID on success, null on failure.
/// </summary>
public async Task<string> DeleteByDocumentIdAsync(string collectionName, string documentId)
{
if (string.IsNullOrWhiteSpace(collectionName) || string.IsNullOrWhiteSpace(documentId)) throw new ArgumentNullException("collectionName/documentId");
try
{
await _db.Collection(collectionName).Document(documentId).DeleteAsync();
return documentId;
}
catch (Exception ex)
{
return null;
}
}
#endregion
#region Helpers: Validation + Conversion
/// <summary>
/// VALIDATION: Ensures data conforms to the collection's schema.
/// For CREATE operations (isPartialUpdate=false): all schema fields must be present
/// For UPDATE operations (isPartialUpdate=true): only supplied fields are validated
/// </summary>
private async Task<bool> ValidateDataAsync(string collectionName, Dictionary<string, object> data, bool isPartialUpdate = false)
{
// Fetch schema for the specific collection
var schemas = await GetMasterSchemaAsync(collectionName);
if (schemas == null || !schemas.TryGetValue(collectionName, out var ms))
{
return false;
}
var collectionSchema = ms.Master[collectionName];
if (!isPartialUpdate)
{
// enforce presence of required fields (every field defined in schema is treated as required by default)
foreach (var required in collectionSchema.Properties.Keys)
{
if (!data.ContainsKey(required))
{
return false;
}
}
}
// Type validation for supplied fields
foreach (var kv in data)
{
if (!collectionSchema.Properties.TryGetValue(kv.Key, out var propSchema))
{
return false;
}
if (!IsTypeValid(kv.Value, propSchema.Type))
{
return false;
}
}
return true;
}
/// <summary>
/// TYPE CHECKING: Validates that a value matches its declared schema type.
/// Supports Firestore types: String, Number, Boolean, Timestamp, Reference, Map, Array
/// </summary>
private bool IsTypeValid(object value, string schemaType)
{
if (value == null) return true; // allow nulls
switch (schemaType)
{
case "String": return value is string;
case "Number": return value is int || value is long || value is double || value is float || value is decimal;
case "Boolean": return value is bool;
case "Timestamp": return value is DateTime || value is Google.Cloud.Firestore.Timestamp;
case "Reference": return value is DocumentReference || value is string; // allow string id (we'll resolve it)
case "Map": return value is Dictionary<string, object>;
case "Array": return value is System.Collections.IEnumerable && !(value is string);
default: return false;
}
}
/// <summary>
/// DESERIALIZATION: Converts Firestore's native types to .NET-friendly types.
/// - Firestore Timestamps → DateTime
/// - DocumentReferences → Document paths
/// - Nested Maps → Dictionaries (recursive)
/// - Arrays → Lists (recursive)
/// </summary>
private Dictionary<string, object> ConvertFromFirestoreTypes(Dictionary<string, object> input)
{
var result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var kv in input)
{
if (kv.Value is Google.Cloud.Firestore.Timestamp t)
{
result[kv.Key] = t.ToDateTime();
}
else if (kv.Value is DocumentReference docRef)
{
result[kv.Key] = docRef.Path; // expose path which can be used to resolve reference
}
else if (kv.Value is Dictionary<string, object> map)
{
result[kv.Key] = ConvertFromFirestoreTypes(map);
}
else if (kv.Value is IEnumerable<object> list)
{
var converted = list.Select(item => item is Dictionary<string, object> imap ? ConvertFromFirestoreTypes(imap) : item).ToList();
result[kv.Key] = converted;
}
else
{
result[kv.Key] = kv.Value;
}
}
return result;
}
/// <summary>
/// SERIALIZATION: Converts .NET types to Firestore-compatible format.
/// - Resolves document references using the schema
/// - DateTime → Firestore Timestamps
/// - String IDs → DocumentReferences (intelligent path resolution)
/// - Preserves Maps and Arrays as-is
/// </summary>
private async Task<Dictionary<string, object>> ConvertToFirestoreCompatibleAsync(string collectionName, Dictionary<string, object> input)
{
var schemas = await GetMasterSchemaAsync(collectionName);
if (schemas == null || !schemas.TryGetValue(collectionName, out var ms))
{
// no schema known - just return input
return input;
}
var collectionSchema = ms.Master[collectionName];
var converted = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var kv in input)
{
if (!collectionSchema.Properties.TryGetValue(kv.Key, out var propSchema))
{
// Unknown field - pass through
converted[kv.Key] = kv.Value;
continue;
}
switch (propSchema.Type)
{
case "Reference":
// Accept either DocumentReference or string id or full path
if (kv.Value is DocumentReference dr) converted[kv.Key] = dr;
else if (kv.Value is string s)
{
if (s.Contains("/")) // assume full path
{
converted[kv.Key] = _db.Document(s);
}
else if (!string.IsNullOrWhiteSpace(propSchema.Collection))
{
converted[kv.Key] = _db.Collection(propSchema.Collection).Document(s);
}
else
{
// best-effort: try same collection
converted[kv.Key] = _db.Collection(collectionName).Document(s);
}
}
else converted[kv.Key] = kv.Value; // pass through
break;
case "Timestamp":
if (kv.Value is DateTime dt) converted[kv.Key] = Timestamp.FromDateTime(dt.ToUniversalTime());
else converted[kv.Key] = kv.Value;
break;
default:
// Map/arrays should be accepted as-is
converted[kv.Key] = kv.Value;
break;
}
}
return converted;
}
#endregion
}
|