Skip to content

Commit

Permalink
Add API Test project; Add DI support
Browse files Browse the repository at this point in the history
  • Loading branch information
engineering87 committed Oct 28, 2024
1 parent 3dbd5d6 commit 43f2e40
Show file tree
Hide file tree
Showing 11 changed files with 279 additions and 5 deletions.
113 changes: 113 additions & 0 deletions src/SharpConnector.Api/Controllers/ConnectorController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// (c) 2020 Francesco Del Re <[email protected]>
// This code is licensed under MIT license (see LICENSE.txt for details)
using Microsoft.AspNetCore.Mvc;
using SharpConnector.Interfaces;

namespace SharpConnector.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class ConnectorController : ControllerBase
{
private readonly ISharpConnectorClient<string> _connectorClient;

private readonly ILogger<ConnectorController> _logger;

public ConnectorController(ILogger<ConnectorController> logger, ISharpConnectorClient<string> connectorClient)
{
_logger = logger;
_connectorClient = connectorClient;
}

[HttpGet("{key}", Name = "Get")]
public ActionResult<string> Get(string key)
{
var result = _connectorClient.Get(key);
return result != null ? Ok(result) : NotFound();
}

[HttpGet("async/{key}")]
public async Task<ActionResult<string>> GetAsync(string key)
{
var result = await _connectorClient.GetAsync(key);
return result != null ? Ok(result) : NotFound();
}

[HttpGet("all")]
public ActionResult<IEnumerable<string>> GetAll()
{
var results = _connectorClient.GetAll();
return Ok(results);
}

[HttpPost("insert")]
public ActionResult<bool> Insert(string key, [FromBody] string value)
{
var success = _connectorClient.Insert(key, value);
return success ? Ok(success) : BadRequest("Insert failed.");
}

[HttpPost("insert/with-expiration")]
public ActionResult<bool> Insert(string key, [FromBody] string value, TimeSpan expiration)
{
var success = _connectorClient.Insert(key, value, expiration);
return success ? Ok(success) : BadRequest("Insert with expiration failed.");
}

[HttpPost("insert-async")]
public async Task<ActionResult<bool>> InsertAsync(string key, [FromBody] string value)
{
var success = await _connectorClient.InsertAsync(key, value);
return success ? Ok(success) : BadRequest("Async insert failed.");
}

[HttpPost("insert-async/with-expiration")]
public async Task<ActionResult<bool>> InsertAsync(string key, [FromBody] string value, TimeSpan expiration)
{
var success = await _connectorClient.InsertAsync(key, value, expiration);
return success ? Ok(success) : BadRequest("Async insert with expiration failed.");
}

[HttpPost("insert-many")]
public ActionResult<bool> InsertMany([FromBody] Dictionary<string, string> values)
{
var success = _connectorClient.InsertMany(values);
return success ? Ok(success) : BadRequest("Insert many failed.");
}

[HttpPost("insert-many/with-expiration")]
public ActionResult<bool> InsertMany([FromBody] Dictionary<string, string> values, TimeSpan expiration)
{
var success = _connectorClient.InsertMany(values, expiration);
return success ? Ok(success) : BadRequest("Insert many with expiration failed.");
}

[HttpDelete("{key}")]
public ActionResult<bool> Delete(string key)
{
var success = _connectorClient.Delete(key);
return success ? Ok(success) : NotFound("Delete failed.");
}

[HttpDelete("async/{key}")]
public async Task<ActionResult<bool>> DeleteAsync(string key)
{
var success = await _connectorClient.DeleteAsync(key);
return success ? Ok(success) : NotFound("Async delete failed.");
}

[HttpPut("{key}")]
public ActionResult<bool> Update(string key, [FromBody] string value)
{
var success = _connectorClient.Update(key, value);
return success ? Ok(success) : NotFound("Update failed.");
}

[HttpPut("async/{key}")]
public async Task<ActionResult<bool>> UpdateAsync(string key, [FromBody] string value)
{
var success = await _connectorClient.UpdateAsync(key, value);
return success ? Ok(success) : NotFound("Async update failed.");
}
}
}
32 changes: 32 additions & 0 deletions src/SharpConnector.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// (c) 2020 Francesco Del Re <[email protected]>
// This code is licensed under MIT license (see LICENSE.txt for details)
using SharpConnector.Middleware;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Register the SharpConnector services with string payload type.
builder.Services.AddSharpConnectorServices<string>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
41 changes: 41 additions & 0 deletions src/SharpConnector.Api/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:44453",
"sslPort": 44308
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5124",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7158;http://localhost:5124",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
18 changes: 18 additions & 0 deletions src/SharpConnector.Api/SharpConnector.Api.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.9.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\SharpConnector\SharpConnector.csproj" />
</ItemGroup>

</Project>
6 changes: 6 additions & 0 deletions src/SharpConnector.Api/SharpConnector.Api.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@SharpConnector.Api_HostAddress = http://localhost:5124

GET {{SharpConnector.Api_HostAddress}}/weatherforecast/
Accept: application/json

###
8 changes: 8 additions & 0 deletions src/SharpConnector.Api/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
14 changes: 14 additions & 0 deletions src/SharpConnector.Api/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"ConnectorConfig": {
"Instance": "Redis",
"DatabaseNumber": 0,
"ConnectionString": "redis_connectionstring_here"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
31 changes: 31 additions & 0 deletions src/SharpConnector/Middleware/SharpConnectorServiceExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// (c) 2020 Francesco Del Re <[email protected]>
// This code is licensed under MIT license (see LICENSE.txt for details)
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SharpConnector.Interfaces;

namespace SharpConnector.Middleware
{
public static class SharpConnectorServiceExtensions
{
/// <summary>
/// Registers the SharpConnector services in the dependency injection container.
/// This allows for a generic SharpConnectorClient to be used with any specified type T.
/// </summary>
/// <typeparam name="T">The type parameter that specifies the type the client will handle.</typeparam>
/// <param name="services">The service collection to which the SharpConnector services will be added.</param>
/// <returns>The updated service collection with the SharpConnector services registered.</returns>
public static IServiceCollection AddSharpConnectorServices<T>(this IServiceCollection services)
{
services.AddControllers();

services.AddSingleton<ISharpConnectorClient<T>>(sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
return new SharpConnectorClient<T>(configuration);
});

return services;
}
}
}
2 changes: 1 addition & 1 deletion src/SharpConnector/SharpConnector.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="EnyimMemcachedCore" Version="3.2.3" />
<PackageReference Include="EnyimMemcachedCore" Version="3.2.4" />
<PackageReference Include="LiteDB" Version="5.0.21" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.2" />
Expand Down
14 changes: 10 additions & 4 deletions src/SharpConnector/SharpConnector.sln
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30621.155
# Visual Studio Version 17
VisualStudioVersion = 17.11.35327.3
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpConnector", "SharpConnector.csproj", "{04B2A952-D494-45B5-8819-EB0C38975CCD}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpConnector", "SharpConnector.csproj", "{04B2A952-D494-45B5-8819-EB0C38975CCD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpConnector.Test", "..\SharpConnector.Test\SharpConnector.Test.csproj", "{F5953500-0FA2-4520-8E52-AB7E67293F09}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpConnector.Test", "..\SharpConnector.Test\SharpConnector.Test.csproj", "{F5953500-0FA2-4520-8E52-AB7E67293F09}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpConnector.Api", "..\SharpConnector.Api\SharpConnector.Api.csproj", "{72A48B94-89D2-4F16-AE8C-E32B763EFA99}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -21,6 +23,10 @@ Global
{F5953500-0FA2-4520-8E52-AB7E67293F09}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F5953500-0FA2-4520-8E52-AB7E67293F09}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F5953500-0FA2-4520-8E52-AB7E67293F09}.Release|Any CPU.Build.0 = Release|Any CPU
{72A48B94-89D2-4F16-AE8C-E32B763EFA99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{72A48B94-89D2-4F16-AE8C-E32B763EFA99}.Debug|Any CPU.Build.0 = Debug|Any CPU
{72A48B94-89D2-4F16-AE8C-E32B763EFA99}.Release|Any CPU.ActiveCfg = Release|Any CPU
{72A48B94-89D2-4F16-AE8C-E32B763EFA99}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
5 changes: 5 additions & 0 deletions src/SharpConnector/SharpConnectorClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ public sealed class SharpConnectorClient<T> : ISharpConnectorClient<T>
{
private IOperations<T> _operations;

public SharpConnectorClient(IConfiguration configuration)
{
InitOperations(configuration);
}

/// <summary>
/// Create e new SharpConnectorClient instance.
/// </summary>
Expand Down

0 comments on commit 43f2e40

Please sign in to comment.