FastBlog/src/FastBlog.Core/Repositories/BlogBlogFileRepository.cs

41 lines
1.4 KiB
C#

using FastBlog.Core.Abstractions.Repositories.Blogs;
using FastBlog.Core.Models;
using FastBlog.Core.Options;
using Microsoft.Extensions.Options;
namespace FastBlog.Core.Repositories;
public sealed class BlogBlogFileRepository(IOptionsMonitor<FileStoreOptions> fileOptions) : IBlogFileRepository
{
public async Task<string?> Read(string path)
{
var targetPath = Path.Combine(fileOptions.CurrentValue.BlogSourcePath, path);
if (!File.Exists(targetPath)) return null;
return await File.ReadAllTextAsync(targetPath);
}
public async Task<Result<bool, BusinessError>> Write(string path, string text)
{
var targetPath = Path.Combine(fileOptions.CurrentValue.BlogSourcePath, path);
var directoryPath = Path.GetDirectoryName(targetPath);
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath!);
if (File.Exists(targetPath))
return new BusinessError("already_exists", "File already exists");
await File.WriteAllTextAsync(targetPath, text);
return true;
}
public Task<bool> Delete(string path)
{
var targetPath = Path.Combine(fileOptions.CurrentValue.BlogSourcePath, path);
if (!File.Exists(targetPath))
return Task.FromResult(false);
File.Delete(targetPath);
return Task.FromResult(true);
}
}