Created
October 9, 2021 22:22
-
-
Save ankitvijay/67bc9f5e10c69de0b3ea4203b21d1805 to your computer and use it in GitHub Desktop.
NServiceBus Cosmos Sample - AddCommentHandler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class AddCommentHandler : IHandleMessages<AddComment> | |
| { | |
| public async Task Handle(AddComment message, IMessageHandlerContext context) | |
| { | |
| var cosmosSession = context.SynchronizedStorageSession.CosmosPersistenceSession(); | |
| var postResource = await cosmosSession.Container.ReadItemAsync<Post>(message.PostId, | |
| new PartitionKey(message.PostId)); | |
| if (postResource == null) | |
| { | |
| throw new Exception( | |
| $"Post {message.PostId} does not exist. Cannot add comment for the post that does not exist"); | |
| } | |
| postResource.Resource.LastUpdatedDate = DateTime.UtcNow; | |
| cosmosSession.Batch.UpsertItem(postResource.Resource, new TransactionalBatchItemRequestOptions | |
| { | |
| IfMatchEtag = postResource.ETag | |
| }); | |
| var comment = new Comment(message.PostId, message.CommentId, message.Content, | |
| message.CommentBy); | |
| cosmosSession.Batch.CreateItem(comment); | |
| await context.Publish(new CommentAdded | |
| { | |
| PostId = message.PostId, | |
| CommentId = comment.Id, | |
| Content = comment.Content, | |
| CommentBy = comment.CommentedBy, | |
| CreatedDate = comment.CreatedDate | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment