

export interface Post {
id: number;
title: string;
content: string;
author: string;
createdAt: Date;
updatedAt?: Date;
}
import { Injectable, NotFoundException } from '@nestjs/common';
import { Post } from './interface/post.interface';
@Injectable()
export class PostService {
private posts: Post[] = [
{
id: 1,
title: 'First Post',
content: 'My First Post....',
author: 'Nithin',
createdAt: new Date(),
},
];
findAll(): Post[] {
return this.posts;
}
findOne(id: number): Post {
const singlePost = this.posts.find((p) => p.id === id);
if (!singlePost) {
throw new NotFoundException(`Post with ${id} is not found`);
}
return singlePost;
}
crateOne(createPostData: Omit<Post, 'id' | 'createdAt'>): Post {
const newpost = {
id: this.getNextId(),
...createPostData,
createdAt: new Date(),
};
this.posts.push(newpost);
return newpost;
}
updateOne(
id: number,
updatePostData: Partial<Omit<Post, 'id' | 'createdAt'>>,
): Post {
const currentPostIndexToEdit = this.posts.findIndex((i) => i.id === id);
if (currentPostIndexToEdit === -1) {
throw new NotFoundException(`Post with ${id} is not found`);
}
this.posts[currentPostIndexToEdit] = {
...this.posts[currentPostIndexToEdit],
...updatePostData,
updatedAt: new Date(),
};
return this.posts[currentPostIndexToEdit];
}
remove(id: number): { message: string } {
const postIndex = this.posts.findIndex((post) => post.id === id);
if (postIndex === -1) {
throw new NotFoundException(`Post with ${id} is not found`);
}
this.posts.splice(postIndex, 1);
return { message: 'Post Deleted' };
}
private getNextId(): number {
return this.posts.length > 0
? Math.max(...this.posts.map((post) => post.id)) + 1
: 1;
}
}
import {
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
ParseIntPipe,
Post,
Put,
Query,
} from '@nestjs/common';
import { PostService } from './post.service';
import * as postInterface from './interface/post.interface';
@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) {}
@Get()
findAll(@Query('search') search?: string): postInterface.Post[] {
const extraclAllPosts = this.postService.findAll();
if (search) {
return extraclAllPosts.filter((singlePost) =>
singlePost.title.toLowerCase().includes(search.toLowerCase()),
);
}
return extraclAllPosts;
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number): postInterface.Post {
return this.postService.findOne(id);
}
@Post()
@HttpCode(HttpStatus.CREATED)
create(
@Body() createPostData: Omit<postInterface.Post, 'id' | 'createdAt'>,
): postInterface.Post {
return this.postService.crateOne(createPostData);
}
@Put(':id')
update(
@Param('id', ParseIntPipe) id: number,
@Body()
updatePostData: Partial<Omit<postInterface.Post, 'id' | 'createdAt'>>,
): postInterface.Post {
return this.postService.updateOne(id, updatePostData);
}
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
remove(@Param('id', ParseIntPipe) id: number): void {
this.postService.remove(id);
}
}
Get, Create, Put, Delete, Httpcode, HttpStatus, Body