Skip to content

Commit

Permalink
feat(db): add postgres database
Browse files Browse the repository at this point in the history
  • Loading branch information
cyberhck authored Aug 29, 2019
1 parent 0ca79b7 commit 71bab46
Show file tree
Hide file tree
Showing 19 changed files with 306 additions and 36 deletions.
11 changes: 11 additions & 0 deletions Micro.Starter.Api/Configs/DatabaseConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Micro.Starter.Api.Configs
{
public class DatabaseConfig
{
public string Host { set; get; }
public int Port { set; get; }
public string Name { set; get; }
public string User { set; get; }
public string Password { set; get; }
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System;

namespace Micro.Starter.Api
namespace Micro.Starter.Api.Controllers
{
public class WeatherForecast
{
Expand All @@ -12,4 +12,4 @@ public class WeatherForecast

public string Summary { get; set; }
}
}
}
14 changes: 0 additions & 14 deletions Micro.Starter.Api/Dockerfile

This file was deleted.

23 changes: 21 additions & 2 deletions Micro.Starter.Api/HealthCheck/HealthCheckController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Micro.Starter.Api.Models;
using Micro.Starter.Api.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

Expand All @@ -9,6 +12,13 @@ namespace Micro.Starter.Api.HealthCheck
[Route("api/health")]
public class HealthCheckController : ControllerBase
{
private readonly IWeatherRepository _weather;

public HealthCheckController(IWeatherRepository weather)
{
_weather = weather;
}

[HttpGet]
[ProducesResponseType(typeof(IEnumerable<HealthData>), StatusCodes.Status200OK)]
public async Task<HealthData> Get()
Expand All @@ -20,9 +30,18 @@ public async Task<HealthData> Get()
};
}

private static Task<bool> GetFakeDbHealth()
private async Task<bool> GetFakeDbHealth()
{
return Task.Run(() => true);
try
{
await _weather.Create(new Weather());
return true;
}
catch (Exception)
{
// todo: log e
return false;
}
}

private static Task<bool> GetFakeCacheHealth()
Expand Down
3 changes: 3 additions & 0 deletions Micro.Starter.Api/Micro.Starter.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.0.0-preview8.19405.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0-preview8.19405.11" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.0.0-preview8" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="1.1.1" />
</ItemGroup>

</Project>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions Micro.Starter.Api/Migrations/20190828165715_InitialCreate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;

namespace Micro.Starter.Api.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Weathers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Temperature = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Weathers", x => x.Id);
});
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Weathers");
}
}
}
36 changes: 36 additions & 0 deletions Micro.Starter.Api/Migrations/ApplicationContextModelSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// <auto-generated />
using Micro.Starter.Api.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

namespace Micro.Starter.Api.Migrations
{
[DbContext(typeof(ApplicationContext))]
partial class ApplicationContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
.HasAnnotation("ProductVersion", "3.0.0-preview8.19405.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);

modelBuilder.Entity("Micro.Starter.Api.Models.Weather", b =>
{
b.Property<string>("Id")
.HasColumnType("text");

b.Property<double>("Temperature")
.HasColumnType("double precision");

b.HasKey("Id");

b.ToTable("Weathers");
});
#pragma warning restore 612, 618
}
}
}
41 changes: 41 additions & 0 deletions Micro.Starter.Api/Models/ApplicationContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using Micro.Starter.Api.Configs;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Npgsql;

namespace Micro.Starter.Api.Models
{
public class ApplicationContext : DbContext
{
private readonly DatabaseConfig _db;
public DbSet<Weather> Weathers { set; get; }

public ApplicationContext(DbContextOptions options, IOptions<DatabaseConfig> dbOption) : base(options)
{
_db = dbOption.Value;
}

protected ApplicationContext(IOptions<DatabaseConfig> dbOption)
{
_db = dbOption.Value;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connection = new NpgsqlConnectionStringBuilder
{
Host = _db.Host,
Port = _db.Port,
Database = _db.Name,
Username = _db.User,
Password = _db.Password,
SslMode = SslMode.Disable
};
optionsBuilder.UseNpgsql(connection.ConnectionString);
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
}
8 changes: 8 additions & 0 deletions Micro.Starter.Api/Models/Weather.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Micro.Starter.Api.Models
{
public class Weather
{
public string Id { set; get; }
public double Temperature { set; get; }
}
}
15 changes: 15 additions & 0 deletions Micro.Starter.Api/Repository/IWeatherRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Micro.Starter.Api.Models;

namespace Micro.Starter.Api.Repository
{
public interface IWeatherRepository
{
Task<IEnumerable<Weather>> GetAll();
Task<Weather> FindById(string id);
Task<Weather> Create([NotNull] Weather weather);
Task Delete(string id);
}
}
46 changes: 46 additions & 0 deletions Micro.Starter.Api/Repository/WeatherRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Micro.Starter.Api.Models;
using Micro.Starter.Api.Uuid;
using Microsoft.EntityFrameworkCore;

namespace Micro.Starter.Api.Repository
{
public class WeatherRepository : IWeatherRepository
{
private readonly ApplicationContext _db;
private readonly IUuidService _uuid;

public WeatherRepository(ApplicationContext db, IUuidService uuid)
{
_db = db;
_uuid = uuid;
}

public async Task<IEnumerable<Weather>> GetAll()
{
return (await _db.Weathers.ToListAsync()).AsEnumerable();
}

public Task<Weather> FindById(string id)
{
return _db.Weathers.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
}

public async Task<Weather> Create(Weather weather)
{
weather.Id = _uuid.GenerateUuId();
var result = await _db.Weathers.AddAsync(weather);
await _db.SaveChangesAsync();
return result.Entity;
}

public async Task Delete(string id)
{
var entities = _db.Weathers.Where(w => w.Id == id);
_db.Weathers.RemoveRange(entities);
await _db.SaveChangesAsync();
}
}
}
18 changes: 18 additions & 0 deletions Micro.Starter.Api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
using Micro.Starter.Api.Configs;
using Micro.Starter.Api.Models;
using Micro.Starter.Api.Repository;
using Micro.Starter.Api.Uuid;
using Micro.Starter.Api.Workers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
Expand All @@ -20,6 +24,8 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
AddConfiguration(services, Configuration);
ConfigureDependencies(services);
services.AddControllers();
services.AddApiVersioning(x =>
{
Expand All @@ -31,6 +37,18 @@ public void ConfigureServices(IServiceCollection services)
RegisterWorker(services);
}

private static void ConfigureDependencies(IServiceCollection services)
{
services.AddDbContext<ApplicationContext>();
services.AddScoped<IWeatherRepository, WeatherRepository>();
services.AddSingleton<IUuidService, UuidService>();
}

private static void AddConfiguration(IServiceCollection services, IConfiguration configuration)
{
services.Configure<DatabaseConfig>(configuration.GetSection("DatabaseConfig"));
}

private static void RegisterWorker(IServiceCollection services)
{
services.AddHostedService<Worker>();
Expand Down
7 changes: 7 additions & 0 deletions Micro.Starter.Api/Uuid/IUuidService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Micro.Starter.Api.Uuid
{
public interface IUuidService
{
string GenerateUuId();
}
}
10 changes: 10 additions & 0 deletions Micro.Starter.Api/Uuid/UuidService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Micro.Starter.Api.Uuid
{
public class UuidService : IUuidService
{
public string GenerateUuId()
{
return System.Guid.NewGuid().ToString();
}
}
}
Loading

0 comments on commit 71bab46

Please sign in to comment.