Exemplo n.º 1
0
        public async Task <IActionResult> CreateLink
        (
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "api/Shortener")] LinkItemCreationDto creationDto,
            HttpRequest req
        )
        {
            creationDto.Id        = !string.IsNullOrEmpty(creationDto.Id) ? creationDto.Id : RandomEx.RandomString(10);
            creationDto.AccessKey = !string.IsNullOrEmpty(creationDto.AccessKey) ? creationDto.AccessKey : RandomEx.RandomString(10);

            if (!string.IsNullOrEmpty(creationDto.Id))
            {
                var idExists = await _context.ShortenerContainer
                               .AsQueryable <LinkItem>()
                               .Where(x => x.Id == creationDto.Id)
                               .ToCosmosAsyncEnumerable()
                               .AnyAsync();

                if (idExists)
                {
                    return(new BadRequestObjectResult(new
                    {
                        Success = false,
                        Message = "Id already exists"
                    }));
                }
            }

            var itemResponse = await _context.ShortenerContainer.CreateItemAsync(_mapper.Map <LinkItem>(creationDto));

            var result = _mapper.Map <LinkItemAdminDto>(itemResponse.Resource)
                         .SetHost(req.GetHostPath());

            return(new ObjectResult(new
            {
                Success = true,
                Data = result
            }));
        }