Files
monorepo/LCU.API.Internal.OnlineLoanApp/Landmark.OLA.Application/DataAccess/ConfigurationAccess.cs
T
2026-03-11 11:18:25 -05:00

115 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using Serilog;
using Landmark.OLA.Application.Common.Domain;
namespace Landmark.OLA.Application.DataAccess
{
public class ConfigurationAccess : IDisposable, IConfigurationAccess
{
private bool disposed = false;
private readonly IDataClient _client;
private readonly string _collectionName = "AppConfiguration";
public ConfigurationAccess(
IDataClient dataClient)
{
_client = dataClient;
}
private IMongoCollection<StoredSettings> GetConfigurationContainersCollection()
{
return _client.GetDatabase().GetCollection<StoredSettings>(_collectionName);
}
public StoredSettings GetStoredSettings()
{
try
{
var collection = GetConfigurationContainersCollection();
var result = collection.Find(new BsonDocument()).ToList().FirstOrDefault();
if( result == null )
{
throw new Exception("Could not find app configuration.");
}
return result;
}
catch (MongoConnectionException ex)
{
Log.Error(ex.Message);
throw new InvalidDataException("Could not load app configuration.");
}
}
public void CreateStoredSettings(StoredSettings storedSettings)
{
try
{
var collection = GetConfigurationContainersCollection();
if (collection.Find(new BsonDocument()).ToList().Count > 0)
{
throw new Exception("Can only insert 1 configuration");
}
collection.InsertOne(storedSettings);
}
catch (Exception e)
{
Log.Error(e.Message);
throw new InvalidDataException("Error occured while creating app configuration");
}
}
public void UpdateStoredSettings(StoredSettings storedSettings)
{
try
{
var collection = GetConfigurationContainersCollection();
ReplaceOneResult result = collection.ReplaceOne(eachConfig => eachConfig.Id == storedSettings.Id, storedSettings);
if (result.MatchedCount == 0 || result.ModifiedCount == 0)
{
throw new KeyNotFoundException("Item not found");
}
}
catch (KeyNotFoundException en)
{
Log.Error(en.Message);
throw new KeyNotFoundException(en.Message);
}
catch (Exception e)
{
Log.Error(e.Message);
throw new InvalidDataException("Error occured while updating app configuration");
}
}
#region IDisposable
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
}
}
this.disposed = true;
}
#endregion
}
}