using MongoDB.Bson; using MongoDB.Bson.IO; namespace FozFc.Api.Infrastructure.Mongo; /// /// Helpers to convert between the flexible JSON documents the frontend exchanges /// and the BSON documents stored in MongoDB, and to map Mongo's _id to the /// id the frontend expects. /// public static class BsonJson { private static readonly JsonWriterSettings RelaxedJson = new() { OutputMode = JsonOutputMode.RelaxedExtendedJson, }; /// Parse a raw JSON object string into a BSON document (or null if invalid). public static BsonDocument? TryParse(string? json) { if (string.IsNullOrWhiteSpace(json)) return null; try { return BsonDocument.Parse(json); } catch { return null; } } /// Serialize a BSON document to relaxed extended JSON (plain numbers/strings). public static string ToJson(BsonDocument document) => document.ToJson(RelaxedJson); /// Serialize a sequence of documents to a JSON array string. public static string ToJsonArray(IEnumerable documents) => "[" + string.Join(",", documents.Select(ToJson)) + "]"; /// Rename _id to id for output. Returns the same instance for chaining. public static BsonDocument NormalizeForOutput(BsonDocument document) { if (document.Contains("_id")) { var id = document["_id"]; document.Remove("_id"); document["id"] = id; } document.Remove("passwordHash"); return document; } }