import { Controller, Get, Post, Put, Delete, Body, Param, Query, HttpCode, HttpStatus, } from '@nestjs/common';
interface User { id: number; name: string; email: string; }
interface CreateUserDto { name: string; email: string; }
interface UpdateUserDto { name?: string; email?: string; }
interface PaginationQuery { page: number; limit: number; }
@Controller('api/users') export class UsersController { private users: User[] = [];
@Get() findAll(@Query() query: PaginationQuery) { const { page = 1, limit = 10 } = query; return { data: this.users.slice((page - 1) * limit, page * limit), meta: { total: this.users.length, page, limit, }, }; }
@Get(':id') findOne(@Param('id') id: string) { const user = this.users.find((u) => u.id === +id); if (!user) { throw new Error('User not found'); } return user; }
@Post() @HttpCode(HttpStatus.CREATED) create(@Body() createUserDto: CreateUserDto) { const newUser: User = { id: this.users.length + 1, ...createUserDto, }; this.users.push(newUser); return newUser; }
@Put(':id') update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) { const userIndex = this.users.findIndex((u) => u.id === +id); if (userIndex === -1) { throw new Error('User not found'); } this.users[userIndex] = { ...this.users[userIndex], ...updateUserDto, }; return this.users[userIndex]; }
@Delete(':id') @HttpCode(HttpStatus.NO_CONTENT) remove(@Param('id') id: string) { const userIndex = this.users.findIndex((u) => u.id === +id); if (userIndex === -1) { throw new Error('User not found'); } this.users.splice(userIndex, 1); }
@Get(':userId/posts') getUserPosts(@Param('userId') userId: string) { return { userId: +userId, posts: [], }; }
@Post('search') @HttpCode(HttpStatus.OK) search(@Body('keyword') keyword: string) { return this.users.filter( (u) => u.name.includes(keyword) || u.email.includes(keyword), ); } }
|