Skip to content

Commit

Permalink
refactor: update repository base
Browse files Browse the repository at this point in the history
- use the new driver api syntax
  • Loading branch information
Sipho Hlophe committed Aug 29, 2020
1 parent 3c80fbc commit 846d904
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 48 deletions.
5 changes: 3 additions & 2 deletions DataAccess/Interfaces/IRepository.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
using Neo4j.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace DataAccess.Interfaces
{
public interface IRepository : IDisposable
{
Task<T> Read<T>(string query, object parameters);
Task<T> Read<T>(string query, IDictionary<string, object> parameters);

Task<T> Write<T>(string query, object parameters);

IAsyncSession GetSession(AccessMode mode);
Task CreateIndicesAsync(string[] labels);
Task<System.Collections.Generic.IList<IRecord>> Read(string query, System.Collections.Generic.IDictionary<string, object> parameters);
Task<IList<IRecord>> Read(string query, IDictionary<string, object> parameters);
}
}
17 changes: 8 additions & 9 deletions DataAccess/Person/PersonRepository.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using DataAccess.Interfaces;
using DataAccess.Serializer.Converters;
using Neo4j.Driver;
using Newtonsoft.Json;
using System.Collections.Generic;
Expand All @@ -23,7 +22,7 @@ public PersonRepository(IRepository repository)

public async Task<Person> Add(Person person)
{
var entity = await _repository.Write<Person>(_mutations["UPDATE_PERSON"].Trim(), person);
var entity = await _repository.Write<Person>(_mutations["UPDATE_PERSON"].Trim(), new Dictionary<string, object> { { "person", person } });
return entity;
}

Expand Down Expand Up @@ -55,19 +54,19 @@ public async Task<IEnumerable<Person>> All()

public async Task<string> Delete(string id)
{
var entity = await _repository.Write<Person>(_mutations["DEACTIVATE_PERSON"].Trim(), new { id });
var entity = await _repository.Write<Person>(_mutations["DEACTIVATE_PERSON"].Trim(), new Dictionary<string, object> { { "id", id } });
return entity.Id;
}

public async Task<Person> Get(string id)
{
var entity = await _repository.Read<Person>(_queries["GET_PERSON"].Trim(), new { id });
var entity = await _repository.Read<Person>(_queries["GET_PERSON"].Trim(), new Dictionary<string, object> { { "id", id } });
return entity;
}

public async Task<Person> Update(Person person)
{
var entity = await _repository.Write<Person>(_mutations["UPDATE_PERSON_2"].Trim(), person);
var entity = await _repository.Write<Person>(_mutations["UPDATE_PERSON_2"].Trim(), new Dictionary<string, object> { { "person", person } });
return entity;
}

Expand All @@ -76,16 +75,16 @@ private Person ProcessProps(IRecord record, string label)
var props = JsonConvert.SerializeObject(record[label]);
var person = JsonConvert.DeserializeObject<Person>(props);

if(person.Manager == null)
if (person.Manager == null)
{
var managerProps = ((Dictionary<string, object>)record.Values.Values.First()).FirstOrDefault(v => v.Key == "manager");
person.Manager = managerProps.Value != null ? JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(managerProps.Value.As<INode>().Properties)) : null;
}

if(person.Line == null)
if (person.Line == null)
{
var lineProps = ((Dictionary<string, object>)record.Values.Values.First()).FirstOrDefault(v => v.Key == "line");
if(lineProps.Value != null && ((List<object>)lineProps.Value).Any())
if (lineProps.Value != null && ((List<object>)lineProps.Value).Any())
{
var lines = ((List<object>)lineProps.Value)
.Select(l => JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(l.As<INode>().Properties)));
Expand All @@ -95,7 +94,7 @@ private Person ProcessProps(IRecord record, string label)
person.Line = new List<Person>();
}

if(person.Team == null)
if (person.Team == null)
{
var teamProps = ((Dictionary<string, object>)record.Values.Values.First()).FirstOrDefault(v => v.Key == "team");
if (teamProps.Value != null && ((List<object>)teamProps.Value).Any())
Expand Down
98 changes: 75 additions & 23 deletions DataAccess/Repository.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using DataAccess.Interfaces;
using Models.DTOs.Configuration;
using Neo4j.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
Expand All @@ -10,10 +11,18 @@ namespace DataAccess
public class Repository : IRepository
{
private readonly IDriver _driver;
private readonly string _databaseName;

public Repository(Connection connection)
{
_driver = GraphDatabase.Driver(connection.BoltURL, AuthTokens.Basic(connection.Username, connection.Password));
_driver = GraphDatabase.Driver(
connection.BoltURL,
AuthTokens.Basic(connection.Username, connection.Password),
o =>
{
o.WithEncryptionLevel(EncryptionLevel.None);
});
_databaseName = connection.DatabaseName;
}

public void Dispose()
Expand All @@ -23,39 +32,25 @@ public void Dispose()

public IAsyncSession GetSession(AccessMode mode)
{
return _driver.AsyncSession();
return _driver.AsyncSession(o => o.WithDatabase(_databaseName));
}

public async Task<T> Read<T>(string query, object parameters)
public async Task<T> Read<T>(string query, IDictionary<string, object> parameters)
{
var session = GetSession(AccessMode.Read);
var trx = await session.ReadTransactionAsync(async tx =>
{
var response = await tx.RunAsync(query, parameters);
return response.ToListAsync().As<T>();
});
await session.CloseAsync();
return trx;
var x = await ProcessTransactionAsync(GetSession(AccessMode.Read), query, parameters);
return x.As<T>();
}

public async Task<IList<IRecord>> Read(string query, IDictionary<string, object> parameters)
{
var session = GetSession(AccessMode.Read);
var s = await session.RunAsync(query, parameters);
await session.CloseAsync();
return await s.ToListAsync();
var records = await ProcessAsync(GetSession(AccessMode.Read), query, parameters);
return records;
}

public async Task<T> Write<T>(string query, object parameters)
{
var session = GetSession(AccessMode.Write);
var trx = await session.WriteTransactionAsync(async tx =>
{
var response = await tx.RunAsync(query, parameters);
return response.ToListAsync().As<T>();
});
await session.CloseAsync();
return trx;
var x = await ProcessWriteTransactionAsync<T>(GetSession(AccessMode.Write), query, parameters);
return x.As<T>();
}

public async Task CreateIndicesAsync(string[] labels)
Expand All @@ -72,5 +67,62 @@ public async Task CreateIndicesAsync(string[] labels)
await session.CloseAsync();
}
}

private async Task<List<IRecord>> ProcessAsync(IAsyncSession session, string query, IDictionary<string, object> parameters)
{
try
{
IResultCursor cursor = await session.RunAsync(query, parameters);
return await cursor.ToListAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
await session.CloseAsync();
await _driver.CloseAsync();
}
}

private async Task<List<IRecord>> ProcessTransactionAsync(IAsyncSession session, string query, IDictionary<string, object> parameters)
{
try
{
var trx = await session.ReadTransactionAsync(tx => tx.RunAsync(query, parameters));
return await trx.ToListAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
await session.CloseAsync();
await _driver.CloseAsync();
}
}

private async Task<List<IRecord>> ProcessWriteTransactionAsync<T>(IAsyncSession session, string query, object parameters)
{
try
{
var trx = await session.WriteTransactionAsync(tx => tx.RunAsync(query, parameters));
return await trx.ToListAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
await session.CloseAsync();
await _driver.CloseAsync();
}
}
}
}
4 changes: 1 addition & 3 deletions IoC/RegisterFrameworks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
using GraphQLCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
//using Microsoft.Extensions.en;
using Models.DTOs.Configuration;
using System.Text.Json;

namespace IoC
{
Expand Down Expand Up @@ -46,7 +44,7 @@ public static void ConfigureFrameworks(this IServiceCollection services, IConfig
o.ExposeExceptions = true;
})
//.AddSystemTextJson()
.AddUserContextBuilder(hc => new GraphQLUserContext {User = hc.User})
.AddUserContextBuilder(hc => new GraphQLUserContext { User = hc.User })
.AddGraphTypes(ServiceLifetime.Scoped);
}
}
Expand Down
8 changes: 2 additions & 6 deletions IoC/RegisterGraphQLHandlers.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
using GraphQLCore;
using GraphQLCore.GraphQLTypes.Building;
using GraphQLCore.GraphQLTypes.Building;
using GraphQLCore.GraphQLTypes.Person;
using GraphQLCore.GraphQLTypes.Product;
using GraphQLCore.GraphQLTypes.Search;
using GraphQLCore.Unions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Models.Types;
using GraphQLSettings = GraphQLCore.GraphQLSettings;
using GraphQLUserContext = GraphQLCore.GraphQLUserContext;

namespace IoC
{
Expand Down Expand Up @@ -47,6 +43,6 @@ public static void ConfigureGraphQLServices(this IServiceCollection services)
services.AddSingleton<CompositeQueries>();
services.AddSingleton<CompositeMutators>();
}

}
}
5 changes: 1 addition & 4 deletions IoC/RegisterRepositories.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using DataAccess;
using DataAccess.Building;
using DataAccess.Building;
using DataAccess.CacheProvider;
using DataAccess.Interfaces;
using DataAccess.Person;
using DataAccess.Product;
using DataAccess.Search;
Expand All @@ -14,7 +12,6 @@ internal static class RegisterRepositories
public static void ConfigureRepositories(this IServiceCollection services)
{
services.AddSingleton<ICacheProvider, InMemoryCache>();
//services.AddTransient<IRepository, Repository>();
services.AddTransient<IPersonRepository, PersonRepository>();
services.AddTransient<IBuildingRepository, BuildingRepository>();
services.AddTransient<IProductRepository, ProductRepository>();
Expand Down
1 change: 1 addition & 0 deletions Models/Configuration/Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ public class Connection
public string BoltURL { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string DatabaseName { get; set; }
}
}
3 changes: 2 additions & 1 deletion net-core-graphql/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"ConnectionStrings": {
"BoltURL": "bolt://localhost:7687",
"Username": "neo4j",
"Password": "n4j"
"Password": "n4j",
"databaseName": "neo4j"
},
"Logging": {
"LogLevel": {
Expand Down

0 comments on commit 846d904

Please sign in to comment.