Skip to content

Commit

Permalink
Update to match blog post
Browse files Browse the repository at this point in the history
  • Loading branch information
Swimburger committed Sep 27, 2022
1 parent 81e07b4 commit 4c51348
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 36 deletions.
47 changes: 25 additions & 22 deletions UrlShortener.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
using StackExchange.Redis;
using UrlShortener.Data;

#region Options

var destinationOption = new Option<string>(
new[] {"--destination-url", "-d"},
description: "The URL that the shortened URL will forward to."
Expand Down Expand Up @@ -43,22 +41,18 @@
connectionStringOption.IsRequired = true;
}

#endregion

var rootCommand = new RootCommand("Manage the shortened URLs.");

async Task<ConnectionMultiplexer> GetRedisConnection(string? connectionString)
{
var redisConnection = await ConnectionMultiplexer.ConnectAsync(
connectionString ??
envConnectionString ??
throw new Exception("Missing connection string")
throw new Exception("Missing connection string.")
);
return redisConnection;
}

#region Create Command

var createCommand = new Command("create", "Create a shortened URL")
{
destinationOption,
Expand All @@ -72,7 +66,7 @@ async Task<ConnectionMultiplexer> GetRedisConnection(string? connectionString)
try
{
await shortUrlRepository.Create(new ShortUrl(destination, path));
Console.WriteLine($"Shortened URL created.");
Console.WriteLine("Shortened URL created.");
}
catch (Exception e)
{
Expand All @@ -82,9 +76,28 @@ async Task<ConnectionMultiplexer> GetRedisConnection(string? connectionString)

rootCommand.AddCommand(createCommand);

#endregion
var updateCommand = new Command("update", "Update a shortened URL")
{
destinationOption,
pathOption,
connectionStringOption
};

updateCommand.SetHandler(async (destination, path, connectionString) =>
{
var shortUrlRepository = new ShortUrlRepository(await GetRedisConnection(connectionString));
try
{
await shortUrlRepository.Update(new ShortUrl(destination, path));
Console.WriteLine("Shortened URL updated.");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
}
}, destinationOption, pathOption, connectionStringOption);

#region Delete Command
rootCommand.AddCommand(updateCommand);

var deleteCommand = new Command("delete", "Delete a shortened URL")
{
Expand All @@ -98,7 +111,7 @@ async Task<ConnectionMultiplexer> GetRedisConnection(string? connectionString)
try
{
await shortUrlRepository.Delete(path);
Console.WriteLine($"Shortened URL deleted.");
Console.WriteLine("Shortened URL deleted.");
}
catch (Exception e)
{
Expand All @@ -108,10 +121,6 @@ async Task<ConnectionMultiplexer> GetRedisConnection(string? connectionString)

rootCommand.AddCommand(deleteCommand);

#endregion

#region Get Command

var getCommand = new Command("get", "Get a shortened URL")
{
pathOption,
Expand All @@ -123,7 +132,7 @@ async Task<ConnectionMultiplexer> GetRedisConnection(string? connectionString)
var shortUrlRepository = new ShortUrlRepository(await GetRedisConnection(connectionString));
try
{
var shortUrl = await shortUrlRepository.GetByPath(path);
var shortUrl = await shortUrlRepository.Get(path);
if (shortUrl == null)
Console.Error.WriteLine($"Shortened URL for path '{path}' not found.");
else
Expand All @@ -137,10 +146,6 @@ async Task<ConnectionMultiplexer> GetRedisConnection(string? connectionString)

rootCommand.AddCommand(getCommand);

#endregion

#region List Command

var listCommand = new Command("list", "List shortened URLs")
{
connectionStringOption
Expand All @@ -165,6 +170,4 @@ async Task<ConnectionMultiplexer> GetRedisConnection(string? connectionString)

rootCommand.AddCommand(listCommand);

#endregion

return rootCommand.InvokeAsync(args).Result;
2 changes: 1 addition & 1 deletion UrlShortener.Data/ShortUrl.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
namespace UrlShortener.Data;

public record ShortUrl(string? Destination, string? Path);
public sealed record ShortUrl(string? Destination, string? Path);
17 changes: 12 additions & 5 deletions UrlShortener.Data/ShortUrlRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

using StackExchange.Redis;

public class ShortUrlRepository
public sealed class ShortUrlRepository
{
private readonly ConnectionMultiplexer redisConnection;
private readonly IDatabase redisDatabase;
Expand All @@ -23,6 +23,16 @@ public async Task Create(ShortUrl shortUrl)
throw new Exception($"Failed to create shortened URL.");
}

public async Task Update(ShortUrl shortUrl)
{
if (await Exists(shortUrl.Path) == false)
throw new Exception($"Shortened URL with path '{shortUrl.Path}' does not exist.");

var urlWasSet = await redisDatabase.StringSetAsync(shortUrl.Path, shortUrl.Destination);
if (!urlWasSet)
throw new Exception($"Failed to update shortened URL.");
}

public async Task Delete(string path)
{
if (await Exists(path) == false)
Expand All @@ -33,11 +43,8 @@ public async Task Delete(string path)
throw new Exception("Failed to delete shortened URL.");
}

public async Task<ShortUrl?> GetByPath(string path)
public async Task<ShortUrl?> Get(string path)
{
if (await Exists(path) == false)
throw new Exception($"Shortened URL with path '{path}' does not exist.");

var redisValue = await redisDatabase.StringGetAsync(path);
if (redisValue.IsNullOrEmpty)
return null;
Expand Down
4 changes: 2 additions & 2 deletions UrlShortener.Data/ShortUrlValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace UrlShortener.Data;
public static class ShortUrlValidator
{
private static readonly Regex PathRegex = new Regex(
"^[a-zA-Z0-9_]*$",
"^[a-zA-Z0-9_-]*$",
RegexOptions.None,
TimeSpan.FromMilliseconds(1)
);
Expand Down Expand Up @@ -71,7 +71,7 @@ public static bool ValidatePath(string? path, out string[] validationResults)
validationResultsList.Add("Path cannot be longer than 10 characters.");

if (!PathRegex.IsMatch(path))
validationResultsList.Add("Path can only contain alphanumeric characters and underscores.");
validationResultsList.Add("Path can only contain alphanumeric characters, underscores, and dashes.");

validationResults = validationResultsList.ToArray();
return validationResultsList.Count > 0;
Expand Down
6 changes: 3 additions & 3 deletions UrlShortener.Forwarder/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("UrlsDb")
?? throw new Exception("Missing 'UrlsDb' connection string");
var connectionString = builder.Configuration.GetConnectionString("ShortenedUrlsDb")
?? throw new Exception("Missing 'ShortenedUrlsDb' connection string");
var redisConnection = await ConnectionMultiplexer.ConnectAsync(connectionString);
builder.Services.AddSingleton(redisConnection);
builder.Services.AddTransient<ShortUrlRepository>();
Expand All @@ -19,7 +19,7 @@ ShortUrlRepository shortUrlRepository
if(ShortUrlValidator.ValidatePath(path, out _))
return Results.BadRequest();

var shortUrl = await shortUrlRepository.GetByPath(path);
var shortUrl = await shortUrlRepository.Get(path);
if (shortUrl == null || string.IsNullOrEmpty(shortUrl.Destination))
return Results.NotFound();

Expand Down
3 changes: 2 additions & 1 deletion UrlShortener.Forwarder/UrlShortener.Forwarder.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>7662012d-f58c-4d03-9218-e470bde971a6</UserSecretsId>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion UrlShortener.Forwarder/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
}
},
"ConnectionStrings": {
"UrlsDb": "localhost"
"ShortenedUrlsDb": "localhost"
}
}
2 changes: 1 addition & 1 deletion UrlShortener.Forwarder/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
},
"AllowedHosts": "*",
"ConnectionStrings": {
"UrlsDb": "[USE_SECRETS_OR_ENV_OR_VAULT]"
"ShortenedUrlsDb": "[USE_SECRETS_OR_ENV_OR_VAULT]"
}
}

0 comments on commit 4c51348

Please sign in to comment.