Example #1
0
        public void SampleId_is_shortened(long aliasId)
        {
            var uss = new URLShortener();

            var result = uss.Encode(aliasId);

            Assert.Less(result.Length, aliasId.ToString().Length);
            Assert.IsInstanceOf <string>(result);
        }
Example #2
0
        public async Task <IActionResult> CreateURL([FromBody] CreateURLRequest request)
        {
            try
            {
                string normalizedLongUrl = URLNormalizer.Normalize(request.URL);

                if (!string.IsNullOrEmpty(request.CustomPath))
                {
                    if (!Uri.IsWellFormedUriString(request.CustomPath, UriKind.Relative))
                    {
                        return(BadRequest("Invalid custom URL"));
                    }
                    var custom = await Context.URLs.FindAsync(request.CustomPath);

                    if (custom != null || Reserved.Contains(request.CustomPath.ToLower()))
                    {
                        return(BadRequest("URL identifier already exists"));
                    }
                    else
                    {
                        var newCustomUrl = await AddURLToDatabase(request.CustomPath, normalizedLongUrl);

                        return(CreatedAtAction(nameof(CreateURL), newCustomUrl));
                    }
                }

                var existingUrl = await Context.URLs.FirstOrDefaultAsync(x => x.LongURL == normalizedLongUrl);

                if (existingUrl != null)
                {
                    return(Ok(existingUrl));
                }

                var    random = new Random();
                string shortUrlId;
                do
                {
                    var randomId = random.Next();
                    shortUrlId = URLShortener.Encode(randomId);
                } while (await Context.URLs.FindAsync(shortUrlId) != null);

                var newUrl = await AddURLToDatabase(shortUrlId, normalizedLongUrl);

                return(CreatedAtAction(nameof(CreateURL), newUrl));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }