Add items crud to api

This commit is contained in:
2026-03-21 20:20:02 -05:00
parent cda10dfaa4
commit a9b4d136d5
12 changed files with 461 additions and 70 deletions

View File

@@ -0,0 +1,306 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace agologum_api.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260322011947_AddItems")]
partial class AddItems
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("agologumApi.Models.Item", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("LastEditedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Items");
});
modelBuilder.Entity("agologumApi.Models.User", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace agologum_api.Migrations
{
/// <inheritdoc />
public partial class AddItems : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Items",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
LastEditedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Items", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Items");
}
}
}

View File

@@ -153,6 +153,33 @@ namespace agologum_api.Migrations
b.ToTable("AspNetUserTokens", (string)null); b.ToTable("AspNetUserTokens", (string)null);
}); });
modelBuilder.Entity("agologumApi.Models.Item", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("LastEditedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Items");
});
modelBuilder.Entity("agologumApi.Models.User", b => modelBuilder.Entity("agologumApi.Models.User", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")

View File

@@ -21,7 +21,7 @@ builder.Services.AddDbContext<AppDbContext>(options =>
builder.Services.AddControllers(); builder.Services.AddControllers();
// services // services
builder.Services.AddScoped<UserService>(); builder.Services.AddScoped<ItemService>();
builder.Services.AddScoped<JwtService>(); builder.Services.AddScoped<JwtService>();
// configuration for jwt authentication // configuration for jwt authentication

View File

@@ -14,14 +14,12 @@ public class AuthController : ControllerBase {
private readonly UserManager<User> userManager_; private readonly UserManager<User> userManager_;
private readonly SignInManager<User> signInManager_; private readonly SignInManager<User> signInManager_;
private readonly UserService users_;
private readonly JwtService jwt_; private readonly JwtService jwt_;
public AuthController(UserManager<User> userManager, SignInManager<User> signInManager, UserService users, JwtService jwt) { public AuthController(UserManager<User> userManager, SignInManager<User> signInManager, JwtService jwt) {
userManager_ = userManager; userManager_ = userManager;
signInManager_ = signInManager; signInManager_ = signInManager;
users_ = users;
jwt_ = jwt; jwt_ = jwt;
} }

View File

@@ -7,39 +7,39 @@ using agologumApi.Services;
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
public class UsersController : ControllerBase { public class ItemsController : ControllerBase {
private readonly UserService service_; private readonly ItemService service_;
public UsersController(UserService service) { public ItemsController(ItemService service) {
service_ = service; service_ = service;
} }
[AllowAnonymous] // accessible if not authorized [AllowAnonymous] // accessible if not authorized
[HttpGet] [HttpGet]
public async Task<ActionResult<List<User>>> getUsers() { public async Task<ActionResult<List<Item>>> getItemss() {
return Ok(await service_.GetAll()); return Ok(await service_.GetAll());
} }
[AllowAnonymous] [AllowAnonymous]
[HttpGet("{id:int}")] [HttpGet("{id:int}")]
public async Task<ActionResult<User>> getUser(int id) { public async Task<ActionResult<Item>> getItem(int id) {
var user = await service_.Get(id); var item = await service_.Get(id);
if (user == null) return NotFound(); if (item == null) return NotFound();
return Ok(user); return Ok(item);
} }
[Authorize] // testing the authorization [Authorize] // testing the authorization
[HttpPost] [HttpPost]
public async Task<ActionResult<User>> createUser(User user) { public async Task<ActionResult<Item>> createItem(Item item) {
var created = await service_.Create(user); var created = await service_.Create(item);
return CreatedAtAction( return CreatedAtAction(
nameof(getUser), nameof(getItem),
new { id = created.Id }, new { id = created.Id },
created created
); );
@@ -47,9 +47,9 @@ public class UsersController : ControllerBase {
[Authorize] [Authorize]
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<ActionResult<User>> updateUser(int id, User user) { public async Task<ActionResult<Item>> updateItem(int id, Item item) {
var updated = await service_.Update(user); var updated = await service_.Update(item);
if (updated == null) return NotFound(); if (updated == null) return NotFound();
@@ -58,7 +58,7 @@ public class UsersController : ControllerBase {
[Authorize] [Authorize]
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<ActionResult> deleteUser(int id) { public async Task<ActionResult> deleteItem(int id) {
var success = await service_.Delete(id); var success = await service_.Delete(id);

View File

@@ -10,4 +10,7 @@ public class AppDbContext : IdentityDbContext<User> {
} }
// Db set for each model besides Users (DbSet<template> is already defined in IdenityDbContext<template>)
public DbSet<Item> Items { get; set; }
} }

View File

@@ -13,3 +13,10 @@ public class LoginDto {
public string Password { get; set; } = ""; public string Password { get; set; } = "";
} }
public class ItemDto {
public String Name { get; set; } = "";
public String Description { get; set; } = "";
}

12
api/src/Models/Item.cs Normal file
View File

@@ -0,0 +1,12 @@
namespace agologumApi.Models;
public class Item {
public int Id { get; set; }
public String Name { get; set; } = "";
public String Description { get; set; } = "";
public DateTime CreatedAt { get; set; }
public DateTime LastEditedAt { get; set; }
};

View File

@@ -0,0 +1,51 @@
using Microsoft.EntityFrameworkCore;
using agologumApi.Models;
namespace agologumApi.Services;
public class ItemService {
private readonly AppDbContext db_;
public ItemService(AppDbContext db) {
db_ = db;
}
public async Task<List<Item>> GetAll() {
return await db_.Items.ToListAsync();
}
public async Task<Item?> Get(int id) {
return await db_.Items.FindAsync(id);
}
public async Task<Item?> Get(string name) {
return await db_.Items.FirstOrDefaultAsync(u => u.Name == name);
}
public async Task<Item> Create(Item item) {
db_.Items.Add(item);
await db_.SaveChangesAsync();
return item;
}
public async Task<Item> Update(Item item) {
db_.Items.Update(item);
await db_.SaveChangesAsync();
return item;
}
public async Task<bool> Delete(int id) {
Item? item = await db_.Items.FindAsync(id);
if(item != null) {
db_.Items.Remove(item);
await db_.SaveChangesAsync();
return true;
} else {
return false;
}
}
}

View File

@@ -1,51 +0,0 @@
using Microsoft.EntityFrameworkCore;
using agologumApi.Models;
namespace agologumApi.Services;
public class UserService {
private readonly AppDbContext db_;
public UserService(AppDbContext db) {
db_ = db;
}
public async Task<List<User>> GetAll() {
return await db_.Users.ToListAsync();
}
public async Task<User?> Get(int id) {
return await db_.Users.FindAsync(id);
}
public async Task<User?> Get(string username) {
return await db_.Users.FirstOrDefaultAsync(u => u.UserName == username);
}
public async Task<User> Create(User user) {
db_.Users.Add(user);
await db_.SaveChangesAsync();
return user;
}
public async Task<User> Update(User user) {
db_.Users.Update(user);
await db_.SaveChangesAsync();
return user;
}
public async Task<bool> Delete(int id) {
User? user = await db_.Users.FindAsync(id);
if(user != null) {
db_.Users.Remove(user);
await db_.SaveChangesAsync();
return true;
} else {
return false;
}
}
}

View File

@@ -11,7 +11,6 @@ export const register = async (user: RegisterDto) => {
try { try {
console.log(user); console.log(user);
const response = await api.post(`${API_URL}/register`, user);
// TODO: if valid // TODO: if valid