Example #1
0
        public async Task UpdatePostAsync(string id, PostUpdateInfo updateInfo, CancellationToken token)
        {
            var updates = new List <UpdateDefinition <Post> >();

            if (updateInfo.Title != null)
            {
                updates.Add(Builders <Post> .Update.Set(p => p.Title, updateInfo.Title));
            }

            if (updateInfo.Text != null)
            {
                updates.Add(Builders <Post> .Update.Set(p => p.Text, updateInfo.Text));
            }

            if (updateInfo.Tags != null)
            {
                updates.Add(Builders <Post> .Update.Set(p => p.Tags, updateInfo.Tags));
            }

            var update = Builders <Post> .Update.Combine(updates);

            var updateResult = await this.postsCollection
                               .UpdateOneAsync(it => it.Id == id, update, cancellationToken : token)
                               .ConfigureAwait(false);

            if (updateResult.ModifiedCount == 0)
            {
                throw new PostNotFoundException(id);
            }
        }
        public async Task <ActionResult> UpdateAsync(
            string id,
            [FromBody] PostUpdateInfo updateInfo,
            CancellationToken token)
        {
            try
            {
                await this.postsService.UpdatePostAsync(id, updateInfo, token).ConfigureAwait(false);

                return(this.NoContent());
            }
            catch (ValidationException ex)
            {
                return(this.BadRequest(ex.ValidationResult));
            }
            catch (PostNotFoundException)
            {
                return(this.NotFound());
            }
        }