From ef2e9c08f941ab9e59b39608a272cf507d7daeb3 Mon Sep 17 00:00:00 2001 From: ashleigh Date: Tue, 2 Oct 2018 17:03:17 +0100 Subject: [PATCH] Added user controller --- src/user/user.controller.ts | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/user/user.controller.ts diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts new file mode 100644 index 0000000..e964969 --- /dev/null +++ b/src/user/user.controller.ts @@ -0,0 +1,56 @@ +import {Controller, Get, Post, Put, Body, ValidationPipe, UnprocessableEntityException, Param, NotFoundException} from '@nestjs/common'; +import { UserEntity } from 'entities'; +import { Pagination } from 'paginate'; +import { UserService } from './user.service'; +import { UserModel } from 'models'; +import { UpdateResult } from 'typeorm'; + +@Controller('users') +export class UserController { + constructor(private readonly userService: UserService) {} + + @Get() + async index(): Promise> { + //TODO make PaginationOptionsInterface an object so it can be defaulted + return await this.userService.paginate(); + } + + @Post() + async store(@Body(new ValidationPipe()) user: UserModel): Promise { + //TODO check duplication + const emailExists = this.userService.findByEmail(user.email); + + if (emailExists) { + throw new UnprocessableEntityException; + } + + return await this.userService.create(user); + } + + @Put('/{id}') + async update(@Param('id') id: number, @Body(new ValidationPipe()) user: UserModel): Promise { + const userEntity = await this.userService.findById(id); + + if (!userEntity) { + throw new NotFoundException; + } + + return await this.userService.update({ + ...userEntity, + ...user, + }); + } + + @Get('/{id}') + async show(@Param('id') id :number): Promise { + const user = this.userService.findById(id); + + if (!user) { + throw new NotFoundException; + } + + return user; + } + + +} \ No newline at end of file