Skip to content

Commit

Permalink
connect user and event entities (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tschonti authored Jul 22, 2024
1 parent f6552e6 commit fec8192
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 96 deletions.

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
-- CreateEnum
CREATE TYPE "DrinkType" AS ENUM ('BEER', 'WINE', 'SPIRIT', 'COCKTAIL');

-- CreateEnum
CREATE TYPE "Gender" AS ENUM ('Male', 'Female');

-- CreateTable
CREATE TABLE "User" (
"authSchId" TEXT NOT NULL,
"email" TEXT NOT NULL,
"firstName" TEXT NOT NULL,
"lastName" TEXT NOT NULL,
"gender" "Gender",
"weight" DOUBLE PRECISION,
"isAdmin" BOOLEAN NOT NULL DEFAULT false,
"profilePictureUrl" TEXT,

CONSTRAINT "User_pkey" PRIMARY KEY ("authSchId")
Expand All @@ -25,15 +31,6 @@ CREATE TABLE "Drink" (
CONSTRAINT "Drink_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "FavouriteDrink" (
"drinkId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"order" INTEGER NOT NULL,

CONSTRAINT "FavouriteDrink_pkey" PRIMARY KEY ("drinkId","userId")
);

-- CreateTable
CREATE TABLE "Event" (
"id" TEXT NOT NULL,
Expand All @@ -55,19 +52,24 @@ CREATE TABLE "DrinkAction" (
"milliliter" INTEGER NOT NULL,
"drinkId" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"userId" TEXT NOT NULL,

CONSTRAINT "DrinkAction_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "_DrinkToUser" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

-- AddForeignKey
ALTER TABLE "FavouriteDrink" ADD CONSTRAINT "FavouriteDrink_drinkId_fkey" FOREIGN KEY ("drinkId") REFERENCES "Drink"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- CreateIndex
CREATE UNIQUE INDEX "_DrinkToUser_AB_unique" ON "_DrinkToUser"("A", "B");

-- AddForeignKey
ALTER TABLE "FavouriteDrink" ADD CONSTRAINT "FavouriteDrink_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("authSchId") ON DELETE RESTRICT ON UPDATE CASCADE;
-- CreateIndex
CREATE INDEX "_DrinkToUser_B_index" ON "_DrinkToUser"("B");

-- AddForeignKey
ALTER TABLE "Event" ADD CONSTRAINT "Event_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("authSchId") ON DELETE RESTRICT ON UPDATE CASCADE;
Expand All @@ -79,4 +81,7 @@ ALTER TABLE "DrinkAction" ADD CONSTRAINT "DrinkAction_drinkId_fkey" FOREIGN KEY
ALTER TABLE "DrinkAction" ADD CONSTRAINT "DrinkAction_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "DrinkAction" ADD CONSTRAINT "DrinkAction_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("authSchId") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "_DrinkToUser" ADD CONSTRAINT "_DrinkToUser_A_fkey" FOREIGN KEY ("A") REFERENCES "Drink"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_DrinkToUser" ADD CONSTRAINT "_DrinkToUser_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("authSchId") ON DELETE CASCADE ON UPDATE CASCADE;
7 changes: 4 additions & 3 deletions apps/backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ model User {
lastName String
gender Gender?
weight Float?
isAdmin Boolean @default(false)
profilePictureUrl String?
// ownedEvents Event[]
ownedEvents Event[]
// drinkActions DrinkAction[]
favouriteDrinks Drink[]
}
Expand All @@ -54,8 +55,8 @@ model Drink {

model Event {
id String @id @default(uuid())
// ownerId String
// owner User @relation(fields: [ownerId], references: [authSchId])
ownerId String
owner User @relation(fields: [ownerId], references: [authSchId])
name String
location String
startDate DateTime
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/events/dto/create-event.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ import { OmitType } from '@nestjs/swagger';

import { Event } from '../entities/event.entity';

export class CreateEventDto extends OmitType(Event, ['id', 'createdAt']) {}
export class CreateEventDto extends OmitType(Event, ['id', 'createdAt', 'ownerId']) {}
6 changes: 6 additions & 0 deletions apps/backend/src/events/entities/event.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ export class Event {
@IsNotEmpty()
location: string;

/**
* Owner's ID.
*/
@IsUUID()
ownerId: string;

/**
* Date and time when the event starts.
* @example '2022-01-01T22:30:00.000Z'
Expand Down
29 changes: 21 additions & 8 deletions apps/backend/src/events/events.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Body, Controller, Delete, Get, Param, ParseUUIDPipe, Patch, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { CurrentUser } from '@kir-dev/passport-authsch';
import { Body, Controller, Delete, Get, Param, ParseUUIDPipe, Patch, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { User } from 'src/users/entities/user.entity';

import { CreateEventDto } from './dto/create-event.dto';
import { UpdateEventDto } from './dto/update-event.dto';
Expand All @@ -12,8 +15,10 @@ export class EventsController {
constructor(private readonly eventsService: EventsService) {}

@Post()
async create(@Body() data: CreateEventDto): Promise<Event> {
return this.eventsService.create(data);
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
async create(@Body() data: CreateEventDto, @CurrentUser() user: User): Promise<Event> {
return this.eventsService.create(data, user.authSchId);
}

@Get()
Expand All @@ -27,12 +32,20 @@ export class EventsController {
}

@Patch(':id')
async update(@Param('id', new ParseUUIDPipe()) id: string, @Body() data: UpdateEventDto): Promise<Event> {
return this.eventsService.update(id, data);
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
async update(
@Param('id', new ParseUUIDPipe()) id: string,
@Body() data: UpdateEventDto,
@CurrentUser() user: User
): Promise<Event> {
return this.eventsService.update(id, data, user);
}

@Delete(':id')
async remove(@Param('id', new ParseUUIDPipe()) id: string): Promise<Event> {
return this.eventsService.remove(id);
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
async remove(@Param('id', new ParseUUIDPipe()) id: string, @CurrentUser() user: User): Promise<Event> {
return this.eventsService.remove(id, user);
}
}
30 changes: 18 additions & 12 deletions apps/backend/src/events/events.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Event } from '@prisma/client';
import { PrismaService } from 'nestjs-prisma';
import { User } from 'src/users/entities/user.entity';

import { CreateEventDto } from './dto/create-event.dto';
import { UpdateEventDto } from './dto/update-event.dto';
Expand All @@ -9,8 +10,13 @@ import { UpdateEventDto } from './dto/update-event.dto';
export class EventsService {
constructor(readonly prisma: PrismaService) {}

async create(data: CreateEventDto): Promise<Event> {
return await this.prisma.event.create({ data });
async create(data: CreateEventDto, userId: string): Promise<Event> {
return await this.prisma.event.create({
data: {
...data,
ownerId: userId,
},
});
}

async findAll(): Promise<Event[]> {
Expand All @@ -25,19 +31,19 @@ export class EventsService {
return event;
}

async update(id: string, data: UpdateEventDto): Promise<Event> {
try {
return await this.prisma.event.update({ where: { id }, data });
} catch {
throw new NotFoundException('Event not found');
async update(id: string, data: UpdateEventDto, user: User): Promise<Event> {
const event = await this.prisma.event.findUnique({ where: { id } });
if (!event || (event.ownerId !== user.authSchId && !user.isAdmin)) {
throw new NotFoundException("Event not found or you don't have permission to update it");
}
return await this.prisma.event.update({ where: { id }, data });
}

async remove(id: string): Promise<Event> {
try {
return await this.prisma.event.delete({ where: { id } });
} catch {
throw new NotFoundException('Event not found');
async remove(id: string, user: User): Promise<Event> {
const event = await this.prisma.event.findUnique({ where: { id } });
if (!event || (event.ownerId !== user.authSchId && !user.isAdmin)) {
throw new NotFoundException("Event not found or you don't have permission to delete it");
}
return await this.prisma.event.delete({ where: { id } });
}
}
9 changes: 8 additions & 1 deletion apps/backend/src/users/entities/user.entity.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Gender } from '@prisma/client';
import { IsNotEmpty, IsOptional, IsString, IsUUID, Min } from 'class-validator';
import { IsBoolean, IsNotEmpty, IsOptional, IsString, IsUUID, Min } from 'class-validator';

export class User {
@IsUUID()
authSchId: string;
Expand Down Expand Up @@ -43,6 +44,12 @@ export class User {
@Min(0)
weight?: number;

/**
* Is the user an administrator?
*/
@IsBoolean()
isAdmin: boolean;

@IsOptional()
profilePictureUrl?: string;
}

0 comments on commit fec8192

Please sign in to comment.