@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
    /** Use ThrottlerGuard to limit number of requests from one IP address. Allow max 4 requests in 20 seconds: */
    @Throttle(4, 20)
    @ApiOperation({ description: 'Post email to subscribe for newsletters' })
        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: {
        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
  @ApiOperation({ summary: '유저 정보 수정 API' })
    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
  async register(@Body() body: Partial<UserEntity>) {
    try {
      const salt = await genSalt(10);
      const { password, ...reset } = body;
      const u: Partial<UserEntity> = {
        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
    description: 'No content. 204',
    schema: {
      type: 'object',
      example: {
        message: 'string',
        error: 'Not Found',
    description: 'User was not found',
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
    description: '500. InternalServerError',
  async verifyUser(@Body() verifyUserDto: VerifyUserDto): Promise<User | null> {
    const foundUser = await this.usersService.getUnverifiedUserByEmail(
    ) 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
  @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(
        `A license exception has been created for project [${project.name}].`,

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

    const result: Result<
    > = 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
  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);
    } 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
  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
    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
    description: 'The option that got created',
    type: Option,
  async saveOptionToQuestion(@Body() createOption: CreateOptionDto) {
    const question = await this.questionService.findQuestionById(
    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
  async paddleWebhook(
    @Body() body: PaddleEvent,
    @Res() response: Response
  ): Promise<void> {
    await this.paddleService.handlePaddleWebhook(body);
Example #13
Source File: RemixController.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
    @Req() request: Request,
    @Res() response: Response,
    @Next() next: NextFunction,
    @Body() body: any
  ) {
    if (this.isStaticAsset(request)) return next();

    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
  @ApiOperation({ summary: 'Update specified collection' })
  @ApiNestNotFoundResponse('No collection was found with the specified id')
  @ApiParam({ name: 'collectionId', example: 1 })
    @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
  @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

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

    const result: Comment = await this.commentsService
        organization: organization.id

    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
  @ApiOkResponse({ type: LoginResDto })
  @ApiUnauthorizedResponse({ type: ApiException })
  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
  @ApiOperation({ summary: 'add an Announcement' })
  async addAnnouncement(@Body() CreateAnnouncementDTO: CreateAnnouncementDTO) {
    return await this.announcementService.addAnnouncement(