Skip to content

Commit

Permalink
add error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
NielsPilgaard committed Aug 30, 2024
1 parent 8b0ca9d commit e12efcc
Showing 1 changed file with 29 additions and 15 deletions.
44 changes: 29 additions & 15 deletions src/web/Jordnaer/Features/PostSearch/PostSearchService.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
using Jordnaer.Database;
using Jordnaer.Features.Metrics;
using Jordnaer.Features.Search;
using Jordnaer.Models;
using Jordnaer.Shared;
using Microsoft.EntityFrameworkCore;
using OneOf;
using OneOf.Types;

namespace Jordnaer.Features.PostSearch;

public interface IPostSearchService
{
Task<PostSearchResult> GetPostsAsync(PostSearchFilter filter,
Task<OneOf<PostSearchResult, Error<string>>> GetPostsAsync(PostSearchFilter filter,
CancellationToken cancellationToken = default);
}

public class PostSearchService(
IDbContextFactory<JordnaerDbContext> contextFactory,
IZipCodeService zipCodeService) : IPostSearchService
IZipCodeService zipCodeService,
ILogger<PostSearchService> logger) : IPostSearchService
{
public async Task<PostSearchResult> GetPostsAsync(PostSearchFilter filter,
public async Task<OneOf<PostSearchResult, Error<string>>> GetPostsAsync(PostSearchFilter filter,
CancellationToken cancellationToken = default)
{
JordnaerMetrics.PostSearchesCounter.Add(1, MakeTagList(filter));
Expand All @@ -35,19 +39,29 @@ public async Task<PostSearchResult> GetPostsAsync(PostSearchFilter filter,
? 0
: (filter.PageNumber - 1) * filter.PageSize;

var posts = await query.OrderByDescending(x => x.CreatedUtc)
.Skip(postsToSkip)
.Take(filter.PageSize)
.Select(x => x.ToPostDto())
.ToListAsync(cancellationToken);

var totalCount = await query.CountAsync(cancellationToken);

return new PostSearchResult
try
{
Posts = posts,
TotalCount = totalCount
};
var posts = await query.OrderByDescending(x => x.CreatedUtc)
.Skip(postsToSkip)
.Take(filter.PageSize)
.Select(x => x.ToPostDto())
.ToListAsync(cancellationToken);

var totalCount = await query.CountAsync(cancellationToken);

return new PostSearchResult
{
Posts = posts,
TotalCount = totalCount
};
}
catch (Exception exception)
{
logger.LogError(exception, "Exception occurred during post search. " +
"Query: {Query}", query.ToQueryString());
}

return new Error<string>(ErrorMessages.Something_Went_Wrong_Try_Again);
}

internal async Task<IQueryable<Post>> ApplyLocationFilterAsync(
Expand Down

0 comments on commit e12efcc

Please sign in to comment.