Find the latest ID to set the new ID against instead of assuming count is good

This commit is contained in:
Robert Marshall 2020-07-15 18:32:38 +01:00
parent ec2a3e0bc5
commit f8e8774d8c
2 changed files with 17 additions and 2 deletions

View file

@ -4,6 +4,7 @@ using NSubstitute;
using Robware.Blog; using Robware.Blog;
using Robware.Blog.Data.State; using Robware.Blog.Data.State;
using System; using System;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
@ -11,8 +12,12 @@ namespace Robware.Data.Tests {
public class BlogRepositoryTests { public class BlogRepositoryTests {
[Fact] [Fact]
public async Task SavePost_WithNewPost_GetsNewIdAndSetsTimestampAndSavesAsync() { 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>>(); 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>(); var database = Substitute.For<IMongoDatabase>();
database.GetCollection<BlogPostState>("blog").Returns(collection); database.GetCollection<BlogPostState>("blog").Returns(collection);

View file

@ -67,9 +67,19 @@ namespace Robware.Data {
public async Task<BlogPost> GetPostByUrlAsync(string url) => await GetPostAsync(post => post.Url == url && !post.Deleted); 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) { public async Task<BlogPost> SavePost(BlogPost post) {
if (post.Id == 0) { if (post.Id == 0) {
post.Id = (await GetCountAsync(true)) + 1; post.Id = (await GetLastPostId()) + 1;
post.Timestamp = DateTime.Now; post.Timestamp = DateTime.Now;
} }