// ========================================================================== // CollectionExtensions.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Threading.Tasks; using MongoDB.Driver; using Squidex.Events; using Squidex.Infrastructure; using Squidex.Infrastructure.CQRS.Events; using Squidex.Infrastructure.MongoDb; namespace Squidex.Read.MongoDb.Utils { public static class MongoCollectionExtensions { public static Task CreateAsync(this IMongoCollection collection, SquidexEvent @event, EnvelopeHeaders headers, Action updater) where T : MongoEntity, new() { var entity = EntityMapper.Create(@event, headers); updater(entity); return collection.InsertOneIfNotExistsAsync(entity); } public static async Task CreateAsync(this IMongoCollection collection, SquidexEvent @event, EnvelopeHeaders headers, Func updater) where T : MongoEntity, new() { var entity = EntityMapper.Create(@event, headers); await updater(entity); await collection.InsertOneIfNotExistsAsync(entity); } public static async Task UpdateAsync(this IMongoCollection collection, SquidexEvent @event, EnvelopeHeaders headers, Action updater) where T : MongoEntity, new() { var entity = await collection.Find(t => t.Id == headers.AggregateId()).FirstOrDefaultAsync(); if (entity == null) { throw new DomainObjectNotFoundException(headers.AggregateId().ToString(), typeof(T)); } EntityMapper.Update(@event, headers, entity); updater(entity); await collection.ReplaceOneAsync(t => t.Id == entity.Id, entity); } } }