|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using CommunityToolkit.Datasync.Server.Abstractions.Http; |
| 6 | +using MongoDB.Bson; |
| 7 | +using MongoDB.Driver; |
| 8 | + |
| 9 | +namespace CommunityToolkit.Datasync.Server.MongoDB; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// A repository implementation that stored data in a LiteDB database. |
| 13 | +/// </summary> |
| 14 | +/// <typeparam name="TEntity">The entity type to store in the database.</typeparam> |
| 15 | +public class MongoDBRepository<TEntity> : IRepository<TEntity> where TEntity : MongoTableData |
| 16 | +{ |
| 17 | + /// <summary> |
| 18 | + /// Creates a new <see cref="MongoDBRepository{TEntity}"/> using the provided MongoDB database. |
| 19 | + /// </summary> |
| 20 | + /// <remarks> |
| 21 | + /// The collection name is based on the entity type. |
| 22 | + /// </remarks> |
| 23 | + /// <param name="database">The <see cref="IMongoDatabase"/> to use for storing entities.</param> |
| 24 | + public MongoDBRepository(IMongoDatabase database) : this(database.GetCollection<TEntity>(typeof(TEntity).Name.ToLowerInvariant() + "s")) |
| 25 | + { |
| 26 | + } |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Creates a new <see cref="MongoDBRepository{TEntity}"/> using the provided database connection |
| 30 | + /// and collection name. |
| 31 | + /// </summary> |
| 32 | + /// <param name="collection">The <see cref="IMongoCollection{TDocument}"/> to use for storing entities.</param> |
| 33 | + public MongoDBRepository(IMongoCollection<TEntity> collection) |
| 34 | + { |
| 35 | + Collection = collection; |
| 36 | + // TODO: Ensure that there is an index on the right properties. |
| 37 | + } |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// The collection within the LiteDb database that stores the entities. |
| 41 | + /// </summary> |
| 42 | + public virtual IMongoCollection<TEntity> Collection { get; } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// The mechanism by which an Id is generated when one is not provided. |
| 46 | + /// </summary> |
| 47 | + public Func<TEntity, string> IdGenerator { get; set; } = _ => Guid.NewGuid().ToString("N"); |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// The mechanism by which a new version byte array is generated. |
| 51 | + /// </summary> |
| 52 | + public Func<byte[]> VersionGenerator { get; set; } = () => Guid.NewGuid().ToByteArray(); |
| 53 | + |
| 54 | + /// <summary> |
| 55 | + /// Updates the system properties for the provided entity on write. |
| 56 | + /// </summary> |
| 57 | + /// <param name="entity">The entity to update.</param> |
| 58 | + protected void UpdateEntity(TEntity entity) |
| 59 | + { |
| 60 | + entity.UpdatedAt = DateTimeOffset.UtcNow; |
| 61 | + entity.Version = VersionGenerator.Invoke(); |
| 62 | + } |
| 63 | + |
| 64 | + /// <summary> |
| 65 | + /// Checks that the provided ID is valid. |
| 66 | + /// </summary> |
| 67 | + /// <param name="id">The ID of the entity to check.</param> |
| 68 | + /// <exception cref="HttpException">Thrown if the ID is not valid.</exception> |
| 69 | + protected static void CheckIdIsValid(string id) |
| 70 | + { |
| 71 | + if (string.IsNullOrEmpty(id)) |
| 72 | + { |
| 73 | + throw new HttpException(HttpStatusCodes.Status400BadRequest); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + /// <summary> |
| 78 | + /// Returns a filter definition for finding a single document. |
| 79 | + /// </summary> |
| 80 | + /// <param name="id">The ID of the document to find.</param> |
| 81 | + /// <returns>The filter definition to find the document.</returns> |
| 82 | + protected FilterDefinition<TEntity> GetFilterById(string id) |
| 83 | + => Builders<TEntity>.Filter.Eq(x => x.Id, id); |
| 84 | + |
| 85 | + /// <summary> |
| 86 | + /// Returns the document with the provided ID, or null if it doesn't exist. |
| 87 | + /// </summary> |
| 88 | + /// <param name="id">The ID of the document to find.</param> |
| 89 | + /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe.</param> |
| 90 | + /// <returns>The document, or null if not found.</returns> |
| 91 | + protected async ValueTask<TEntity?> FindDocumentByIdAsync(string id, CancellationToken cancellationToken = default) |
| 92 | + { |
| 93 | + return await Collection.Find(GetFilterById(id)).FirstOrDefaultAsync(cancellationToken); |
| 94 | + } |
| 95 | + |
| 96 | + /// <inheritdoc/> |
| 97 | + public virtual ValueTask<IQueryable<TEntity>> AsQueryableAsync(CancellationToken cancellationToken = default) |
| 98 | + => ValueTask.FromResult(Collection.AsQueryable()); |
| 99 | + |
| 100 | + /// <inheritdoc/> |
| 101 | + public virtual async ValueTask CreateAsync(TEntity entity, CancellationToken cancellationToken = default) |
| 102 | + { |
| 103 | + if (string.IsNullOrEmpty(entity.Id)) |
| 104 | + { |
| 105 | + entity.Id = IdGenerator.Invoke(entity); |
| 106 | + } |
| 107 | + |
| 108 | + TEntity? existingEntity = await FindDocumentByIdAsync(entity.Id, cancellationToken).ConfigureAwait(false); |
| 109 | + if (existingEntity is not null) |
| 110 | + { |
| 111 | + throw new HttpException(HttpStatusCodes.Status409Conflict) { Payload = existingEntity }; |
| 112 | + } |
| 113 | + |
| 114 | + UpdateEntity(entity); |
| 115 | + await Collection.InsertOneAsync(entity, options: null, cancellationToken); |
| 116 | + } |
| 117 | + |
| 118 | + /// <inheritdoc/> |
| 119 | + public virtual async ValueTask DeleteAsync(string id, byte[]? version = null, CancellationToken cancellationToken = default) |
| 120 | + { |
| 121 | + CheckIdIsValid(id); |
| 122 | + |
| 123 | + TEntity storedEntity = await FindDocumentByIdAsync(id, cancellationToken).ConfigureAwait(false) |
| 124 | + ?? throw new HttpException(HttpStatusCodes.Status404NotFound); |
| 125 | + if (version?.Length > 0 && !storedEntity.Version.SequenceEqual(version)) |
| 126 | + { |
| 127 | + throw new HttpException(HttpStatusCodes.Status412PreconditionFailed) { Payload = storedEntity }; |
| 128 | + } |
| 129 | + |
| 130 | + DeleteResult result = await Collection.DeleteOneAsync(GetFilterById(id), cancellationToken); |
| 131 | + if (result.DeletedCount == 0) |
| 132 | + { |
| 133 | + throw new HttpException(HttpStatusCodes.Status404NotFound); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + /// <inheritdoc/> |
| 138 | + public virtual async ValueTask<TEntity> ReadAsync(string id, CancellationToken cancellationToken = default) |
| 139 | + { |
| 140 | + CheckIdIsValid(id); |
| 141 | + |
| 142 | + return await FindDocumentByIdAsync(id, cancellationToken).ConfigureAwait(false) |
| 143 | + ?? throw new HttpException(HttpStatusCodes.Status404NotFound); |
| 144 | + } |
| 145 | + |
| 146 | + /// <inheritdoc/> |
| 147 | + public virtual async ValueTask ReplaceAsync(TEntity entity, byte[]? version = null, CancellationToken cancellationToken = default) |
| 148 | + { |
| 149 | + CheckIdIsValid(entity.Id); |
| 150 | + |
| 151 | + TEntity storedEntity = await FindDocumentByIdAsync(entity.Id, cancellationToken).ConfigureAwait(false) |
| 152 | + ?? throw new HttpException(HttpStatusCodes.Status404NotFound); |
| 153 | + if (version?.Length > 0 && !storedEntity.Version.SequenceEqual(version)) |
| 154 | + { |
| 155 | + throw new HttpException(HttpStatusCodes.Status412PreconditionFailed) { Payload = storedEntity }; |
| 156 | + } |
| 157 | + |
| 158 | + UpdateEntity(entity); |
| 159 | + ReplaceOptions<TEntity> options = new() { IsUpsert = false }; |
| 160 | + ReplaceOneResult result = await Collection.ReplaceOneAsync(GetFilterById(entity.Id), entity, options, cancellationToken); |
| 161 | + if (result.IsModifiedCountAvailable && result.ModifiedCount == 0) |
| 162 | + { |
| 163 | + throw new HttpException(HttpStatusCodes.Status404NotFound); |
| 164 | + } |
| 165 | + } |
| 166 | +} |
0 commit comments