Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added sample Swagger Doc functionality for Gateway API with unit tests #4

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/src/TaskTracker.Api/bin/Debug/netcoreapp2.0/TaskTracker.Api.dll",
"args": [],
"cwd": "${workspaceFolder}/src/TaskTracker.Api",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"launchBrowser": {
"enabled": true,
"args": "${auto-detect-url}",
"windows": {
"command": "cmd.exe",
"args": "/C start ${auto-detect-url}"
},
"osx": {
"command": "open"
},
"linux": {
"command": "xdg-open"
}
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
,]
}
15 changes: 15 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/src/TaskTracker.Api/TaskTracker.Api.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
76 changes: 60 additions & 16 deletions src/TaskTracker.Api/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,86 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TaskTracker.Api.Models;

namespace TaskTracker.Api.Controllers
{
[Route("api/[controller]")]
///<summary>
/// Performs CRUD operations related to microservices
///</summary>
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
private readonly IMicroserviceRepository _provider;

///<summary>
///Constructor
///</summary>
public ValuesController(IMicroserviceRepository provider)
{
return new string[] { "value1", "value2" };
_provider = provider;
}

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
///<summary>
/// Gets all the associated microservices
///</summary>
/// <response code="200">If service exists</response>
[HttpGet]
public IActionResult GetMicroServices()
{
return "value";
var services = _provider.GetMicroservices();
return Ok(services);
}

// POST api/values
[HttpPost]
public void Post([FromBody]string value)
// GET api/values/5
///<summary>
/// Gets the microservice with a particular id
///</summary>
///<param name="id"></param>
/// <response code="200">If service exists</response>
/// <response code="404">If the service does not exist</response>
[HttpGet("{id}",Name = "GetService")]
public IActionResult GetMicroserviceById(int id)
{
var service = _provider.GetMicroserviceById(id);
if(service == null) return NotFound();
return Ok(service);
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
// POST api/values
///<summary>
///Creates a new Microservice
///</summary>
///<param name="data"></param>
/// <response code="201">If service gets created</response>
/// <response code="400">If the request is not valid</response>
/// <returns>A newly created Microservice</returns>
[HttpPost]
public IActionResult Post([FromBody]Microservice data)
{
if(data == null) return BadRequest("Pass some service data");
if(data.Name == null) return BadRequest("Pass the name property");
int id = _provider.CreateMicroservice(data);
return CreatedAtRoute("GetService",new {Id= id },data);
}

// DELETE api/values/5
///<summary>
///Deletes a Microservice
///</summary>
///<param name="id"></param>
/// <response code="204">If service gets deleted</response>
/// <response code="404">If the service is not found</response>
[HttpDelete("{id}")]
public void Delete(int id)
public IActionResult Delete(int id)
{
var result = _provider.DeleteMicroService(id);
if(result == "Not Found"){
return NotFound();
}
else{
return NoContent();
}
}
}
}
14 changes: 14 additions & 0 deletions src/TaskTracker.Api/Models/AppDBContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Microsoft.EntityFrameworkCore;

namespace TaskTracker.Api.Models
{
public class AppDBContext:DbContext
{
public AppDBContext(DbContextOptions options):base(options)
{

}

public DbSet<Microservice> Microservices{get;set;}
}
}
57 changes: 57 additions & 0 deletions src/TaskTracker.Api/Models/BaseRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace TaskTracker.Api.Models
{
public interface IMicroserviceRepository
{
IEnumerable<Microservice> GetMicroservices();
object GetMicroserviceById(int id);

int CreateMicroservice(Microservice data);

string DeleteMicroService(int id);
}

public class MicroserviceRepository:IMicroserviceRepository
{
private readonly AppDBContext _context;

public MicroserviceRepository(AppDBContext context)
{
_context = context;
if(_context.Microservices.Count() == 0){
_context.Microservices.Add(new Microservice {Name = "Identity"});
_context.SaveChangesAsync();
}
}
public IEnumerable<Microservice> GetMicroservices()
{
var services = _context.Microservices.ToList();
return services;
}

public object GetMicroserviceById(int id)
{
var service = _context.Microservices.SingleOrDefault(x => x.Id == id);
return service;
}

public int CreateMicroservice(Microservice service)
{
_context.Microservices.Add(service);
_context.SaveChangesAsync();
return service.Id;
}

public string DeleteMicroService(int id)
{
var service = _context.Microservices.SingleOrDefault(x => x.Id == id);
if(service == null) return "Not Found";
_context.Microservices.Remove(service);
_context.SaveChangesAsync();
return "Deleted";
}
}
}
13 changes: 13 additions & 0 deletions src/TaskTracker.Api/Models/Microservice.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace TaskTracker.Api.Models
{
public class Microservice
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
}
1 change: 1 addition & 0 deletions src/TaskTracker.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public static void Main(string[] args)
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:2000")
.Build();
}
}
69 changes: 57 additions & 12 deletions src/TaskTracker.Api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TaskTracker.Api.Models;
using Microsoft.EntityFrameworkCore;
using System.IO;
using Microsoft.AspNetCore.Http;
using Ocelot.DependencyInjection;
using CacheManager.Core;
using Ocelot.Middleware;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System;

namespace TaskTracker.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
public Startup(IHostingEnvironment env)
{
Configuration = configuration;
var builder = new ConfigurationBuilder();
builder.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
//add configuration.json
.AddJsonFile("configuration.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();

Configuration = builder.Build();
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<AppDBContext>(db =>
db.UseInMemoryDatabase("MicroserviceDB"));
services.AddScoped<IMicroserviceRepository,MicroserviceRepository>();
services.AddMvc();
var audienceConfig = Configuration.GetSection("Audience");

var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audienceConfig["Key"]));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = audienceConfig["Issuer"],
ValidateAudience = true,
ValidAudience = audienceConfig["Aud"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};

services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = "TestKey";
})
.AddJwtBearer("TestKey", x =>
{
x.RequireHttpsMetadata = false;
x.TokenValidationParameters = tokenValidationParameters;
});

services.AddOcelot(Configuration);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseMvc();
app.UseAuthentication();

await app.UseOcelot();

}
}
}
Loading