refactor(cache): check if file exists in load

recyclarr
Robert Dailey 3 years ago
parent 85c7e167a1
commit 59934be5d4

@ -48,14 +48,13 @@ namespace Trash.Tests.Cache
}
[Test]
public void Load_NoFileExists_ThrowsException()
public void Load_NoFileExists_ReturnsNull()
{
// use a real filesystem to test no file existing
var ctx = new Context(new FileSystem());
Action act = () => ctx.Cache.Load<ObjectWithAttribute>();
var ctx = new Context();
ctx.Filesystem.File.Exists(Arg.Any<string>()).Returns(false);
act.Should().Throw<Exception>();
var result = ctx.Cache.Load<ObjectWithAttribute>();
result.Should().BeNull();
}
[Test]
@ -66,12 +65,14 @@ namespace Trash.Tests.Cache
ctx.StoragePath.Path.Returns("testpath");
dynamic testJson = new {TestValue = "Foo"};
ctx.Filesystem.File.Exists(Arg.Any<string>()).Returns(true);
ctx.Filesystem.File.ReadAllText(Arg.Any<string>())
.Returns(_ => JsonConvert.SerializeObject(testJson));
var obj = ctx.Cache.Load<ObjectWithAttribute>();
obj.TestValue.Should().Be("Foo");
obj.Should().NotBeNull();
obj!.TestValue.Should().Be("Foo");
ctx.Filesystem.File.Received().ReadAllText(Path.Join("testpath", "c59d1c81", $"{ValidObjectName}.json"));
}

@ -2,7 +2,7 @@
{
public interface IServiceCache
{
T Load<T>();
void Save<T>(T obj);
T? Load<T>() where T : class;
void Save<T>(T obj) where T : class;
}
}

@ -13,7 +13,7 @@ namespace Trash.Cache
{
public class ServiceCache : IServiceCache
{
private static readonly Regex AllowedObjectNameCharacters = new(@"^\w+$", RegexOptions.Compiled);
private static readonly Regex AllowedObjectNameCharacters = new(@"^[\w-]+$", RegexOptions.Compiled);
private readonly IServiceConfiguration _config;
private readonly IFileSystem _fileSystem;
private readonly IFNV1a _hash;
@ -27,13 +27,19 @@ namespace Trash.Cache
_hash = FNV1aFactory.Instance.Create(FNVConfig.GetPredefinedConfig(32));
}
public T Load<T>()
public T? Load<T>() where T : class
{
var json = _fileSystem.File.ReadAllText(PathFromAttribute<T>());
var path = PathFromAttribute<T>();
if (!_fileSystem.File.Exists(path))
{
return null;
}
var json = _fileSystem.File.ReadAllText(path);
return JObject.Parse(json).ToObject<T>();
}
public void Save<T>(T obj)
public void Save<T>(T obj) where T : class
{
var path = PathFromAttribute<T>();
_fileSystem.Directory.CreateDirectory(Path.GetDirectoryName(path));

Loading…
Cancel
Save