Skip to content

Commit ac3aa29

Browse files
author
Stefan Gmeiner
committed
Allow set-content to overwrite existing names.
1 parent 1eb3e61 commit ac3aa29

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

Source/MongoDbGridFsProvider/ExtParameters.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,10 @@ public class MongoContentParameters
4545
[Parameter(Mandatory = false)]
4646
public string Name { get; set; }
4747
}
48+
49+
public class MongoContentWriterParameters : MongoContentParameters
50+
{
51+
[Parameter(Mandatory = false)]
52+
public SwitchParameter Overwrite { get; set; }
53+
}
4854
}

Source/MongoDbGridFsProvider/MongoProvider.cs

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -349,23 +349,48 @@ public object GetContentReaderDynamicParameters(string path)
349349

350350
public IContentWriter GetContentWriter(string id)
351351
{
352-
if (!(DynamicParameters is MongoContentParameters param))
352+
if (!(DynamicParameters is MongoContentWriterParameters param))
353353
{
354354
throw new ArgumentException("Expected dynamic parameter of type " + typeof(MongoContentParameters).FullName);
355355
}
356356

357357
id = RemovePathPrefix(id);
358358
if (!string.IsNullOrEmpty(id))
359359
{
360-
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException($"MongoDb does not support overwrite a gridfs-entry. Delete existing element first."), "FileAlreadyExist", ErrorCategory.InvalidArgument, null));
360+
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException($"Writing Content to an existing ID is not supported."), "FileAlreadyExist", ErrorCategory.InvalidArgument, null));
361+
}
362+
363+
if (!string.IsNullOrEmpty(param.Name))
364+
{
365+
// check if name already exists
366+
var result = Bucket.Find(Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, param.Name)).ToList();
367+
368+
if (result.Count > 0)
369+
{
370+
if (param.Overwrite.IsPresent)
371+
{
372+
if (result.Count == 1)
373+
{
374+
Bucket.Delete(result[0].Id);
375+
}
376+
else
377+
{
378+
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException($"More than one entry with the name {param.Name} exists and therefore cannot be overwritten."), "FileAlreadyExist", ErrorCategory.InvalidArgument, null));
379+
}
380+
}
381+
else
382+
{
383+
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException($"A file with the name {param.Name} already exists. Try -Overwrite."), "FileAreadyExist", ErrorCategory.InvalidArgument, null));
384+
}
385+
}
361386
}
362387

363388
return new MongoWriteContentProvider(Bucket, param.Name);
364389
}
365390

366391
public object GetContentWriterDynamicParameters(string path)
367392
{
368-
return new MongoContentParameters();
393+
return new MongoContentWriterParameters();
369394
}
370395

371396
public void ClearContent(string path)

0 commit comments

Comments
 (0)