@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: app.service.ts    From nr-apm-stack with Apache License 2.0 6 votes vote down vote up
/**
   * Handles the data received as a mock Kinesis event
   * @param data The data to pass into the parser
   * @param print If true, print the data to the console
   * @returns Promise with the result
   */
  handleKinesisEvent(@Body() data: OsDocumentData, print: boolean): Promise<OpenSearchBulkResult> {
    return myContainer.get<KinesisStreamWrapperService>(TYPES.KinesisStreamWrapperService)
      .handleData(data, print);
  }
Example #2
Source File: plugin-newsletter.controller.ts    From Cromwell with MIT License 6 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 || !/\[email protected]\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 #3
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 #4
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 #5
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiNoContentResponse({
    description: 'No content. 204',
  })
  @ApiNotFoundResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        error: 'Not Found',
      },
    },
    description: 'User was not found',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiBearerAuth()
  @HttpCode(HttpStatus.NO_CONTENT)
  @Auth(RolesEnum.admin)
  @Put('verify')
  async verifyUser(@Body() verifyUserDto: VerifyUserDto): Promise<User | null> {
    const foundUser = await this.usersService.getUnverifiedUserByEmail(
      verifyUserDto.email,
    ) as UserDocument;

    if (!foundUser) {
      throw new NotFoundException('The user does not exist');
    }

    return this.usersService.update(foundUser._id, { verified: true });
  }
Example #6
Source File: bom-license-exception.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Post('/')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: BomLicenseException })
  async createOneManualLicense(
    @Body() dto: BomLicenseException,
    @ParsedRequest() req: CrudRequest,
    @Request() request: any,
  ): Promise<BomLicenseException> {
    const { id: userId } = request.user;
    dto.userId = userId;
    const exception = await this.service.createOne(req, dto);

    const project = await this.projectService.findOne({ id: dto.project.id });
    await this.commandBus.execute(
      new LogProjectChangeCommand(
        project.id,
        LogProjectChangeCommand.Actions.licenseExceptionCreated,
        `A license exception has been created for project [${project.name}].`,
        userId,
      ),
    );

    return exception;
  }
Example #7
Source File: create-user.http.controller.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
@Post(routesV1.user.root)
  @ApiOperation({ summary: 'Create a user' })
  @ApiResponse({
    status: HttpStatus.OK,
    type: IdResponse,
  })
  @ApiResponse({
    status: HttpStatus.CONFLICT,
    description: UserAlreadyExistsError.message,
  })
  @ApiResponse({
    status: HttpStatus.BAD_REQUEST,
  })
  async create(@Body() body: CreateUserRequest): Promise<IdResponse> {
    const command = new CreateUserCommand(body);

    const result: Result<
      ID,
      UserAlreadyExistsError
    > = await this.commandBus.execute(command);

    // Deciding what to do with a Result (similar to Rust matching)
    // if Ok we return a response with an id
    // if Error decide what to do with it depending on its type
    return match(result, {
      Ok: id => new IdResponse(id.value),
      Err: error => {
        if (error instanceof UserAlreadyExistsError)
          throw new ConflictException(error.message);
        throw error;
      },
    });
  }
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: collections.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiOperation({ summary: 'Update specified collection' })
  @ApiNestNotFoundResponse('No collection was found with the specified id')
  @ApiParam({ name: 'collectionId', example: 1 })
  @UseGuards(CollectionGuard)
  @Put(':collectionId')
  update(
    @Param('collectionId', ParseIntPipe) collectionId: number,
    @Body() updateCollectionDto: UpdateCollectionDto,
  ) {
    return this.collectionsService.update(collectionId, updateCollectionDto);
  }
Example #15
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 #16
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('login')
  @HttpCode(HttpStatus.OK)
  @ApiOkResponse({ type: LoginResDto })
  @ApiUnauthorizedResponse({ type: ApiException })
  @UseGuards(AuthenticationGuard)
  async login(
    @Body() _: LoginReqDto,
    @Req() req?: Request
  ): Promise<LoginResDto> {
    const accessToken = await this.authService.getAuthToken(req.user as User);
    return { accessToken };
  }
Example #17
Source File: announcement.controller.ts    From edu-server with MIT License 6 votes vote down vote up
@Post()
  @Roles(Role.ADMIN)
  @ApiOperation({ summary: 'add an Announcement' })
  @ApiCreatedResponse(responsedoc.addAnnouncement)
  async addAnnouncement(@Body() CreateAnnouncementDTO: CreateAnnouncementDTO) {
    return await this.announcementService.addAnnouncement(
      CreateAnnouncementDTO,
    );
  }