refactor(backend): use explicit types instead of var by default
This commit is contained in:
parent
bc7fd6d804
commit
649988db25
52 changed files with 506 additions and 420 deletions
|
@ -11,9 +11,8 @@ namespace Foxnouns.Backend.Database;
|
|||
|
||||
public class DatabaseContext(DbContextOptions options) : DbContext(options)
|
||||
{
|
||||
private static string GenerateConnectionString(Config.DatabaseConfig config)
|
||||
{
|
||||
return new NpgsqlConnectionStringBuilder(config.Url)
|
||||
private static string GenerateConnectionString(Config.DatabaseConfig config) =>
|
||||
new NpgsqlConnectionStringBuilder(config.Url)
|
||||
{
|
||||
Pooling = config.EnablePooling ?? true,
|
||||
Timeout = config.Timeout ?? 5,
|
||||
|
@ -22,7 +21,6 @@ public class DatabaseContext(DbContextOptions options) : DbContext(options)
|
|||
ConnectionPruningInterval = 10,
|
||||
ConnectionIdleLifetime = 10,
|
||||
}.ConnectionString;
|
||||
}
|
||||
|
||||
public static NpgsqlDataSource BuildDataSource(Config config)
|
||||
{
|
||||
|
@ -138,16 +136,16 @@ public class DesignTimeDatabaseContextFactory : IDesignTimeDbContextFactory<Data
|
|||
public DatabaseContext CreateDbContext(string[] args)
|
||||
{
|
||||
// Read the configuration file
|
||||
var config =
|
||||
Config config =
|
||||
new ConfigurationBuilder()
|
||||
.AddConfiguration()
|
||||
.Build()
|
||||
// Get the configuration as our config class
|
||||
.Get<Config>() ?? new();
|
||||
.Get<Config>() ?? new Config();
|
||||
|
||||
var dataSource = DatabaseContext.BuildDataSource(config);
|
||||
NpgsqlDataSource dataSource = DatabaseContext.BuildDataSource(config);
|
||||
|
||||
var options = DatabaseContext
|
||||
DbContextOptions options = DatabaseContext
|
||||
.BuildOptions(new DbContextOptionsBuilder(), dataSource, null)
|
||||
.Options;
|
||||
|
||||
|
|
|
@ -26,7 +26,7 @@ public static class DatabaseQueryExtensions
|
|||
}
|
||||
|
||||
User? user;
|
||||
if (Snowflake.TryParse(userRef, out var snowflake))
|
||||
if (Snowflake.TryParse(userRef, out Snowflake? snowflake))
|
||||
{
|
||||
user = await context
|
||||
.Users.Where(u => !u.Deleted)
|
||||
|
@ -42,7 +42,7 @@ public static class DatabaseQueryExtensions
|
|||
return user;
|
||||
throw new ApiError.NotFound(
|
||||
"No user with that ID or username found.",
|
||||
code: ErrorCode.UserNotFound
|
||||
ErrorCode.UserNotFound
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -52,12 +52,12 @@ public static class DatabaseQueryExtensions
|
|||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
var user = await context
|
||||
User? user = await context
|
||||
.Users.Where(u => !u.Deleted)
|
||||
.FirstOrDefaultAsync(u => u.Id == id, ct);
|
||||
if (user != null)
|
||||
return user;
|
||||
throw new ApiError.NotFound("No user with that ID found.", code: ErrorCode.UserNotFound);
|
||||
throw new ApiError.NotFound("No user with that ID found.", ErrorCode.UserNotFound);
|
||||
}
|
||||
|
||||
public static async Task<Member> ResolveMemberAsync(
|
||||
|
@ -66,16 +66,13 @@ public static class DatabaseQueryExtensions
|
|||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
var member = await context
|
||||
Member? member = await context
|
||||
.Members.Include(m => m.User)
|
||||
.Where(m => !m.User.Deleted)
|
||||
.FirstOrDefaultAsync(m => m.Id == id, ct);
|
||||
if (member != null)
|
||||
return member;
|
||||
throw new ApiError.NotFound(
|
||||
"No member with that ID found.",
|
||||
code: ErrorCode.MemberNotFound
|
||||
);
|
||||
throw new ApiError.NotFound("No member with that ID found.", ErrorCode.MemberNotFound);
|
||||
}
|
||||
|
||||
public static async Task<Member> ResolveMemberAsync(
|
||||
|
@ -86,7 +83,7 @@ public static class DatabaseQueryExtensions
|
|||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
var user = await context.ResolveUserAsync(userRef, token, ct);
|
||||
User user = await context.ResolveUserAsync(userRef, token, ct);
|
||||
return await context.ResolveMemberAsync(user.Id, memberRef, ct);
|
||||
}
|
||||
|
||||
|
@ -98,7 +95,7 @@ public static class DatabaseQueryExtensions
|
|||
)
|
||||
{
|
||||
Member? member;
|
||||
if (Snowflake.TryParse(memberRef, out var snowflake))
|
||||
if (Snowflake.TryParse(memberRef, out Snowflake? snowflake))
|
||||
{
|
||||
member = await context
|
||||
.Members.Include(m => m.User)
|
||||
|
@ -118,7 +115,7 @@ public static class DatabaseQueryExtensions
|
|||
return member;
|
||||
throw new ApiError.NotFound(
|
||||
"No member with that ID or name found.",
|
||||
code: ErrorCode.MemberNotFound
|
||||
ErrorCode.MemberNotFound
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -127,7 +124,10 @@ public static class DatabaseQueryExtensions
|
|||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
var app = await context.Applications.FirstOrDefaultAsync(a => a.Id == new Snowflake(0), ct);
|
||||
Application? app = await context.Applications.FirstOrDefaultAsync(
|
||||
a => a.Id == new Snowflake(0),
|
||||
ct
|
||||
);
|
||||
if (app != null)
|
||||
return app;
|
||||
|
||||
|
@ -152,9 +152,9 @@ public static class DatabaseQueryExtensions
|
|||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
var hash = SHA512.HashData(rawToken);
|
||||
byte[] hash = SHA512.HashData(rawToken);
|
||||
|
||||
var oauthToken = await context
|
||||
Token? oauthToken = await context
|
||||
.Tokens.Include(t => t.Application)
|
||||
.Include(t => t.User)
|
||||
.FirstOrDefaultAsync(
|
||||
|
@ -174,7 +174,7 @@ public static class DatabaseQueryExtensions
|
|||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
var hash = SHA512.HashData(rawToken);
|
||||
byte[] hash = SHA512.HashData(rawToken);
|
||||
return await context
|
||||
.Tokens.Where(t =>
|
||||
t.Hash == hash
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
using Npgsql;
|
||||
using Serilog;
|
||||
|
||||
namespace Foxnouns.Backend.Database;
|
||||
|
@ -9,8 +10,8 @@ public static class DatabaseServiceExtensions
|
|||
Config config
|
||||
)
|
||||
{
|
||||
var dataSource = DatabaseContext.BuildDataSource(config);
|
||||
var loggerFactory = new LoggerFactory().AddSerilog(dispose: false);
|
||||
NpgsqlDataSource dataSource = DatabaseContext.BuildDataSource(config);
|
||||
ILoggerFactory loggerFactory = new LoggerFactory().AddSerilog(dispose: false);
|
||||
|
||||
serviceCollection.AddDbContext<DatabaseContext>(options =>
|
||||
DatabaseContext.BuildOptions(options, dataSource, loggerFactory)
|
||||
|
|
|
@ -20,8 +20,10 @@ public static class FlagQueryExtensions
|
|||
Snowflake[] flagIds
|
||||
)
|
||||
{
|
||||
var currentFlags = await db.UserFlags.Where(f => f.UserId == userId).ToListAsync();
|
||||
foreach (var flag in currentFlags)
|
||||
List<UserFlag> currentFlags = await db
|
||||
.UserFlags.Where(f => f.UserId == userId)
|
||||
.ToListAsync();
|
||||
foreach (UserFlag flag in currentFlags)
|
||||
db.UserFlags.Remove(flag);
|
||||
|
||||
// If there's no new flags to set, we're done
|
||||
|
@ -30,12 +32,16 @@ public static class FlagQueryExtensions
|
|||
if (flagIds.Length > 100)
|
||||
return ValidationError.LengthError("Too many profile flags", 0, 100, flagIds.Length);
|
||||
|
||||
var flags = await db.GetFlagsAsync(userId);
|
||||
var unknownFlagIds = flagIds.Where(id => flags.All(f => f.Id != id)).ToArray();
|
||||
List<PrideFlag> flags = await db.GetFlagsAsync(userId);
|
||||
Snowflake[] unknownFlagIds = flagIds.Where(id => flags.All(f => f.Id != id)).ToArray();
|
||||
if (unknownFlagIds.Length != 0)
|
||||
return ValidationError.GenericValidationError("Unknown flag IDs", unknownFlagIds);
|
||||
|
||||
var userFlags = flagIds.Select(id => new UserFlag { PrideFlagId = id, UserId = userId });
|
||||
IEnumerable<UserFlag> userFlags = flagIds.Select(id => new UserFlag
|
||||
{
|
||||
PrideFlagId = id,
|
||||
UserId = userId,
|
||||
});
|
||||
db.UserFlags.AddRange(userFlags);
|
||||
|
||||
return null;
|
||||
|
@ -48,8 +54,10 @@ public static class FlagQueryExtensions
|
|||
Snowflake[] flagIds
|
||||
)
|
||||
{
|
||||
var currentFlags = await db.MemberFlags.Where(f => f.MemberId == memberId).ToListAsync();
|
||||
foreach (var flag in currentFlags)
|
||||
List<MemberFlag> currentFlags = await db
|
||||
.MemberFlags.Where(f => f.MemberId == memberId)
|
||||
.ToListAsync();
|
||||
foreach (MemberFlag flag in currentFlags)
|
||||
db.MemberFlags.Remove(flag);
|
||||
|
||||
if (flagIds.Length == 0)
|
||||
|
@ -57,12 +65,12 @@ public static class FlagQueryExtensions
|
|||
if (flagIds.Length > 100)
|
||||
return ValidationError.LengthError("Too many profile flags", 0, 100, flagIds.Length);
|
||||
|
||||
var flags = await db.GetFlagsAsync(userId);
|
||||
var unknownFlagIds = flagIds.Where(id => flags.All(f => f.Id != id)).ToArray();
|
||||
List<PrideFlag> flags = await db.GetFlagsAsync(userId);
|
||||
Snowflake[] unknownFlagIds = flagIds.Where(id => flags.All(f => f.Id != id)).ToArray();
|
||||
if (unknownFlagIds.Length != 0)
|
||||
return ValidationError.GenericValidationError("Unknown flag IDs", unknownFlagIds);
|
||||
|
||||
var memberFlags = flagIds.Select(id => new MemberFlag
|
||||
IEnumerable<MemberFlag> memberFlags = flagIds.Select(id => new MemberFlag
|
||||
{
|
||||
PrideFlagId = id,
|
||||
MemberId = memberId,
|
||||
|
|
|
@ -18,8 +18,8 @@ public class Application : BaseModel
|
|||
string[] redirectUrls
|
||||
)
|
||||
{
|
||||
var clientId = RandomNumberGenerator.GetHexString(32, true);
|
||||
var clientSecret = AuthUtils.RandomToken();
|
||||
string clientId = RandomNumberGenerator.GetHexString(32, true);
|
||||
string clientSecret = AuthUtils.RandomToken();
|
||||
|
||||
if (scopes.Except(AuthUtils.ApplicationScopes).Any())
|
||||
{
|
||||
|
|
|
@ -59,7 +59,7 @@ public readonly struct Snowflake(ulong value) : IEquatable<Snowflake>
|
|||
public static bool TryParse(string input, [NotNullWhen(true)] out Snowflake? snowflake)
|
||||
{
|
||||
snowflake = null;
|
||||
if (!ulong.TryParse(input, out var res))
|
||||
if (!ulong.TryParse(input, out ulong res))
|
||||
return false;
|
||||
snowflake = new Snowflake(res);
|
||||
return true;
|
||||
|
@ -70,10 +70,7 @@ public readonly struct Snowflake(ulong value) : IEquatable<Snowflake>
|
|||
|
||||
public override bool Equals(object? obj) => obj is Snowflake other && Value == other.Value;
|
||||
|
||||
public bool Equals(Snowflake other)
|
||||
{
|
||||
return Value == other.Value;
|
||||
}
|
||||
public bool Equals(Snowflake other) => Value == other.Value;
|
||||
|
||||
public override int GetHashCode() => Value.GetHashCode();
|
||||
|
||||
|
@ -83,11 +80,7 @@ public readonly struct Snowflake(ulong value) : IEquatable<Snowflake>
|
|||
/// An Entity Framework ValueConverter for Snowflakes to longs.
|
||||
/// </summary>
|
||||
// ReSharper disable once ClassNeverInstantiated.Global
|
||||
public class ValueConverter()
|
||||
: ValueConverter<Snowflake, long>(
|
||||
convertToProviderExpression: x => x,
|
||||
convertFromProviderExpression: x => x
|
||||
);
|
||||
public class ValueConverter() : ValueConverter<Snowflake, long>(x => x, x => x);
|
||||
|
||||
private class JsonConverter : JsonConverter<Snowflake>
|
||||
{
|
||||
|
@ -106,10 +99,7 @@ public readonly struct Snowflake(ulong value) : IEquatable<Snowflake>
|
|||
Snowflake existingValue,
|
||||
bool hasExistingValue,
|
||||
JsonSerializer serializer
|
||||
)
|
||||
{
|
||||
return ulong.Parse((string)reader.Value!);
|
||||
}
|
||||
) => ulong.Parse((string)reader.Value!);
|
||||
}
|
||||
|
||||
private class TypeConverter : System.ComponentModel.TypeConverter
|
||||
|
@ -126,9 +116,6 @@ public readonly struct Snowflake(ulong value) : IEquatable<Snowflake>
|
|||
ITypeDescriptorContext? context,
|
||||
CultureInfo? culture,
|
||||
object value
|
||||
)
|
||||
{
|
||||
return TryParse((string)value, out var snowflake) ? snowflake : null;
|
||||
}
|
||||
) => TryParse((string)value, out Snowflake? snowflake) ? snowflake : null;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -28,9 +28,9 @@ public class SnowflakeGenerator : ISnowflakeGenerator
|
|||
public Snowflake GenerateSnowflake(Instant? time = null)
|
||||
{
|
||||
time ??= SystemClock.Instance.GetCurrentInstant();
|
||||
var increment = Interlocked.Increment(ref _increment);
|
||||
var threadId = Environment.CurrentManagedThreadId % 32;
|
||||
var timestamp = time.Value.ToUnixTimeMilliseconds() - Snowflake.Epoch;
|
||||
long increment = Interlocked.Increment(ref _increment);
|
||||
int threadId = Environment.CurrentManagedThreadId % 32;
|
||||
long timestamp = time.Value.ToUnixTimeMilliseconds() - Snowflake.Epoch;
|
||||
|
||||
return (timestamp << 22)
|
||||
| (uint)(_processId << 17)
|
||||
|
@ -44,8 +44,5 @@ public static class SnowflakeGeneratorServiceExtensions
|
|||
public static IServiceCollection AddSnowflakeGenerator(
|
||||
this IServiceCollection services,
|
||||
int? processId = null
|
||||
)
|
||||
{
|
||||
return services.AddSingleton<ISnowflakeGenerator>(new SnowflakeGenerator(processId));
|
||||
}
|
||||
) => services.AddSingleton<ISnowflakeGenerator>(new SnowflakeGenerator(processId));
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue