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)); } }
public string ShouldCorrectlyNormalizeURL(string url) { return(URLNormalizer.Normalize(url)); }
public void ShouldFailOnInvalidURL(string url) { Action normalize = () => URLNormalizer.Normalize(url); normalize.Should().Throw <Exception>(); }