@nestjs/common#Body TypeScript Examples

The following examples show how to use @nestjs/common#Body. 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: plugin-newsletter.controller.ts    From Cromwell with MIT License 7 votes vote down vote up
@Post('subscribe')
    /** Use ThrottlerGuard to limit number of requests from one IP address. Allow max 4 requests in 20 seconds: */
    @UseGuards(ThrottlerGuard)
    @Throttle(4, 20)
    @ApiOperation({ description: 'Post email to subscribe for newsletters' })
    @ApiResponse({
        status: 200,
        type: Boolean,
    })
    @ApiBody({ type: PluginNewsletterSubscription })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async placeSubscription(@Body() input: PluginNewsletterSubscription): Promise<boolean | undefined> {
        const email = input?.email;
        if (!email || !/\S+@\S+\.\S+/.test(email)) {
            throw new HttpException(`Invalid email`, HttpStatus.BAD_REQUEST);
        }

        const hasSubscribed = await getManager().findOne(PluginNewsletter, {
            where: {
                email
            }
        });
        if (hasSubscribed) return true;

        const newsletter = new PluginNewsletter();
        newsletter.email = email;
        await getManager().save(newsletter);
        return true;
    }
Example #2
Source File: RemixController.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
@All("*")
  handler(
    @Req() request: Request,
    @Res() response: Response,
    @Next() next: NextFunction,
    @Body() body: any
  ) {
    if (this.isStaticAsset(request)) return next();
    this.purgeRequireCacheInDev();

    return createRequestHandler({
      // `remix build` and `remix dev` output files to a build directory, you need
      // to pass that build to the request handler
      build: require(this.remixHandlerPath),

      // return anything you want here to be available as `context` in your
      // loaders and actions. This is where you can bridge the gap between Remix
      // and your server
      getLoadContext: () => ({
        actions: this.actions,
        loaders: this.loaders,
      }),
    })(request, response, next);
  }
Example #3
Source File: blocks.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@ApiExcludeEndpoint()
  @Post('disconnect')
  @UseGuards(ApiKeyGuard)
  async disconnect(
    @Body(
      new ValidationPipe({
        errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        transform: true,
      }),
    )
    { sequence_gt: sequenceGt }: DisconnectBlocksDto,
    @Res() res: Response,
  ): Promise<void> {
    await this.blocksService.disconnectAfter(sequenceGt);
    res.sendStatus(HttpStatus.OK);
  }
Example #4
Source File: weather-city.controller.ts    From life-helper-backend with MIT License 6 votes vote down vote up
/**
   * 新增一个天气城市
   *
   * @param userId 用户 ID
   * @param body 请求数据
   */
  @Post()
  async add(@User('id') userId: number, @Body() body: WxChooseLocationResult): Promise<AddResponseDto> {
    const weatherCity = await this.weatherCityService.add(userId, body)
    return plainToClass(AddResponseDto, weatherCity)
  }
Example #5
Source File: resources.controller.ts    From pandaid with MIT License 6 votes vote down vote up
@Post()
  @HttpCode(204)
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(Role.ADMIN, Role.SUPERVISOR)
  public create(@Body() createRequestRequest: ResourceBase) {
    const id = this.resourcesService.getResources().length
    this.resourcesService.addResource({
      id: id,
      quantityCovered: 0,
      state: ResourceStates.OPEN,
      name: createRequestRequest.name,
      quantity: createRequestRequest.quantity,
      price: createRequestRequest.price,
      beneficiary: createRequestRequest.beneficiary,
      contactPerson: createRequestRequest.contactPerson,
      deadline: createRequestRequest.deadline
    })
  }
Example #6
Source File: register.controller.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
@Post()
    register(
        @Body() registerDto: RegisterDto,
        @Res() res: Response): Observable<Response> {
        const username = registerDto.username;

        return this.userService.existsByUsername(username).pipe(
            mergeMap(exists => {
                if (exists) {
                    throw new ConflictException(`username:${username} is existed`)
                }
                else {
                    const email = registerDto.email;
                    return this.userService.existsByEmail(email).pipe(
                        mergeMap(exists => {
                            if (exists) {
                                throw new ConflictException(`email:${email} is existed`)
                            }
                            else {
                                return this.userService.register(registerDto).pipe(
                                    map(user =>
                                        res.location('/users/' + user.id)
                                            .status(201)
                                            .send()
                                    )
                                );
                            }
                        })
                    );
                }
            })
        );
    }
Example #7
Source File: product.controller.ts    From nest-js-products-api with MIT License 6 votes vote down vote up
@Put(':id')
  public async updateProduct(
    @Res() request,
    @Param('id') id: string,
    @Body() product: Product,
  ): Promise<any> {
    const productUpdated = await this.updateProductUseCase.handler(id, product);
    return request.status(HttpStatus.OK).json(productUpdated);
  }
Example #8
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 #9
Source File: user.controller.ts    From edu-server with MIT License 6 votes vote down vote up
@Put('/enrolledCourses/:courseId')
  @ApiOperation({ summary: 'user updating enrolled courses' })
  @ApiCreatedResponse(responsedoc.updateEnrolledCourses)
  async updateEnrolledCourses(
    @Param('courseId') courseId: Schema.Types.ObjectId,
    @Body() updateEnrolledDto: UpdateEnrolledDTO,
  ) {
    return await this.userService.updateCourse(updateEnrolledDto, courseId);
  }
Example #10
Source File: users.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiResponse({ type: UserDto, status: HttpStatus.CREATED })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  @ApiBearerAuth()
  async create(@Body() input: CreateUserDto): Promise<UserDto> {
    const exist = await this.usersService.findOneAsync({
      title: input.email.toLowerCase()
    });
    if (exist) {
      throw new ConflictException(
        `User with the email "${exist.email}" already exists`
      );
    }
    return super.create(input);
  }
Example #11
Source File: organizations.controller.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
@Post(':name/comments')
  @Header('Content-Type', 'application/json')
  async createOrganizationComment(@Param('name') name: string, @Body() comment: CommentDto): Promise<Comment> {
    this.logger.info('OrganizationController#createOrganizationComment.call', name)

    const organization: Organization = await this.organizationsService
      .findByName({
        name
      })
      .toPromise()

    if (!organization) throw new NotFoundException('NOT_FOUND', 'Organization not found.')

    const result: Comment = await this.commentsService
      .create({
        ...comment,
        organization: organization.id
      })
      .toPromise()

    this.logger.info('OrganizationController#createOrganizationComment.result', result)

    return result
  }
Example #12
Source File: users.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiNestNotFoundResponse('No user was found with the specified id')
  @ApiOperation({ summary: 'Updates the access level of a user' })
  @ApiParam({ name: 'id', example: 1 })
  @OverrideLevelAccess(AdminLevel.SuperAdmin)
  @Put(':id/level')
  setAdminLevel(
    @Param('id', ParseIntPipe) id: number,
    @Body() setAdminLevelDto: SetAdminLevelDto,
  ): Promise<void> {
    return this.usersService.setAdminLevel(id, setAdminLevelDto.level);
  }
Example #13
Source File: paddle.controller.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@Post('paddle-webhook')
  @UseInterceptors(MorganInterceptor('combined'))
  async paddleWebhook(
    @Body() body: PaddleEvent,
    @Res() response: Response
  ): Promise<void> {
    await this.paddleService.handlePaddleWebhook(body);
    response.sendStatus(200);
  }
Example #14
Source File: user.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
@Post('/register')
  @ApiCreatedResponse({
    description: 'Created user object as response',
    type: User,
  })
  @ApiBadRequestResponse({ description: 'User cannot register. Try again!' })
  async doUserRegistration(
    @Body(SETTINGS.VALIDATION_PIPE)
    userRegister: UserRegisterRequestDto,
  ): Promise<User> {
    return await this.userService.doUserRegistration(userRegister);
  }
Example #15
Source File: app.controller.ts    From nest_transact with MIT License 6 votes vote down vote up
@Post('transfer')
  @ApiResponse({
    type: TransferOperationResultDto,
  })
  async makeRemittanceWithTransaction(@Body() remittanceDto: TransferParamsDTO) {
    return this.connection.transaction(manager => {
      return this.appService.withTransaction(manager)/* <-- this is interesting new thing */.makeTransfer(remittanceDto.userIdFrom, remittanceDto.userIdTo, remittanceDto.sum, remittanceDto.withError);
    });
  }
Example #16
Source File: DesktopConfigController.ts    From rewind with MIT License 6 votes vote down vote up
@Post()
  async saveOsuStablePath(@Res() res: Response, @Body() { osuStablePath }: UpdateOsuStablePathDto) {
    this.logger.log(`Received request to update the OsuStablePath to ${osuStablePath}`);

    const sanityCheckPassed = await osuFolderSanityCheck(osuStablePath);
    if (sanityCheckPassed) {
      await this.desktopConfigService.saveOsuStablePath(osuStablePath);
      res.status(200).json({ result: "OK" });
    } else {
      res.status(400).json({ error: `Given folder '${osuStablePath}' does not seem to be a valid osu!stable folder` });
    }
  }
Example #17
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 #18
Source File: plugin.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Post('settings')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator')
    @ApiOperation({
        description: 'Saves JSON settings of a plugin by pluginName.',
        parameters: [{ name: 'pluginName', in: 'query', required: true }]
    })
    @ApiResponse({
        status: 200,
        type: Boolean
    })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async savePluginSettings(@Query('pluginName') pluginName: string, @Body() input): Promise<boolean> {
        logger.log('PluginController::savePluginSettings');

        if (!pluginName)
            throw new HttpException(`Invalid plugin name: ${pluginName}`, HttpStatus.NOT_ACCEPTABLE);

        return savePluginSettings(pluginName, input);
    }
Example #19
Source File: project-notes.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Post('/')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: ProjectNote })
  createOneProjectNote(
    @Body() dto: ProjectNote,
    @ParsedRequest() req: CrudRequest,
    @Request() request: any,
  ): Promise<ProjectNote> {
    const { id } = request.user;
    dto.userId = id;
    return this.service.createOne(req, dto);
  }
Example #20
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiMovedPermanentlyResponse({ description: 'Redirects to home' })
  @ApiInternalServerErrorResponse({ description: 'Returns the 500 error' })
  @Post('/register')
  @Redirect('/v1/auth/login')
  public async create(@Body() params: SignUpDto): Promise<void> {
    const { email, id } = await this.usersService.create(params);
    const token = await this.authService.createVerifyToken(id);
    await this.mailerService.sendMail({
      to: email,
      from: this.configService.get<string>('MAILER_FROM_EMAIL'),
      subject: 'Email Verification',
      template: `${process.cwd()}/public/views/mailer/templates/verify-password`,
      context: {
        token,
        email,
        host: this.configService.get<number>('SERVER_HOST'),
      },
    });
  }
Example #21
Source File: app.controller.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@Post('auth/register')
  async register(@Body() body: Partial<UserEntity>) {
    try {
      const salt = await genSalt(10);
      const { password, ...reset } = body;
      const u: Partial<UserEntity> = {
        salt,
        ...reset,
        password: hashSync(password, salt),
        role: Roles.user,
      };
      const user = await this.authService.register(u);
      const logedInUser = await this.authService.login(user);
      delete logedInUser.password;
      delete logedInUser.salt;
      return logedInUser;
    } catch (error) {
      throw error;
    }
  }
Example #22
Source File: user.controller.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
@Put(':id')
  @ApiOperation({ summary: '유저 정보 수정 API' })
  @ApiOkResponse({
    description: 'Id가 일치하는 유저 정보를 수정한다.',
    type: User,
  })
  async update(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() requestDto: UserUpdateRequestDto,
    @Res() res: Response,
  ) {
    const updatedUser = await this.userService.updateUser(id, requestDto);

    return res.status(HttpStatus.OK).json(updatedUser);
  }
Example #23
Source File: theme.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Post('palette')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator')
    @ApiOperation({
        description: `Update palette of an active theme`,
        parameters: [
            { name: 'themeName', in: 'query', required: true },
        ],
    })
    @ApiResponse({
        status: 201,
        type: Boolean
    })
    @ApiBody({ type: ThemePaletteDto })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async saveThemePalette(@Body() input: ThemePaletteDto, @Query('themeName') themeName: string): Promise<boolean> {
        logger.log('ThemeController::saveThemePalette');
        if (input && typeof input === 'object') {
            return await this.themeService.saveThemePalette(input, themeName);
        }
        return false;
    }