Files
TinyInvoice/Server/Data/CustomerData.cs
Andre Beging cc877259cf Refactor file path retrieval for settings and customer data.
Replaced hardcoded file paths with a method that retrieves the parent directory, ensuring consistency and maintainability. This change affects methods for loading and saving JSON data in both SettingsData and CustomerData classes.
2024-11-06 16:26:52 +01:00

65 lines
2.0 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
using Server.Model;
namespace Server.Data
{
public class CustomerData
{
#region Public Properties
public List<Address> Customers { get; set; } = [];
public static CustomerData Instance { get; set; } = new();
#endregion
/// <summary>
/// Retrieves the file path for the settings JSON file.
/// </summary>
/// <returns>The file path of the settings JSON file as a string.</returns>
private static string GetFilePath()
{
var parentDirectory = Directory.GetParent(Directory.GetCurrentDirectory());
if (parentDirectory == null) return "Customers.json";
return Path.Combine(parentDirectory.FullName, "Customers.json");
}
#region Public Method LoadAsync
/// <summary>
/// Loads customer data asynchronously from a JSON file if it exists.
/// </summary>
/// <return>
/// A Task representing the asynchronous operation.
/// </return>
public static async Task LoadAsync()
{
if (!File.Exists(GetFilePath())) return;
var jsonString = await File.ReadAllTextAsync(GetFilePath());
var deserialized = JsonSerializer.Deserialize<CustomerData>(jsonString)!;
Instance = deserialized;
}
#endregion
#region Public Method SaveAsync
/// <summary>
/// Saves the current customer data asynchronously to a JSON file.
/// </summary>
/// <return>
/// A Task representing the asynchronous operation.
/// </return>
public static async Task SaveAsync()
{
var jsonString = JsonSerializer.Serialize(Instance, new JsonSerializerOptions { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
await File.WriteAllTextAsync(GetFilePath(), jsonString);
}
#endregion
}
}