✨ Affliation spell CRUD
This commit is contained in:
45
DysonNetwork.Pass/Affiliation/AffiliationSpellService.cs
Normal file
45
DysonNetwork.Pass/Affiliation/AffiliationSpellService.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System.Security.Cryptography;
|
||||
using DysonNetwork.Shared.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DysonNetwork.Pass.Affiliation;
|
||||
|
||||
public class AffiliationSpellService(AppDatabase db)
|
||||
{
|
||||
public async Task<SnAffiliationSpell> CreateAffiliationSpell(Guid accountId, string? spellWord)
|
||||
{
|
||||
spellWord ??= _GenerateRandomString(8);
|
||||
var hasTaken = await db.AffiliationSpells.AnyAsync(s => s.Spell == spellWord);
|
||||
if (hasTaken) throw new InvalidOperationException("The spell has been taken.");
|
||||
|
||||
var spell = new SnAffiliationSpell
|
||||
{
|
||||
AccountId = accountId,
|
||||
Spell = spellWord
|
||||
};
|
||||
|
||||
db.AffiliationSpells.Add(spell);
|
||||
await db.SaveChangesAsync();
|
||||
return spell;
|
||||
}
|
||||
|
||||
public async Task<SnAffiliationSpell?> GetAffiliationSpell(string spellWord)
|
||||
{
|
||||
var spell = await db.AffiliationSpells.FirstOrDefaultAsync(s => s.Spell == spellWord);
|
||||
return spell;
|
||||
}
|
||||
|
||||
private static string _GenerateRandomString(int length)
|
||||
{
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
var result = new char[length];
|
||||
using var rng = RandomNumberGenerator.Create();
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
var bytes = new byte[1];
|
||||
rng.GetBytes(bytes);
|
||||
result[i] = chars[bytes[0] % chars.Length];
|
||||
}
|
||||
return new string(result);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user