@nestjs/common#Put TypeScript Examples

The following examples show how to use @nestjs/common#Put. 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: 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 #2
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 #3
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 #4
Source File: profile.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Put()
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiResponse({ type: UserDto, status: HttpStatus.OK })
  async updateProfile(
    @Body() input: UpdateProfileDto,
    @Req() req: Request
  ): Promise<UserDto> {
    const id = req.user['userId'];
    const user = await this.userService.updateAsync(id, input);
    return plainToClass(UserDto, user, {
      excludeExtraneousValues: true,
      enableImplicitConversion: true
    });
  }
Example #5
Source File: announcement.controller.ts    From edu-server with MIT License 6 votes vote down vote up
@Put('/:announcementId')
  @Roles(Role.ADMIN)
  @ApiParam(announcementId)
  @ApiOperation({ summary: 'update Announcement by Id' })
  @ApiOkResponse(responsedoc.updateAnnouncement)
  async updateAnnouncement(
    @Param('announcementId') announcementId: string,
    @Body() updateAnnouncementDTO: UpdateAnnouncementDTO,
  ) {
    return await this.announcementService.updateAnnouncement(
      announcementId,
      updateAnnouncementDTO,
    );
  }
Example #6
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 #7
Source File: post.controller.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
@Put(':id')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @HasRoles(RoleType.USER, RoleType.ADMIN)
  updatePost(
    @Param('id', ParseObjectIdPipe) id: string,
    @Body() post: UpdatePostDto,
    @Res() res: Response,
  ): Observable<Response> {
    return this.postService.update(id, post).pipe(
      map((post) => {
        return res.status(204).send();
      }),
    );
  }
Example #8
Source File: qrcode.controller.ts    From life-helper-backend with MIT License 6 votes vote down vote up
/**
   * 扫码操作
   */
  @Put('scan')
  @UseGuards(AuthGuard)
  async scan(@User('id') userId: number, @Query() query: ScanQueryDto): Promise<ScanResponseDto> {
    const code = query.code

    const authen = await this.qrcodeService.scan(userId, code)
    return { scanTime: authen.scanTime } as ScanResponseDto
  }
Example #9
Source File: users.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@ApiExcludeEndpoint()
  @Put(':id')
  @UseGuards(MagicLinkGuard)
  async update(
    @Context() { user }: MagicLinkContext,
    @Param('id', new IntIsSafeForPrismaPipe())
    id: number,
    @Body(
      new ValidationPipe({
        errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        transform: true,
      }),
    )
    dto: UpdateUserDto,
  ): Promise<User> {
    if (id !== user.id) {
      throw new ForbiddenException();
    }
    return this.usersUpdater.update(user, {
      countryCode: dto.country_code,
      discord: dto.discord,
      github: dto.github,
      graffiti: dto.graffiti,
      telegram: dto.telegram,
    });
  }
Example #10
Source File: board.controller.ts    From Phantom with MIT License 6 votes vote down vote up
@UseGuards(AuthGuard('jwt'))
  @Put('/me/boards/sortAZ')
  async sortBoardsAtoZ(@Request() req) {
    let userId = req.user._id;
    let boards = await this.BoardService.sortBoardsAtoZ(userId);
    if (boards) {
      return boards;
    } else {
      throw new NotFoundException({ message: 'no boards' });
    }
  }
Example #11
Source File: documentType.controller.ts    From MyAPI with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiOperation({ summary: 'Update document type' })
  @ApiOkResponse({ description: 'The document type has been updated successfully' })
  @ApiBadRequestResponse({ description: 'The document type could not be updated' })
  @ApiForbiddenResponse({ description: 'You do not have the necessary role to perform this action' })
  @UseGuards(AuthGuard(), RolesGuard)
  @Roles(DefaultRole.Admin)
  @Put()
  @HttpCode(HttpStatus.OK)
  updateDocumentType(
    @Body() documentType: DocumentType,
  ): Promise<void> {
    try {
      return this.documentTypeService.upsert(documentType)
    } catch (error) {
      switch (error.code) {
        default:
          this.logger.error(error.message, 'UPDATE_DOCUMENT_TYPE')
          throw new BadRequestException(error.message)
      }
    }
  }
Example #12
Source File: MediaController.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Put(':mediaId')
  @HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth()
  @ApiBody({type: HttpRestApiModelEditMediaBody})
  @ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
  public async editMedia(
    @HttpUser() user: HttpUserPayload,
    @Body() body: HttpRestApiModelEditMediaBody,
    @Param('mediaId') mediaId: string
    
  ): Promise<CoreApiResponse<MediaUseCaseDto>> {
    
    const adapter: EditMediaAdapter = await EditMediaAdapter.new({
      mediaId    : mediaId,
      executorId : user.id,
      name       : body.name,
    });
    
    const editedMedia: MediaUseCaseDto = await this.editMediaUseCase.execute(adapter);
    this.setFileStorageBasePath([editedMedia]);
    
    return CoreApiResponse.success(editedMedia);
  }
Example #13
Source File: auth.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Put('/password-reset/:passwordResetUuid')
	@HttpCode(204)
	public async resetPassword(@Param('passwordResetUuid') passwordResetUuid: string, @Body() body: any): Promise<void> {
		const passwordReset = await this.passwordResetService.findOne(passwordResetUuid);
		const user = await this.userService.findOne({ email: passwordReset.emailAddress });

		user.password = bcryptjs.hashSync(body.password);
		await this.userService.update(user.uuid, user);

		await this.passwordResetService.delete(passwordResetUuid);

		return;
	}
Example #14
Source File: users.controller.ts    From nestjs-starter with MIT License 6 votes vote down vote up
/**
   * Update many
   * @param dtos Update User Form including the ID insude
   * @example PUT /users/bulk
   */
  @ApiTags('Users batch operations')
  @ApiOperation({ summary: 'Update users - Batch', description: 'Update users. You have to provide an id each object inside an updateUserDTO' })
  @ApiOkResponse({ status: 200, description: 'Success response' })
  @ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
  @ApiBadGatewayResponse({ status: 502, description: 'Something happened' })
  @ApiBadRequestResponse({ status: 400, description: 'You will prompt with an array with the validation issues' })
  @ApiBody({ required: true, type: [UpdateUserDto] })
  @Put('bulk')
  async updateMany(@Body(new ParseArrayPipe({ items: UpdateUserDto })) dtos: UpdateUserDto[]) {
    return await this.service.updateMany(dtos);
  }
Example #15
Source File: NftController.ts    From tatum-blockchain-connector with MIT License 6 votes vote down vote up
@Put('/royalty')
    @HttpCode(HttpStatus.OK)
    public async updateRoyaltyErc721(@Body() body: CeloUpdateCashbackErc721 | TronUpdateCashbackTrc721 | UpdateCashbackErc721 | OneUpdateCashback721) {
        try {
            return await this.service.updateCashbackForAuthor(body);
        } catch (e) {
            if (['Array', 'NftError', 'ValidationError'].includes(e.constructor.name)) {
                throw new BadRequestException(e);
            }
            if (e.constructor.name === 'TatumError') {
                throw e;
            }
            throw new NftError(`Unexpected error occurred. Reason: ${e.response?.message || e.response?.data || e.message || e}`, 'nft.error');
        }
    }
Example #16
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 5 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<SuccessResponseInterface | never> {
    const foundUser = await this.usersService.getUnverifiedUserByEmail(
      verifyUserDto.email
    ) as UserDocument;

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

    return ResponseUtils.success(
      'users',
      await this.usersService.update(foundUser._id, { verified: true }),
    );
  }
Example #17
Source File: heroes.controller.ts    From nestjs-geteventstore with MIT License 5 votes vote down vote up
@Put(':id/kill')
  async killDragon(@Param('id') id: string, @Body() dto: KillDragonDto) {
    return this.commandBus
      .execute(new KillDragonCommand(id, dto.dragonId))
      .catch((e) => console.log('e : ', e));
  }
Example #18
Source File: tag.controller.ts    From whispr with MIT License 5 votes vote down vote up
@Put(':id')
  @HttpCode(204)
  @UsePipes(new ValidationPipe({ whitelist: true }))
  async replaceTag(@Param('id') id: string, @Body() tag: TagInputType): Promise<ITag> {
    return this.tagService.replace(id, tag);
  }
Example #19
Source File: base.controller.ts    From codeclannigeria-backend with MIT License 5 votes vote down vote up
export function BaseCrudController<
  TEntity extends BaseEntity,
  TEntityDto,
  TCreateDto,
  TUpdateDto = Partial<TCreateDto>,
  TPagedListDto = any
>(
  options: BaseControllerWithSwaggerOpts<
    TEntity,
    TEntityDto,
    TCreateDto,
    TUpdateDto,
    TPagedListDto
  >
): Type<
  IBaseController<
    TEntityDto,
    TCreateDto,
    TUpdateDto,
    FindDto,
    IPagedListDto<TEntityDto>
  >
> {
  const {
    entity: Entity,
    entityDto: EntityDto,
    createDto: CreateDto,
    updateDto: UpdateDto,
    pagedListDto: PagedListDto
  } = options;
  const auth = getAuthObj(options.auth);
  @ApiTags(pluralize(Entity.name))
  @Controller(pluralize(Entity.name.toLowerCase()))
  class BaseController {
    constructor(
      @Inject(BaseService)
      protected service: BaseService<TEntity>
    ) {}

    @Post()
    @ApiResponse({ type: EntityDto, status: HttpStatus.CREATED })
    @ApiBody({ type: CreateDto })
    @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
    @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
    @Authenticate(auth.create.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.create.enableAuth, Roles(...auth.create.authRoles))
    @Authenticate(auth.create.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'Create' })
    async create(@Body() input: TCreateDto) {
      const entity = this.service.createEntity(input);
      await this.service.insertAsync(entity);
      return plainToClass(EntityDto, entity, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
    }

    @Get()
    @ApiResponse({ type: PagedListDto, status: HttpStatus.OK })
    @ApiResponse({ type: ApiException, status: HttpStatus.UNAUTHORIZED })
    @Authenticate(auth.find.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.find.enableAuth, Roles(...auth.find.authRoles))
    @Authenticate(auth.find.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'FindAll' })
    async findAll(@Query() query: FindDto) {
      const { skip, limit, search, opts } = query;
      const conditions = JSON.parse(search || '{}');
      const options = JSON.parse(opts || '{}');

      if (options?.sort) {
        const sort = { ...options.sort };
        Object.keys(sort).map((key) => {
          if (sort[key] === 'ascend') sort[key] = 1;
          else if (sort[key] === 'descend') sort[key] = -1;
          return sort;
        });
        options.sort = sort;
      }
      const entities = await this.service
        .findAll(conditions, options)
        .limit(limit)
        .skip(skip);

      const totalCount = await this.service.countAsync();
      const items = plainToClass(EntityDto, entities, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
      return { totalCount, items };
    }

    @Get(':id')
    @ApiResponse({ type: EntityDto, status: HttpStatus.OK })
    @ApiResponse({ status: HttpStatus.NOT_FOUND, type: ApiException })
    @Authenticate(auth.findById.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.findById.enableAuth, Roles(...auth.findById.authRoles))
    @Authenticate(auth.findById.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'FindById' })
    async findById(@Param('id') id: string) {
      const entity = await this.service.findByIdAsync(id);
      if (!entity)
        throw new NotFoundException(`Entity with id ${id} does not exist`);
      return plainToClass(EntityDto, entity, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
    }

    @Put(':id')
    @ApiBody({ type: UpdateDto })
    @ApiResponse({ status: HttpStatus.OK, type: EntityDto })
    @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
    @ApiResponse({ status: HttpStatus.NOT_FOUND, type: ApiException })
    @Authenticate(auth.update.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.update.enableAuth, Roles(...auth.update.authRoles))
    @Authenticate(auth.update.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'Update' })
    async update(@Param('id') id: string, @Body() input: TUpdateDto) {
      const existingEntity = await this.service.findByIdAsync(id);
      if (!existingEntity)
        throw new NotFoundException(`Entity with Id ${id} does not exist`);
      const value = plainToClass(Entity, existingEntity, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
      const toBeUpdatedEntity = { ...value, ...input };
      const result = await this.service.updateAsync(id, toBeUpdatedEntity);
      return plainToClass(EntityDto, result, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
    }

    @Delete(':id')
    @ApiResponse({ status: HttpStatus.OK })
    @Authenticate(auth.delete.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.delete.enableAuth, Roles(...auth.delete.authRoles))
    @Authenticate(auth.delete.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'Delete' })
    async delete(
      @Param('id') id: string,
      @Query('isHardDelete') isHardDelete: boolean
    ) {
      isHardDelete
        ? await this.service.hardDeleteById(id)
        : await this.service.softDeleteByIdAsync(id);
    }

    @Delete()
    @ApiResponse({ status: HttpStatus.OK })
    @Authenticate(auth.delete.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.delete.enableAuth, Roles(...auth.delete.authRoles))
    @Authenticate(auth.delete.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'Delete many' })
    async deleteMany(
      @Body() input: DeleteManyType,
      @Query('isHardDelete') isHardDelete: boolean
    ) {
      isHardDelete
        ? await this.service.hardDeleteMany({ _id: { $in: [...input.ids] } })
        : await this.service.softDeleteMany({ _id: { $in: [...input.ids] } });
    }
  }
  return BaseController;
}
Example #20
Source File: user.controller.ts    From edu-server with MIT License 5 votes vote down vote up
@Put('/enrolledCourses')
  @ApiOperation({ summary: 'user enrolling courses' })
  @ApiCreatedResponse(responsedoc.addEnrolledCourses)
  async addEnrolledCourses(@Body() createEnrolledDto: CreateEnrolledDTO) {
    return await this.userService.addCourse(createEnrolledDto);
  }
Example #21
Source File: product.controller.ts    From nest-keycloak-connect with MIT License 5 votes vote down vote up
@Put(':code')
  @Scopes('Edit')
  async update(@Param('code') code: string, @Body() product: Product) {
    return await this.service.update(code, product);
  }
Example #22
Source File: post.controller.ts    From nest-casl with MIT License 5 votes vote down vote up
@Put(':id')
  @UseGuards(AccessGuard)
  @UseAbility(Actions.update, Post, PostHook)
  async updatePost(@Param('id') id: string, @Body() updatePostInput: UpdatePostInput) {
    return this.postService.update({ ...updatePostInput, id });
  }
Example #23
Source File: offer.controller.ts    From pandaid with MIT License 5 votes vote down vote up
@Put(':id/state')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(Role.ADMIN, Role.SUPERVISOR)
  @ApiResponse({ status: 200, type: ChangeStateRequest })
  public setState(@Param('id') id: string, @Body() changeStatusRequest: ChangeStateRequest): Offer {
    return this.offerService.changeState(parseInt(id), changeStatusRequest.state)
  }
Example #24
Source File: calendar.controller.ts    From life-helper-backend with MIT License 5 votes vote down vote up
/**
   * 修改一条任务
   */
  @Put('task/:id')
  async updateTask(@User('id') userId: number, @Param('id') taskId: number, @Body() body: CreateTaskRequestDto) {
    return this.calendarTaskService.update(userId, taskId, body)
  }
Example #25
Source File: topic.controller.ts    From Phantom with MIT License 5 votes vote down vote up
@Put('/edit')
  async addImageToTopic(@Body('topics') topics: Array<object>) {
    let topic = await this.TopicService.editTopic(topics);
    if (topic) return topic;
    return new ForbiddenException();
  }
Example #26
Source File: api-key.controller.ts    From radiopanel with GNU General Public License v3.0 5 votes vote down vote up
@Put('/:id')
	@Permissions('api-keys/update')
	@AuditLog('api-keys/update')
	public async update(@Param('id') uuid: string, @Body() apiKey: ApiKey ): Promise<ApiKey> {
		return this.apiKeyService.update(uuid, apiKey);
	}