/// <summary>
        /// You can use jwt.io to decode the token - it is the same one we'd use on dev, etc.
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        public async Task <HttpResponseMessage> CallApi(UpdatePersonRequestObject requestObject, Guid?id, int?ifMatch)
        {
            var token =
                "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMTUwMTgxMTYwOTIwOTg2NzYxMTMiLCJlbWFpbCI6ImUyZS10ZXN0aW5nQGRldmVsb3BtZW50LmNvbSIsImlzcyI6IkhhY2tuZXkiLCJuYW1lIjoiVGVzdGVyIiwiZ3JvdXBzIjpbImUyZS10ZXN0aW5nIl0sImlhdCI6MTYyMzA1ODIzMn0.SooWAr-NUZLwW8brgiGpi2jZdWjyZBwp4GJikn0PvEw";

            var idString = id.HasValue ? id.Value.ToString() : "dsfoidfjh";
            var uri      = new Uri($"api/v1/persons/{idString}", UriKind.Relative);

            var message = new HttpRequestMessage(HttpMethod.Patch, uri);

            var jsonSettings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting        = Formatting.Indented,
                ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                Converters        = new[] { new StringEnumConverter() }
            };
            var requestJson = JsonConvert.SerializeObject(requestObject, jsonSettings);

            message.Content = new StringContent(requestJson, Encoding.UTF8, "application/json");
            message.Method  = HttpMethod.Patch;
            message.Headers.Add("Authorization", token);
            message.Headers.TryAddWithoutValidation(HeaderConstants.IfMatch, $"\"{ifMatch?.ToString()}\"");

            _httpClient.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return(await _httpClient.SendAsync(message).ConfigureAwait(false));
        }
Esempio n. 2
0
        public async Task<IActionResult> UpdatePersonByIdAsync([FromBody] UpdatePersonRequestObject personRequestObject,
            [FromRoute] PersonQueryObject query)
        {
            // This is only possible because the EnableRequestBodyRewind middleware is specified in the application startup.
            var bodyText = await HttpContext.Request.GetRawBodyStringAsync().ConfigureAwait(false);
            var token = _tokenFactory.Create(_contextWrapper.GetContextRequestHeaders(HttpContext));

            var ifMatch = GetIfMatchFromHeader();

            try
            {
                // We use a request object AND the raw request body text because the incoming request will only contain the fields that changed
                // whereas the request object has all possible updateable fields defined.
                // The implementation will use the raw body text to identify which fields to update and the request object is specified here so that its
                // associated validation will be executed by the MVC pipeline before we even get to this point.
                var person = await _updatePersonUseCase.ExecuteAsync(personRequestObject, bodyText, token, query, ifMatch)
                                                       .ConfigureAwait(false);
                if (person == null) return NotFound(query.Id);

                return NoContent();
            }
            catch (VersionNumberConflictException vncErr)
            {
                return Conflict(vncErr.Message);
            }
        }
Esempio n. 3
0
        public void GivenAUpdatePersonRequest()
        {
            var personRequest = new UpdatePersonRequestObject()
            {
                FirstName   = "Update",
                Surname     = "Updating",
                Title       = Title.Dr,
                DateOfDeath = DateTime.UtcNow.AddYears(50)
            };

            UpdateSnsTopic();

            UpdatePersonRequest = personRequest;
        }
Esempio n. 4
0
        public async Task<PersonResponseObject> ExecuteAsync(UpdatePersonRequestObject personRequestObject, string requestBody,
            Token token, PersonQueryObject query, int? ifMatch)
        {
            var result = await _gateway.UpdatePersonByIdAsync(personRequestObject, requestBody, query, ifMatch).ConfigureAwait(false);
            if (result is null) return null;

            // Only raise the event if something actually changed.
            if (result.NewValues.Any())
            {
                var personSnsMessage = _snsFactory.Update(result, token);
                var topicArn = Environment.GetEnvironmentVariable("PERSON_SNS_ARN");
                await _snsGateway.Publish(personSnsMessage, topicArn).ConfigureAwait(false);
            }

            return _responseFactory.ToResponse(result.UpdatedEntity.ToDomain());
        }
        public void UpdatePersonByIdAsyncExceptionIsThrown(int?ifMatch)
        {
            // Arrange
            var personRequest = new UpdatePersonRequestObject();
            var token         = new Token();
            var query         = ConstructQuery(Guid.NewGuid());
            var exception     = new ApplicationException("Test exception");

            _mockGateway.Setup(x => x.UpdatePersonByIdAsync(personRequest, It.IsAny <string>(), query, ifMatch)).ThrowsAsync(exception);

            // Act
            Func <Task <PersonResponseObject> > func = async() =>
                                                       await _classUnderTest.ExecuteAsync(personRequest, "", token, query, ifMatch).ConfigureAwait(false);

            // Assert
            func.Should().Throw <ApplicationException>().WithMessage(exception.Message);
        }
Esempio n. 6
0
        public async Task <UpdateEntityResult <PersonDbEntity> > UpdatePersonByIdAsync(UpdatePersonRequestObject requestObject, string requestBody,
                                                                                       PersonQueryObject query, int?ifMatch)
        {
            var existingPerson = await _dynamoDbContext.LoadAsync <PersonDbEntity>(query.Id).ConfigureAwait(false);

            if (existingPerson == null)
            {
                return(null);
            }

            if (ifMatch != existingPerson.VersionNumber)
            {
                throw new VersionNumberConflictException(ifMatch, existingPerson.VersionNumber);
            }

            var result = _updater.UpdateEntity(existingPerson, requestBody, requestObject);

            if (result.NewValues.Any())
            {
                _logger.LogDebug($"Calling IDynamoDBContext.SaveAsync to update id {query.Id}");
                result.UpdatedEntity.LastModified = DateTime.UtcNow;
                await _dynamoDbContext.SaveAsync(result.UpdatedEntity).ConfigureAwait(false);
            }

            return(result);
        }
 public async Task WhenTheUpdatePersonApiIsCalled(UpdatePersonRequestObject personRequestObject, Guid?id, int?ifMatch)
 {
     _lastResponse = await CallApi(personRequestObject, id, ifMatch).ConfigureAwait(false);
 }
 public async Task WhenTheUpdatePersonApiIsCalled(UpdatePersonRequestObject personRequestObject, Guid?id)
 {
     await WhenTheUpdatePersonApiIsCalled(personRequestObject, id, 0).ConfigureAwait(false);
 }