Adds messages api

This commit is contained in:
Jonathan Bourdon
2024-06-27 12:37:59 -04:00
parent 97a2c296f1
commit 623972bc36
21 changed files with 485 additions and 61 deletions

View File

@@ -0,0 +1,13 @@
namespace Hutopy.Web.Messages.Data;
public class Message
{
public Guid Id { get; init; }
public Guid ContentId { get; init; } // works for any - VideoId, ChatId, RoomId, xxxId, ForumId
public Guid CreatedBy { get; init; }
public DateTime CreatedAt { get; }
public Guid ParentId { get; init; }
public string Value { get; init; } = null!;
}

View File

@@ -0,0 +1,19 @@
using Microsoft.EntityFrameworkCore;
namespace Hutopy.Web.Messages.Data;
public class MessagingDbContext(
DbContextOptions<MessagingDbContext> options)
: DbContext(options)
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Message>()
.Property(c => c.CreatedAt)
.ValueGeneratedOnAdd()
.HasDefaultValueSql("CURRENT_TIMESTAMP");
}
public DbSet<Message> Messages { get; set; }
}

View File

@@ -0,0 +1,30 @@
using FastEndpoints;
using Hutopy.Web.Messages.Data;
using Microsoft.EntityFrameworkCore;
namespace Hutopy.Web.Messages.Handlers;
public class GetMessages(
MessagingDbContext context)
: EndpointWithoutRequest<List<Message>>
{
public override void Configure()
{
Tags("Messages");
Get("/api/messages/{ContentId:guid}");
AllowAnonymous();
}
public override async Task HandleAsync(
CancellationToken ct)
{
var contentId = Route<Guid>("ContentId");
var comments = await context
.Messages
.Where(c => c.ContentId == contentId)
.ToListAsync(cancellationToken: ct);
await SendAsync(comments, cancellation: ct);
}
}

View File

@@ -0,0 +1,33 @@
using FastEndpoints;
using Hutopy.Web.Messages.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Hutopy.Web.Messages.Handlers;
public record GetMessagesByUserRequest(
[FromRoute] Guid UserId);
public class GetMessagesByUser(
MessagingDbContext context)
: EndpointWithoutRequest<List<Message>>
{
public override void Configure()
{
Tags("Messages");
Get("/api/messages/by-user/{UserId:guid}");
}
public override async Task HandleAsync(
CancellationToken ct)
{
var userId = Route<Guid>("UserId");
var posts = await context
.Messages
.Where(c => c.CreatedBy == userId)
.ToListAsync(cancellationToken: ct);
await SendAsync(posts, cancellation: ct);
}
}

View File

@@ -0,0 +1,34 @@
using FastEndpoints;
using Hutopy.Web.Messages.Data;
namespace Hutopy.Web.Messages.Handlers;
public record PostMessageRequest(
Guid ContentId,
string Message);
public class PostMessage(
MessagingDbContext context)
: Endpoint<PostMessageRequest>
{
public override void Configure()
{
// TODO: Find how to specify the name we see in Swagger
Tags("Messages");
Post("/api/messages");
}
public override async Task HandleAsync(
PostMessageRequest req,
CancellationToken ct)
{
await context.Messages.AddAsync(
new Message {
ContentId = req.ContentId,
CreatedBy = User.GetUserId(),
Value = req.Message },
ct);
await context.SaveChangesAsync(ct);
}
}

View File

@@ -0,0 +1,37 @@
using FastEndpoints;
using Hutopy.Web.Messages.Data;
namespace Hutopy.Web.Messages.Handlers;
public record PostReplyMessageRequest(
Guid ContentId,
Guid ParentId,
string Message);
public sealed class PostReplyMessage(
MessagingDbContext context)
: Endpoint<PostReplyMessageRequest>
{
public override void Configure()
{
Tags("Messages");
Post("/api/messages/reply");
}
public override async Task HandleAsync(
PostReplyMessageRequest req,
CancellationToken ct)
{
await context.Messages.AddAsync(
new Message
{
ContentId = req.ContentId,
ParentId = req.ParentId,
CreatedBy = User.GetUserId(),
Value = req.Message
},
ct);
await context.SaveChangesAsync(ct);
}
}

View File

@@ -0,0 +1,59 @@
// <auto-generated />
using System;
using Hutopy.Web.Messages.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Hutopy.Web.Messages.Migrations
{
[DbContext(typeof(MessagingDbContext))]
[Migration("20240627081653_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Hutopy.Web.Messages.Data.Message", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("ContentId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2")
.HasDefaultValueSql("CURRENT_TIMESTAMP");
b.Property<Guid>("CreatedBy")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("ParentId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Messages");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Hutopy.Web.Messages.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ContentId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedBy = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
ParentId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Value = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Messages", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Messages");
}
}
}

View File

@@ -0,0 +1,56 @@
// <auto-generated />
using System;
using Hutopy.Web.Messages.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Hutopy.Web.Messages.Migrations
{
[DbContext(typeof(MessagingDbContext))]
partial class MessagingDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Hutopy.Web.Messages.Data.Message", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("ContentId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2")
.HasDefaultValueSql("CURRENT_TIMESTAMP");
b.Property<Guid>("CreatedBy")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("ParentId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Messages");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,42 @@
using System.Security.Claims;
namespace Hutopy.Web.Messages;
public class Shared(string claimName) : Exception;
public static class ClaimsPrincipalExtensions
{
public static Guid GetUserId(this ClaimsPrincipal claims)
{
return (Guid)claims.GetFirstValue<Guid>(ClaimTypes.NameIdentifier);
}
public static string GetFirstName(this ClaimsPrincipal claims)
{
return (string)claims.GetFirstValue<string>(ClaimTypes.GivenName);
}
public static string GetLastName(this ClaimsPrincipal claims)
{
return (string)claims.GetFirstValue<string>(ClaimTypes.Surname);
}
public static string GetEmail(this ClaimsPrincipal claims)
{
return (string)claims.GetFirstValue<string>(ClaimTypes.Email);
}
public static object GetFirstValue<TValue>(this ClaimsPrincipal claims, string key)
{
var claim = claims.FindFirst(key);
if (claim is null) throw new Shared(key);
if (typeof(TValue) == typeof(Guid))
{
return Guid.Parse(claim.Value);
}
return Convert.ChangeType(claim.Value, typeof(TValue));
}
}