@nestjs/common#UsePipes TypeScript Examples

The following examples show how to use @nestjs/common#UsePipes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: test.controller.ts    From nestjs-form-data with MIT License 6 votes vote down vote up
@Post('auto-delete-single-file')
  @UsePipes(ValidationPipe)
  @FormDataRequest({ autoDeleteFile: true, storage: FileSystemStoredFile })
  @HttpCode(HttpStatus.OK)
  uploadSingleWithAutoDeleteFile(@Body() singleFileDto: UploadSingleFileFSStorageDto) {
    return {
      filename: singleFileDto.file.originalName,
      mimetype: singleFileDto.file.mimetype,
      path: singleFileDto.file.path,
    };
  }
Example #2
Source File: question.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
@Post('')
  @UsePipes(ValidationPipe)
  @ApiCreatedResponse({
    description: 'Question added to a quiz',
    type: Question,
  })
  async saveQuestion(@Body() question: CreateQuestionDto): Promise<Question> {
    const quiz = await this.quizService.getQuizById(question.quizId);
    return await this.questionService.createQuestion(question, quiz);
  }
Example #3
Source File: option.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
@Post('')
  @UsePipes(ValidationPipe)
  @ApiCreatedResponse({
    description: 'The option that got created',
    type: Option,
  })
  async saveOptionToQuestion(@Body() createOption: CreateOptionDto) {
    const question = await this.questionService.findQuestionById(
      createOption.questionId,
    );
    const option = await this.optionService.creatOption(createOption, question);
    return { question, createOption, option };
  }
Example #4
Source File: user.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
/**
   * Responds to: _POST(`/`)_
   *
   * Creates a new user based on data from [[CreateUserDto]].
   */
  @Post()
  @UsePipes(ValidationPipe)
  create(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }
Example #5
Source File: application.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
//   @Put(':id')
  //   @UsePipes(ValidationPipe)
  //   update(@Param('id') id: string, @Body() updateApplicationDto: UpdateApplicationDto) {
  //     return this.applicationService.update(+id, updateApplicationDto);
  //   }

  @Delete(':id')
  @UsePipes(ValidationPipe)
  async remove(@Request() req, @Param('id') id: string) {
    const user: AuthorizedUser = req.user;
    const application = await this.applicationService.findOneById(id);
    if (application === null) {
      throw new NotFoundException();
    }
    if (String(application.admin) !== user.id) {
      throw new UnauthorizedException();
    }
    await application.remove();
    return 'removed';
  }
Example #6
Source File: application.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Get(':id')
  @UsePipes(ValidationPipe)
  async findOne(@Request() req, @Param('id') id: string) {
    const user: AuthorizedUser = req.user;
    const application = await this.applicationService.findOneById(id);
    if (String(application.admin) !== user.id) {
      throw new UnauthorizedException();
    }
    delete application.admin;
    return application;
  }
Example #7
Source File: test.controller.ts    From nestjs-form-data with MIT License 6 votes vote down vote up
@Post('single-file')
  @UsePipes(ValidationPipe)
  @FormDataRequest()
  @HttpCode(HttpStatus.OK)
  uploadSingleFile(@Body() singleFileDto: UploadSingleFileDto) {
    return {
      filename: singleFileDto.file.originalName,
      mimetype: singleFileDto.file.mimetype,
    };
  }
Example #8
Source File: test.controller.ts    From nestjs-form-data with MIT License 6 votes vote down vote up
@Post('array-files')
  @UsePipes(ValidationPipe)
  @FormDataRequest()
  @HttpCode(HttpStatus.OK)
  uploadArrayFiles(@Body() arrayFilesDto: UploadArrayFilesDto) {
    return arrayFilesDto.files.map(file => {
      return {
        filename: file.originalName,
        mimetype: file.mimetype,
      };
    });
  }
Example #9
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Post('/register')
  @UsePipes(ValidationPipe)
  async processRegisterPage(@Res() res: Response, @Body() createUserDtoWithCaptcha: CreateUserDtoWithCaptcha) {
    try {
      const response = await this.userService.create(createUserDtoWithCaptcha);
      const templateData = {
        server: {
          message: 'please check your email for verification link',
        },
      };
      // this.mailerService.sendEmail(response.collegeEmail);
      return res.render('account/register', { templateData, project_name: appData.Name });
    } catch (e) {
      const templateData = {
        server: e.response,
      };
      return res.render('account/register', { templateData, project_name: appData.Name });
    }
  }
Example #10
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Post('/password/request')
  @UsePipes(ValidationPipe)
  async processRequestPage(@Res() res: Response, @Body() requestPasswordResetDto: RequestPasswordResetDto) {
    try {
      const response = await this.userService.request(requestPasswordResetDto);
      const templateData = {
        server: {
          message: 'please check your email for password reset link',
        },
      };
      this.mailerService.sendPasswordResetLink(response.collegeEmail);
      return res.render('account/login', { templateData, project_name: appData.Name });
    } catch (e) {
      const templateData = {
        server: e.response,
      };
      return res.render('account/login', templateData);
    }
  }
Example #11
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Post('login')
  @UsePipes(ValidationPipe)
  async processLoginPage(@Res() res: Response, @Body() loginDto: LoginDto) {
    try {
      const user = await this.userService.login(loginDto);
      const jwtData = { id: user._id, email: user.collegeEmail };
      const cookieData = await this.authService.generateJwt(jwtData);
      res.cookie('vitAuth', cookieData);
      //   res.render('profile/homepage', user);
      res.redirect('./../dashboard');
    } catch (e) {
      return res.render('account/login', { server: { message: e.message }, project_name: appData.Name });
    }
  }
Example #12
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
/**
   * NON OAUTH FLOW HANDLERS :: Normal Operations
   */
  /**
   * to display login page
   */
  @Get('login')
  @UsePipes(
    new ValidationPipe({
      disableErrorMessages: false,
    }),
  )
  async showLoginPage(@Res() res: Response) {
    try {
      return res.render('account/login', { project_name: appData.Name });
    } catch (e) {
      return res.render('error', e.response);
    }
  }
Example #13
Source File: test.controller.ts    From nestjs-form-data with MIT License 6 votes vote down vote up
@Post('auto-delete-single-file-busboy')
  @UsePipes(ValidationPipe)
  @FormDataRequest({ autoDeleteFile: true, storage: FileSystemStoredFile, limits: {fileSize: 5}})
  @HttpCode(HttpStatus.OK)
  uploadSingleWithAutoDeleteFileBusboySizeLimit(@Body() singleFileDto: UploadSingleFileFSStorageDto) {
    return {
      filename: singleFileDto.file.originalName,
      mimetype: singleFileDto.file.mimetype,
      path: singleFileDto.file.path,
    };
  }
Example #14
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
/**
   * OAUTH FLOW HANDLERS :: Displayed only when invoded mid-way auth flow
   */

  /**
   * to display login form on client-initiated-auth
   */
  @Get('o/login')
  @UsePipes(
    new ValidationPipe({
      disableErrorMessages: false,
    }),
  )
  async showLoginPageAsAuth(@Res() res: Response, @Query() incomingAuthDto: IncomingAuthDto) {
    const { client_id } = incomingAuthDto;
    try {
      const applicationDetails = await this.accountService.validateAccessRequest(incomingAuthDto);
      return res.render('account/o/login', { app: applicationDetails, project_name: appData.Name });
    } catch (e) {
      this.logger.error(`${e.message} for ${client_id}`);
      return res.render('error', e.response);
    }
  }
Example #15
Source File: versions.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@ApiExcludeEndpoint()
  @UseGuards(ApiKeyGuard)
  @UsePipes(
    new ValidationPipe({
      errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
      transform: true,
    }),
  )
  @Post()
  async updateVersion(
    @Body()
    { version }: CreateVersionDto,
  ): Promise<SerializedVersion> {
    return serializedVersionFromRecord(
      await this.versionsService.create(version),
    );
  }
Example #16
Source File: admins.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
// TODO @yashmurty : Investigate pagination for this later.
  @UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Get all admin users' })
  @ApiOkResponse({ type: [Admin] })
  @Get('/users')
  async getAdminUsers(@Request() req, @Query() query: PaginationParamsDto): Promise<Admin[]> {
    const requestAdminUser: RequestAdminUser = req.user
    return this.adminsService.findAllAdminUsers(requestAdminUser, query.limit, query.offset)
  }
Example #17
Source File: admins.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Create new admin user' })
  @ApiOkResponse({ type: NoResponseBody })
  @ApiBadRequestResponse()
  @ApiUnauthorizedResponse()
  @ApiConflictResponse()
  @Post('/users')
  @HttpCode(200)
  async postAdminUser(
    @Request() req,
    @Body() createAdminRequest: CreateAdminRequestDto
  ): Promise<NoResponseBody> {
    const requestAdminUser: RequestAdminUser = req.user
    await this.adminsService.createOneAdminUser(requestAdminUser, createAdminRequest)

    return {}
  }
Example #18
Source File: auth.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Login endpoint for normal user' })
  @ApiOkResponse({ type: NoResponseBody })
  @ApiBadRequestResponse()
  @UseGuards(FirebaseNormalUserLoginGuard)
  @Post('login')
  @HttpCode(200)
  async loginFirebase(
    @Request() req,
    @Body() loginNormalUserRequestDto: LoginNormalUserRequestDto
  ): Promise<NoResponseBody> {
    await this.authService.normalUserLogin(req.user, loginNormalUserRequestDto)
    return {}
  }
Example #19
Source File: prefectures.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Creates any missing prefectures' })
  @ApiOkResponse({ type: NoResponseBody })
  @ApiBadRequestResponse()
  @Post('/prefectures')
  @HttpCode(200)
  async postPrefecture(@Request() req): Promise<void> {
    const requestAdminUser: RequestAdminUser = req.user

    return this.prefecturesService.setupInitialPrefectures(requestAdminUser)
  }
Example #20
Source File: prefectures.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Update prefecture' })
  @ApiOkResponse({ type: NoResponseBody })
  @ApiNotFoundResponse()
  @Patch('/prefectures/:prefectureId')
  async patchMeProfile(
    @Request() req,
    @Param('prefectureId') prefectureId: number,
    @Body() updatePrefectureRequest: UpdatePrefectureRequestDto
  ): Promise<NoResponseBody> {
    const requestAdminUser: RequestAdminUser = req.user
    updatePrefectureRequest.prefectureId = prefectureId

    await this.prefecturesService.updateOnePrefecture(requestAdminUser, updatePrefectureRequest)

    return {}
  }
Example #21
Source File: users.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Update user profile' })
  @ApiOkResponse({ type: NoResponseBody })
  @Patch('/me/profile')
  async patchMeProfile(
    @Request() req,
    @Body() updateUserProfileDto: UpdateUserProfileDto
  ): Promise<void> {
    updateUserProfileDto.userId = req.user.uid
    return this.usersService.updateUserProfile(updateUserProfileDto)
  }
Example #22
Source File: users.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Give the user a positive flag by health-center-token' })
  @ApiOkResponse({ type: NoResponseBody })
  @ApiBadRequestResponse()
  @ApiNotFoundResponse()
  @Post('/me/health_center_tokens')
  @HttpCode(200)
  async createDiagnosisKeys(
    @Request() req,
    @Body() createDiagnosisKeys: CreateDiagnosisKeysDto
  ): Promise<NoResponseBody> {
    await this.usersService.createDiagnosisKeys(createDiagnosisKeys)
    return {}
  }
Example #23
Source File: users.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Let the users themselves eliminate the positive flag' })
  @ApiOkResponse({ type: NoResponseBody })
  @ApiBadRequestResponse()
  @ApiNotFoundResponse()
  @Delete('/me/diagnosis_keys')
  @HttpCode(200)
  async deleteDiagnosisKeys(
    @Request() req,
    @Body() deleteDiagnosisKeys: DeleteDiagnosisKeysDto
  ): Promise<NoResponseBody> {
    await this.usersService.deleteDiagnosisKeys(deleteDiagnosisKeys)
    return {}
  }
Example #24
Source File: tag.controller.ts    From whispr with MIT License 5 votes vote down vote up
@Patch(':id')
  @HttpCode(204)
  @UsePipes(new ValidationPipe({ whitelist: true }))
  async updateTag(@Param('id') id: string, @Body() tag: TagInputType): Promise<ITag> {
    return this.tagService.update(id, tag);
  }
Example #25
Source File: quiz.controller.ts    From nest-js-quiz-manager with MIT License 5 votes vote down vote up
@ApiCreatedResponse({ description: 'The quiz that got created', type: Quiz })
  @Post('/create')
  @UsePipes(ValidationPipe)
  @UseGuards(RolesGuard)
  @Roles('admin')
  async createQuiz(@Body() quizData: CreateQuizDto): Promise<Quiz> {
    return await this.quizService.createNewQuiz(quizData);
  }
Example #26
Source File: auth.controller.ts    From uniauth-backend with MIT License 5 votes vote down vote up
@Post('login')
  @UsePipes(ValidationPipe)
  async login(@Body() loginDto: LoginDto): Promise<any> {
    return this.authService.checkLogin(loginDto);
  }
Example #27
Source File: application.controller.ts    From uniauth-backend with MIT License 5 votes vote down vote up
@Get()
  @UsePipes(ValidationPipe)
  findAll() {
    return this.applicationService.findAll();
  }
Example #28
Source File: application.controller.ts    From uniauth-backend with MIT License 5 votes vote down vote up
@Post()
  @UseGuards(JwtAuthGuard)
  @UsePipes(ValidationPipe)
  create(@Request() req, @Body() createApplicationDto: CreateApplicationDto) {
    const user: LoggedInUser = req.user;
    this.logger.verbose(`${user.email} creating ${createApplicationDto.name}`);
    return this.applicationService.create(createApplicationDto, user);
  }
Example #29
Source File: account.controller.ts    From uniauth-backend with MIT License 5 votes vote down vote up
@Post('o/access')
  @UsePipes(ValidationPipe)
  async shareUserDetailsViaAuth(@Body() accessUserDetailsDto: AccessUserDetailsDto) {
    return this.accountService.provideUserDetailOnAccess(accessUserDetailsDto);
  }