Beispiel #1
0
        public async Task <ActionResult <ShortUrl> > ShortenUrlAsync([FromForm] string targetUrl, [FromForm] string name = null, [FromForm] bool generateName = false)
        {
            if (!Uri.TryCreate(targetUrl, UriKind.Absolute, out _))
            {
                return(UnprocessableEntity("Invalid url!"));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                name = GeneratorService.GenerateNextName();
            }
            else
            {
                bool nameUsed = await DbContext.ShortUrls.AnyAsync(x => x.Name == name);

                if (nameUsed)
                {
                    if (!generateName)
                    {
                        return(Conflict("this name is already being used"));
                    }

                    name = GeneratorService.GenerateNextName();
                }
            }

            var target = await DbContext.RedirectTargets.Where(x => x.TargetUrl == targetUrl).FirstOrDefaultAsync();

            if (target == null)
            {
                target = new RedirectTarget(targetUrl);
                DbContext.RedirectTargets.Add(target);
            }

            var userId   = Guid.Parse(User.FindFirstValue("UserId"));
            var shortUrl = new ShortUrl(userId, target.Id, name);

            DbContext.ShortUrls.Add(shortUrl);
            await DbContext.SaveChangesAsync();

            WebhookService.QueueShortUrl(shortUrl);

            return(Ok(shortUrl));
        }