Find the latest ID to set the new ID against instead of assuming count is good
This commit is contained in:
parent
ec2a3e0bc5
commit
f8e8774d8c
2 changed files with 17 additions and 2 deletions
|
@ -4,6 +4,7 @@ using NSubstitute;
|
|||
using Robware.Blog;
|
||||
using Robware.Blog.Data.State;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
|
||||
|
@ -11,8 +12,12 @@ namespace Robware.Data.Tests {
|
|||
public class BlogRepositoryTests {
|
||||
[Fact]
|
||||
public async Task SavePost_WithNewPost_GetsNewIdAndSetsTimestampAndSavesAsync() {
|
||||
var findResult = Substitute.For<IAsyncCursor<BlogPostState>>();
|
||||
findResult.Current.Returns(new[] { new BlogPostState { Id = 10 } });
|
||||
findResult.MoveNext(Arg.Any<CancellationToken>()).Returns(true, false);
|
||||
findResult.MoveNextAsync(Arg.Any<CancellationToken>()).Returns(true, false);
|
||||
var collection = Substitute.For<IMongoCollection<BlogPostState>>();
|
||||
collection.CountDocumentsAsync(Arg.Any<FilterDefinition<BlogPostState>>()).Returns(10);
|
||||
collection.FindAsync(Arg.Any<FilterDefinition<BlogPostState>>(), Arg.Any<FindOptions<BlogPostState>>()).Returns(findResult);
|
||||
var database = Substitute.For<IMongoDatabase>();
|
||||
database.GetCollection<BlogPostState>("blog").Returns(collection);
|
||||
|
||||
|
|
|
@ -67,9 +67,19 @@ namespace Robware.Data {
|
|||
|
||||
public async Task<BlogPost> GetPostByUrlAsync(string url) => await GetPostAsync(post => post.Url == url && !post.Deleted);
|
||||
|
||||
private async Task<int> GetLastPostId() {
|
||||
var sort = Builders<BlogPostState>.Sort.Descending(post => post.Id);
|
||||
var options = new FindOptions<BlogPostState> {
|
||||
Sort = sort,
|
||||
Limit = 1
|
||||
};
|
||||
var states = (await _collection.FindAsync<BlogPostState>(_ => true, options)).ToEnumerable();
|
||||
return states.First().Id;
|
||||
}
|
||||
|
||||
public async Task<BlogPost> SavePost(BlogPost post) {
|
||||
if (post.Id == 0) {
|
||||
post.Id = (await GetCountAsync(true)) + 1;
|
||||
post.Id = (await GetLastPostId()) + 1;
|
||||
post.Timestamp = DateTime.Now;
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue