using Core.Blueprint.DAL.Mongo.Contracts; using Core.Blueprint.DAL.Mongo.Entities.Collections; using Core.Blueprint.DAL.Mongo.Entities.Requests; using Core.Blueprint.Mongo; using Core.Blueprint.Redis; using Core.Blueprint.Redis.Helpers; using Mapster; using Microsoft.Extensions.Options; namespace Core.Blueprint.DAL.Mongo.Service { public class BlueprintService : IBlueprintService { private readonly CollectionRepository repository; private readonly CacheSettings cacheSettings; private readonly IRedisCacheProvider cacheProvider; public BlueprintService(CollectionRepository repository, IRedisCacheProvider cacheProvider, IOptions cacheSettings) { this.repository = repository; this.repository.CollectionInitialization(); this.cacheSettings = cacheSettings.Value; this.cacheProvider = cacheProvider; } public async ValueTask CreateBlueprint(BlueprintRequest newBlueprint, CancellationToken cancellationToken) { var blueprintCollection = newBlueprint.Adapt(); await this.repository.InsertOneAsync(blueprintCollection); return blueprintCollection; } public async ValueTask GetBlueprintById(string _id, CancellationToken cancellationToken) { var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetBlueprintById", _id); var cachedData = await cacheProvider.GetAsync(cacheKey); if (cachedData is not null) { return cachedData; } var blueprint = await this.repository.FindByIdAsync(_id); await cacheProvider.SetAsync(cacheKey, blueprint); return blueprint; } public async ValueTask> GetAllBlueprints(CancellationToken cancellationToken) { var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllBlueprints"); var cachedData = await cacheProvider.GetAsync>(cacheKey) ?? []; if (cachedData.Any()) return cachedData; var blueprints = await this.repository.AsQueryable(); await cacheProvider.SetAsync(cacheKey, blueprints); return blueprints; } public async ValueTask UpdateBlueprint(string _id, BlueprintCollection entity, CancellationToken cancellationToken) { await this.repository.ReplaceOneAsync(entity); return entity; } public async ValueTask DeleteBlueprint(string _id, CancellationToken cancellationToken) { var entity = await this.repository.DeleteOneAsync(doc => doc._Id == _id); return entity; } } }