2 Commits

Author SHA1 Message Date
7ab03d8073 change users crud to items
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 8s
Build and Deploy API / build-and-deploy (push) Successful in 10s
2026-03-21 23:44:26 -05:00
a9b4d136d5 Add items crud to api 2026-03-21 20:20:02 -05:00
23 changed files with 625 additions and 213 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);
});
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")

View File

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

View File

@@ -14,14 +14,12 @@ public class AuthController : ControllerBase {
private readonly UserManager<User> userManager_;
private readonly SignInManager<User> signInManager_;
private readonly UserService users_;
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;
signInManager_ = signInManager;
users_ = users;
jwt_ = jwt;
}

View File

@@ -7,39 +7,39 @@ using agologumApi.Services;
[ApiController]
[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;
}
[AllowAnonymous] // accessible if not authorized
[HttpGet]
public async Task<ActionResult<List<User>>> getUsers() {
public async Task<ActionResult<List<Item>>> getItemss() {
return Ok(await service_.GetAll());
}
[AllowAnonymous]
[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
[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(
nameof(getUser),
nameof(getItem),
new { id = created.Id },
created
);
@@ -47,9 +47,9 @@ public class UsersController : ControllerBase {
[Authorize]
[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();
@@ -58,7 +58,7 @@ public class UsersController : ControllerBase {
[Authorize]
[HttpDelete("{id}")]
public async Task<ActionResult> deleteUser(int id) {
public async Task<ActionResult> deleteItem(int 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

@@ -1,15 +0,0 @@
public class RegisterDto {
public string UserName { get; set; } = "";
public string Email { get; set; } = "";
public string Password { get; set; } = "";
}
public class LoginDto {
public string UserName { get; set; } = "";
public string Password { get; set; } = "";
}

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

@@ -0,0 +1,19 @@
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; }
};
public class ItemDto {
public String Name { get; set; } = "";
public String Description { get; set; } = "";
}

View File

@@ -30,3 +30,19 @@ public class User : IdentityUser {
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.entityframeworkcore.identityuser?view=aspnetcore-1.1
*/
};
// DTOs include only the minimum information for transit
public class RegisterDto {
public string UserName { get; set; } = "";
public string Email { get; set; } = "";
public string Password { get; set; } = "";
}
public class LoginDto {
public string UserName { get; set; } = "";
public string Password { 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 {
console.log(user);
const response = await api.post(`${API_URL}/register`, user);
// TODO: if valid

View File

@@ -0,0 +1,18 @@
// services are kinda whatever, but in general its a good idea for all api calls to be within a service (at least thats how angular handles it)
// this item service will handle all to <-> from the server when handling item objects
import api from "./axios.ts"
import type { Item } from "../models/Item.ts";
const API_URL: string = "/items";
export const getItems = () => api.get<Item[]>(`${API_URL}`);
export const getItem = (id: number) => api.get<Item>(`${API_URL}/${id}`);
export const createItem = (data: Item) => api.post<Item>(`${API_URL}`, data);
export const updateItem = (id: number, data: Item) => api.put<Item>(`${API_URL}/${id}`, data);
export const deleteItem = (id: number) => api.delete<Item>(`${API_URL}/${id}`);

View File

@@ -1,18 +0,0 @@
// services are kinda whatever, but in general its a good idea for all api calls to be within a service (at least thats how angular handles it)
// this user service will handle all to <-> from the server when handling user objects
import api from "./axios.ts"
import type { User } from "../models/User.ts";
const API_URL: string = "/users";
export const getUsers = () => api.get<User[]>(`${API_URL}`);
export const getUser = (id: number) => api.get<User>(`${API_URL}/${id}`);
export const createUser = (data: User) => api.post<User>(`${API_URL}`, data);
export const updateUser = (id: number, data: User) => api.put<User>(`${API_URL}/${id}`, data);
export const deleteUser = (id: number) => api.delete<User>(`${API_URL}/${id}`);

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
import { onMounted } from "vue";
import { useItemsStore} from "../stores/ItemsStore.ts";
const store = useItemsStore();
onMounted(() => { // register callback for when component is loaded on page
store.fetchItems();
})
</script>
<template>
<div>
<h1>Items</h1>
<router-link to="/item/new">Create Item</router-link>
<table>
<tr v-for="item in store.items" :key="item.id">
<td>{{ item.name }}</td>
<td>
<router-link :to="`/item/${item.id}`">Edit</router-link>
<button @click="store.removeItem(item.id)">Delete</button>
</td>
</tr>
</table>
</div>
</template>

View File

@@ -1,33 +0,0 @@
<script setup lang="ts">
import { onMounted } from "vue";
import { useUsersStore} from "../stores/UsersStore.ts";
const store = useUsersStore();
onMounted(() => { // register callback for when component is loaded on page
store.fetchUsers();
})
</script>
<template>
<div>
<h1>Users</h1>
<router-link to="/user/new">Create User</router-link>
<table>
<tr v-for="user in store.users" :key="user.id">
<td>{{ user.username }}</td>
<td>
<router-link :to="`/user/${user.id}`">Edit</router-link>
<button @click="store.removeUser(user.id)">Delete</button>
</td>
</tr>
</table>
</div>
</template>

19
client/src/models/Item.ts Normal file
View File

@@ -0,0 +1,19 @@
export interface Item {
id: number;
name: string;
description: string;
createdAt: string;
lastEditedAt: string;
}
export interface RegisterDto {
username: string;
email: string;
password: string;
}
export interface LoginDto {
username: string;
password: string;
}

View File

@@ -5,37 +5,38 @@
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useUsersStore } from "../stores/UsersStore.ts";
import type { User } from "../models/User.ts";
import { useItemsStore } from "../stores/ItemsStore.ts";
import type { Item } from "../models/Item.ts";
const store = useUsersStore();
const store = useItemsStore();
const route = useRoute();
const router = useRouter();
const user = ref<User>({
const item = ref<Item>({
id: 0,
username: "",
email: "",
password: ""
name: "",
description: "",
createdAt: "",
lastEditedAt: ""
});
const id: string | undefined = route.params.id as string | undefined
onMounted(() => {
if(id) {
const existing = store.users.find(i => i.id == Number(id));
if (existing) user.value = { ...existing };
const existing = store.items.find(i => i.id == Number(id));
if (existing) item.value = { ...existing };
}
});
async function save(): Promise<void> {
if(id) {
await store.updateUser(Number(id), user.value);
await store.updateItem(Number(id), item.value);
} else {
await store.addUser(user.value);
await store.addItem(item.value);
}
router.push("/users"); // redirect
router.push("/items"); // redirect
}
</script>
@@ -43,10 +44,10 @@ async function save(): Promise<void> {
<template>
<div>
<h2>{{ id ? "Edit User" : "Create User" }}</h2> <!-- omg I love ternary operator :D -->
<h2>{{ id ? "Edit Item" : "Create Item" }}</h2> <!-- omg I love ternary operator :D -->
<form @submit.prevent="save">
<input v-model="user.username" placeholder="Name" />
<input v-model="item.name" placeholder="Name" />
<button type="submit">Save</button>
</form>

View File

@@ -3,14 +3,14 @@
import { onMounted } from "vue"
import { useRoute, useRouter } from "vue-router";
import { useUsersStore } from "../stores/UsersStore.ts"
import { useItemsStore } from "../stores/ItemsStore.ts"
import * as authApi from "../api/AuthApi";
const store = useUsersStore()
const store = useItemsStore()
const router = useRouter();
onMounted(() => {
store.fetchUsers()
store.fetchItems()
})
function logout() {
@@ -22,23 +22,23 @@ function logout() {
<template>
<div>
<h1>Users</h1>
<h1>Items</h1>
<router-link to="/user/new">Create User</router-link>
<router-link to="/user/new">Create Item</router-link>
<table>
<tr v-for="user in store.users" :key="user.id">
<td>{{ user.username }}</td>
<tr v-for="item in store.items" :key="item.id">
<td>{{ item.name }}</td>
<td>
<router-link :to="`/user/${user.id}`" custom v-slot="{ navigate }">
<router-link :to="`/item/${item.id}`" custom v-slot="{ navigate }">
<button @click="navigate" role="link">Edit</button>
</router-link>
<button @click="store.removeUser(user.id)">Delete</button>
<button @click="store.removeItem(item.id)">Delete</button>
</td>
</tr>
</table>
<button @click="logout()">Logout</button>
</div>
</template>
</template>

View File

@@ -4,8 +4,8 @@
import { createRouter, createWebHistory } from "vue-router";
import LoginForm from "../pages/LoginForm.vue";
import RegisterForm from "../pages/RegisterForm.vue";
import UsersList from "../pages/UsersList.vue";
import UserForm from "../pages/UserForm.vue";
import ItemsList from "../pages/ItemsList.vue";
import ItemForm from "../pages/ItemForm.vue";
import index from "../pages/index.vue";
// link path to the page component
@@ -13,9 +13,9 @@ const routes = [
{ path: "/", component: index },
{ path: "/login", component: LoginForm },
{ path: "/register", component: RegisterForm },
{ path: "/users", component: UsersList, meta: { requiresAuth: true } },
{ path: "/user/new", component: UserForm, meta: { requiresAuth: true } },
{ path: "/user/:id", component: UserForm, meta: { requiresAuth: true } }
{ path: "/items", component: ItemsList },
{ path: "/item/new", component: ItemForm, meta: { requiresAuth: true } },
{ path: "/item/:id", component: ItemForm, meta: { requiresAuth: true } }
]; // I really like this
const router = createRouter({

View File

@@ -0,0 +1,48 @@
// stores are for component state management
// Pinia (?) i kinda dont get it because in angular you just hook a component to a service and that's it,
// though I guess the service handled the state management
// sighh
import { defineStore } from "pinia";
import type { Item } from "../models/Item.ts";
import * as itemsApi from "../api/ItemsApi";
interface ItemState {
items: Item[];
loading: boolean;
}
export const useItemsStore = defineStore("items", {
state: (): ItemState => ({
items: [],
loading: false
}),
actions: {
async fetchItems() {
this.loading = true;
const response = await itemsApi.getItems();
this.items = response.data;
this.loading = false;
},
async addItem(item: Item) {
const response = await itemsApi.createItem(item);
this.items.push(response.data);
},
async updateItem(id: number, item: Item) {
await itemsApi.updateItem(id, item);
const index = this.items.findIndex(i => i.id === id);
this.items[index] = item;
},
async removeItem(id: number) {
await itemsApi.deleteItem(id);
this.items = this.items.filter(i => i.id !== id);
}
}
});

View File

@@ -1,48 +0,0 @@
// stores are for component state management
// Pinia (?) i kinda dont get it because in angular you just hook a component to a service and that's it,
// though I guess the service handled the state management
// sighh
import { defineStore } from "pinia";
import type { User } from "../models/User.ts";
import * as usersApi from "../api/UsersApi";
interface UserState {
users: User[];
loading: boolean;
}
export const useUsersStore = defineStore("users", {
state: (): UserState => ({
users: [],
loading: false
}),
actions: {
async fetchUsers() {
this.loading = true;
const response = await usersApi.getUsers();
this.users = response.data;
this.loading = false;
},
async addUser(user: User) {
const response = await usersApi.createUser(user);
this.users.push(response.data);
},
async updateUser(id: number, user: User) {
await usersApi.updateUser(id, user);
const index = this.users.findIndex(i => i.id === id);
this.users[index] = user;
},
async removeUser(id: number) {
await usersApi.deleteUser(id);
this.users = this.users.filter(i => i.id !== id);
}
}
});