57 lines
1.9 KiB
C#
57 lines
1.9 KiB
C#
using FictionArchive.Service.Shared.Contracts.Events;
|
|
using FictionArchive.Service.UserNovelDataService.Models.Database;
|
|
using FictionArchive.Service.UserNovelDataService.Services;
|
|
using MassTransit;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace FictionArchive.Service.UserNovelDataService.Consumers;
|
|
|
|
public class ChapterCreatedConsumer : IConsumer<IChapterCreated>
|
|
{
|
|
private readonly ILogger<ChapterCreatedConsumer> _logger;
|
|
private readonly UserNovelDataServiceDbContext _dbContext;
|
|
|
|
public ChapterCreatedConsumer(
|
|
ILogger<ChapterCreatedConsumer> logger,
|
|
UserNovelDataServiceDbContext dbContext)
|
|
{
|
|
_logger = logger;
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public async Task Consume(ConsumeContext<IChapterCreated> context)
|
|
{
|
|
var message = context.Message;
|
|
|
|
// Ensure novel exists
|
|
var novelExists = await _dbContext.Novels.AnyAsync(n => n.Id == message.NovelId);
|
|
if (!novelExists)
|
|
{
|
|
var novel = new Novel { Id = message.NovelId };
|
|
_dbContext.Novels.Add(novel);
|
|
}
|
|
|
|
// Ensure volume exists
|
|
var volumeExists = await _dbContext.Volumes.AnyAsync(v => v.Id == message.VolumeId);
|
|
if (!volumeExists)
|
|
{
|
|
var volume = new Volume { Id = message.VolumeId };
|
|
_dbContext.Volumes.Add(volume);
|
|
}
|
|
|
|
// Create chapter if not exists
|
|
var chapterExists = await _dbContext.Chapters.AnyAsync(c => c.Id == message.ChapterId);
|
|
if (chapterExists)
|
|
{
|
|
_logger.LogDebug("Chapter {ChapterId} already exists, skipping", message.ChapterId);
|
|
return;
|
|
}
|
|
|
|
var chapter = new Chapter { Id = message.ChapterId };
|
|
_dbContext.Chapters.Add(chapter);
|
|
await _dbContext.SaveChangesAsync();
|
|
|
|
_logger.LogInformation("Created chapter stub for {ChapterId} in novel {NovelId}", message.ChapterId, message.NovelId);
|
|
}
|
|
}
|