Skip to content

Commit

Permalink
feat: post service
Browse files Browse the repository at this point in the history
  • Loading branch information
recepkefelii committed Mar 12, 2023
1 parent 2485ab8 commit 06115e2
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
16 changes: 16 additions & 0 deletions src/post/post.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Controller, Get, Param } from '@nestjs/common';
import { PostService } from './post.service';

@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) { }
@Get('all')
async getAllPost() {
return this.postService.getAllPost()
}

@Get(":id")
async getPostById(@Param('id') id: string){
return this.postService.getPostById(id)
}
}
11 changes: 10 additions & 1 deletion src/post/post.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { Module } from "@nestjs/common";
import { CreatePostModule } from "./create-post/create.post.module";
import { UpdatePostController } from "./update-post/update.post.controller";
import { UpdatePostModule } from "./update-post/update.post.module";
import { PostService } from './post.service';
import { PostController } from './post.controller';
import { MongooseModule } from "@nestjs/mongoose";
import { Post, PostSchema } from "./schemas/post.schema";

@Module({
imports: [CreatePostModule]
imports: [MongooseModule.forFeature([{ name: Post.name, schema: PostSchema }]),
CreatePostModule, UpdatePostModule],
providers: [PostService],
controllers: [PostController]
})
export class PostModule { }
25 changes: 25 additions & 0 deletions src/post/post.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { BadRequestException, HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { HttpErrorByCode } from '@nestjs/common/utils/http-error-by-code.util';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Post, PostDocument } from './schemas/post.schema';

@Injectable()
export class PostService {
constructor(@InjectModel(Post.name) private postModel: Model<PostDocument>) { }
async getAllPost(): Promise<Post[]> {
try {
return await this.postModel.find()
} catch (error) {
throw new BadRequestException("cannot list posts")
}
}

async getPostById(id:string): Promise<Post>{
try {
return await this.postModel.findById(id)
} catch (error) {
throw new HttpException(`a post with this ${id} was not found`,HttpStatus.NOT_FOUND,)
}
}
}

0 comments on commit 06115e2

Please sign in to comment.