Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added posts crud #14

Merged
merged 5 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.8",
"@prisma/client": "^5.13.0",
"class-validator": "^0.14.1",
"nestjs-prisma": "^0.23.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { PrismaModule } from 'nestjs-prisma';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { PostsModule } from './posts/posts.module';
import { UserModule } from './user/user.module';

@Module({
imports: [PrismaModule.forRoot({ isGlobal: true }), UserModule, AuthModule],
imports: [PrismaModule.forRoot({ isGlobal: true }), UserModule, AuthModule, PostsModule],
controllers: [AppController],
providers: [AppService],
})
Expand Down
5 changes: 5 additions & 0 deletions apps/backend/src/posts/dto/create-post.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { OmitType } from '@nestjs/swagger';

import { PostEntity } from '../entities/post.entity';

export class CreatePostDto extends OmitType(PostEntity, ['id', 'author', 'createdAt', 'updatedAt']) {}
11 changes: 11 additions & 0 deletions apps/backend/src/posts/dto/get-posts.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { IsInt, IsOptional, Min } from 'class-validator';
export class GetPostsDto {
@IsOptional()
@IsInt()
@Min(0)
page: number;
@IsOptional()
@IsInt()
@Min(1)
page_size: number;
}
5 changes: 5 additions & 0 deletions apps/backend/src/posts/dto/simple-post.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { OmitType } from '@nestjs/swagger';

import { PostEntity } from '../entities/post.entity';

export class SimplePostDto extends OmitType(PostEntity, ['author']) {}
5 changes: 5 additions & 0 deletions apps/backend/src/posts/dto/update-post.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PartialType } from '@nestjs/swagger';

import { CreatePostDto } from './create-post.dto';

export class UpdatePostDto extends PartialType(CreatePostDto) {}
14 changes: 14 additions & 0 deletions apps/backend/src/posts/entities/post.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { User } from 'src/user/entities/user.entity';

export class PostEntity {
id: number;
title: string;
content: string;
preview: string;
visible: boolean = true;
@ApiProperty({ type: User })
author: User;
createdAt: Date;
updatedAt: Date;
}
52 changes: 52 additions & 0 deletions apps/backend/src/posts/posts.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { CurrentUser } from '@kir-dev/passport-authsch';
import { Body, Controller, Delete, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth } from '@nestjs/swagger';
import { Role, User } from '@prisma/client';
import { Roles } from 'src/auth/decorators/Roles.decorator';
import { RolesGuard } from 'src/auth/roles.guard';

import { CreatePostDto } from './dto/create-post.dto';
import { GetPostsDto } from './dto/get-posts.dto';
import { SimplePostDto } from './dto/simple-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { PostsService } from './posts.service';

@Controller('posts')
export class PostsController {
constructor(private readonly postsService: PostsService) {}

@UseGuards(AuthGuard('jwt'), RolesGuard)
@ApiBearerAuth()
@Roles(Role.BODY_ADMIN, Role.BODY_MEMBER)
@Post()
create(@Body() createPostDto: CreatePostDto, @CurrentUser() user: User) {
return this.postsService.create(createPostDto, user);
}

@Get()
async findAll(@Query() getPostsDto: GetPostsDto): Promise<SimplePostDto[]> {
return this.postsService.findAll(getPostsDto);
}

@Get(':id')
async findOne(@Param('id') id: string) {
return this.postsService.findOne(Number(id));
}

@UseGuards(AuthGuard('jwt'), RolesGuard)
@Roles(Role.BODY_ADMIN, Role.BODY_MEMBER)
@ApiBearerAuth()
@Patch(':id')
update(@Param('id') id: string, @Body() updatePostDto: UpdatePostDto) {
return this.postsService.update(Number(id), updatePostDto);
}

@UseGuards(AuthGuard('jwt'), RolesGuard)
@Roles(Role.BODY_ADMIN, Role.BODY_MEMBER)
@ApiBearerAuth()
@Delete(':id')
remove(@Param('id') id: string) {
return this.postsService.remove(Number(id));
}
}
10 changes: 10 additions & 0 deletions apps/backend/src/posts/posts.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';

import { PostsController } from './posts.controller';
import { PostsService } from './posts.service';

@Module({
controllers: [PostsController],
providers: [PostsService],
})
export class PostsModule {}
93 changes: 93 additions & 0 deletions apps/backend/src/posts/posts.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { BadRequestException, Injectable, InternalServerErrorException, NotFoundException } from '@nestjs/common';
import { Prisma, User } from '@prisma/client';
import { PrismaService } from 'nestjs-prisma';

import { CreatePostDto } from './dto/create-post.dto';
import { GetPostsDto } from './dto/get-posts.dto';
import { UpdatePostDto } from './dto/update-post.dto';

@Injectable()
export class PostsService {
constructor(private readonly prisma: PrismaService) {}
create(createPostDto: CreatePostDto, user: User) {
return this.prisma.post.create({
data: {
...createPostDto,
author: {
connect: {
authSchId: user.authSchId,
},
},
},
});
}

findAll(getPostsDto: GetPostsDto) {
const skip = getPostsDto.page * getPostsDto.page_size;
return this.prisma.post.findMany({
skip,
take: Number(getPostsDto.page_size),
});
}

findOne(id: number) {
try {
return this.prisma.post.findUniqueOrThrow({
where: {
id,
},
include: {
author: true,
},
});
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2025') {
throw new NotFoundException('This post does not exist.');
}
throw new InternalServerErrorException('An error occurred.');
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

classic mistake: trying to catch an error in an async call without awaiting it

}

async update(id: number, updatePostDto: UpdatePostDto) {
try {
return await this.prisma.post.update({
where: {
id,
},
data: updatePostDto,
});
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
switch (e.code) {
case 'P2000':
throw new BadRequestException('The content is too long.');
case 'P2025':
throw new NotFoundException('This post does not exist.');
}
}
throw new InternalServerErrorException('An error occurred.');
}
}

async remove(id: number) {
try {
return this.prisma.post.delete({
where: {
id,
},
});
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
switch (e.code) {
case 'P2000':
throw new BadRequestException('The content is too long.');
case 'P2025':
throw new NotFoundException('This post does not exist.');
}
}
throw new InternalServerErrorException('An error occurred.');
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same

}
20 changes: 20 additions & 0 deletions apps/backend/src/user/entities/user.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Application, ApplicationPeriod, Post } from '@prisma/client';

export class User {
authSchId: string;
role: string;
fullName: string;
email: string;
isSchResident: boolean;
isActiveVikStudent: boolean;
roomNumber: number;
profileImage: any;
canHelpNoobs: boolean;
publicDesc: string;
createdAt: Date;
updatedAt: Date;
profileSeenAt: Date;
applicationPeriods: ApplicationPeriod[];
applications: Application[];
posts: Post[];
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
{
"dependencies": {
"@nestjs/mapped-types": "*"
},
"name": "next-nest-template",
"version": "0.0.0",
"description": "Template repository for full-stack NestJS + NextJS projects",
Expand Down
26 changes: 25 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@
"@types/jsonwebtoken" "9.0.5"
jsonwebtoken "9.0.2"

"@nestjs/[email protected]":
"@nestjs/mapped-types@*", "@nestjs/mapped-types@2.0.5":
version "2.0.5"
resolved "https://registry.yarnpkg.com/@nestjs/mapped-types/-/mapped-types-2.0.5.tgz#485d6b44e19779c98d04e52bd1d2bcc7001df0ea"
integrity sha512-bSJv4pd6EY99NX9CjBIyn4TVDoSit82DUZlL4I3bqNfy5Gt+gXTa86i3I/i0iIV9P4hntcGM5GyO+FhZAhxtyg==
Expand Down Expand Up @@ -676,6 +676,11 @@
"@types/node" "*"
"@types/send" "*"

"@types/validator@^13.11.8":
version "13.12.0"
resolved "https://registry.yarnpkg.com/@types/validator/-/validator-13.12.0.tgz#1fe4c3ae9de5cf5193ce64717c99ef2fa7d8756f"
integrity sha512-nH45Lk7oPIJ1RVOF6JgFI6Dy0QpHEzq4QecZhvguxYPDwT8c93prCMqAtiIttm39voZ+DDR+qkNnMpJmMBRqag==

"@typescript-eslint/eslint-plugin@^7.7.1":
version "7.7.1"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.7.1.tgz#50a9044e3e5fe76b22caf64fb7fc1f97614bdbfd"
Expand Down Expand Up @@ -1429,6 +1434,15 @@ chrome-trace-event@^1.0.2:
resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz#1015eced4741e15d06664a957dbbf50d041e26ac"
integrity sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==

class-validator@^0.14.1:
version "0.14.1"
resolved "https://registry.yarnpkg.com/class-validator/-/class-validator-0.14.1.tgz#ff2411ed8134e9d76acfeb14872884448be98110"
integrity sha512-2VEG9JICxIqTpoK1eMzZqaV+u/EiwEJkMGzTrZf6sU/fwsnOITVgYJ8yojSy6CaXtO9V0Cc6ZQZ8h8m4UBuLwQ==
dependencies:
"@types/validator" "^13.11.8"
libphonenumber-js "^1.10.53"
validator "^13.9.0"

class-variance-authority@^0.7.0:
version "0.7.0"
resolved "https://registry.yarnpkg.com/class-variance-authority/-/class-variance-authority-0.7.0.tgz#1c3134d634d80271b1837452b06d821915954522"
Expand Down Expand Up @@ -3176,6 +3190,11 @@ levn@^0.4.1:
prelude-ls "^1.2.1"
type-check "~0.4.0"

libphonenumber-js@^1.10.53:
version "1.11.4"
resolved "https://registry.yarnpkg.com/libphonenumber-js/-/libphonenumber-js-1.11.4.tgz#e63fe553f45661b30bb10bb8c82c9cf2b22ec32a"
integrity sha512-F/R50HQuWWYcmU/esP5jrH5LiWYaN7DpN0a/99U8+mnGGtnx8kmRE+649dQh3v+CowXXZc8vpkf5AmYkO0AQ7Q==

lilconfig@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/lilconfig/-/lilconfig-2.1.0.tgz#78e23ac89ebb7e1bfbf25b18043de756548e7f52"
Expand Down Expand Up @@ -4915,6 +4934,11 @@ v8-compile-cache-lib@^3.0.1:
resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf"
integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==

validator@^13.9.0:
version "13.12.0"
resolved "https://registry.yarnpkg.com/validator/-/validator-13.12.0.tgz#7d78e76ba85504da3fee4fd1922b385914d4b35f"
integrity sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==

vary@^1, vary@~1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc"
Expand Down