Dalej próbuję stworzyć prostą wersję OneDrive'a i mam taki kod:
public class CreateDirectoryCommandHandler : IRequestHandler<CreateDirectoryCommand, Result>
{
private readonly ApplicationDbContext dbContext;
private readonly IAuthContext authContext;
private readonly StorageConfiguration storageConfiguration;
public CreateDirectoryCommandHandler(ApplicationDbContext dbContext, IAuthContext authContext, StorageConfiguration storageConfiguration)
{
this.dbContext = dbContext;
this.authContext = authContext;
this.storageConfiguration = storageConfiguration;
}
public async Task<Result> Handle(CreateDirectoryCommand command, CancellationToken cancellationToken)
{
var currentUserId = authContext.GetCurrentUserId();
var parentRelativePath = string.Empty;
if (command.ParentDirectoryId != null)
{
var parentDirectory = await dbContext.Directories.FindAsync(command.ParentDirectoryId);
if (parentDirectory == null)
{
return new Result(ErrorName.NotValid, "Nie można utworzyć folderu, gdyż folder nadrzędny o podanym id nie istnieje.");
}
parentRelativePath = parentDirectory.RelativePath;
}
var relativePath = Path.Combine(parentRelativePath, command.DirectoryName);
var isExisting = dbContext.Directories.Any(d => d.UserId == currentUserId && d.RelativePath == relativePath);
if (isExisting)
{
return new Result(ErrorName.NotValid, "Folder już istnieje.");
}
Directory.CreateDirectory(Path.Combine(storageConfiguration.AbsolutePath, currentUserId.ToString(), relativePath));
var createdDirectory = new MyDrive.Model.Directory
{
RelativePath = relativePath,
UserId = currentUserId
};
dbContext.Directories.Add(createdDirectory);
await dbContext.SaveChangesAsync();
return Result.SuccessfulResult;
}
}
Problem w tym, że w jednej metodzie mam walidację (wstępna jest przy użyciu FluentValidation), zapis do bazy i tworzenie katalogu na dysku. Czy wystarczy po prostu podzielić ten kod na funkcje i będzie dobrze? Przy takim podejściu funkcje walidująca i zapisująca do bazy będą miały sporo tego samego kodu, a to raczej nie dobrze (w obu metodach trzeba dokonać odczytu z bazy, aby znaleźć katalog nadrzędny, i utworzyć ścieżkę względną do tworzonego folderu). I czy w ogóle tworzenie katalogu na dysku powinno być w handlerze komendy, czy może lepiej w jakimś handlerze eventu DirectoryCreated
?