diff --git a/Kyoo/Controllers/Repositories/StudioRepository.cs b/Kyoo/Controllers/Repositories/StudioRepository.cs new file mode 100644 index 00000000..900f5b79 --- /dev/null +++ b/Kyoo/Controllers/Repositories/StudioRepository.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Kyoo.Models; +using Kyoo.Models.Exceptions; +using Microsoft.EntityFrameworkCore; + +namespace Kyoo.Controllers +{ + public class StudioRepository : IStudioRepository + { + private readonly DatabaseContext _database; + + + public StudioRepository(DatabaseContext database) + { + _database = database; + } + + public async Task Get(int id) + { + return await _database.Studios.FirstOrDefaultAsync(x => x.ID == id); + } + + public async Task Get(string slug) + { + return await _database.Studios.FirstOrDefaultAsync(x => x.Slug == slug); + } + + public async Task> Search(string query) + { + return await _database.Studios + .Where(x => EF.Functions.Like(x.Name, $"%{query}%")) + .Take(20) + .ToListAsync(); + } + + public async Task> GetAll() + { + return await _database.Studios.ToListAsync(); + } + + public async Task Create(Studio obj) + { + if (obj == null) + throw new ArgumentNullException(nameof(obj)); + + await _database.Studios.AddAsync(obj); + await _database.SaveChangesAsync(); + return obj.ID; + } + + public async Task CreateIfNotExists(Studio obj) + { + if (obj == null) + throw new ArgumentNullException(nameof(obj)); + + Studio old = await Get(obj.Slug); + if (old != null) + return old.ID; + return await Create(obj); + } + + public async Task Edit(Studio edited, bool resetOld) + { + if (edited == null) + throw new ArgumentNullException(nameof(edited)); + + Studio old = await Get(edited.Name); + + if (old == null) + throw new ItemNotFound($"No studio found with the name {edited.Name}."); + + if (resetOld) + Utility.Nullify(old); + Utility.Merge(old, edited); + await _database.SaveChangesAsync(); + } + + public async Task Delete(Studio obj) + { + _database.Studios.Remove(obj); + await _database.SaveChangesAsync(); + } + } +} \ No newline at end of file