@nestjs/common#Delete TypeScript Examples

The following examples show how to use @nestjs/common#Delete. 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: theme.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Delete('page')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator')
    @ApiOperation({
        description: `Deletes virtual page in both configs`,
        parameters: [
            { name: 'pageRoute', in: 'query', required: true },
            { name: 'themeName', in: 'query', required: true },
        ],
    })
    @ApiResponse({
        status: 200,
        type: PageConfigDto
    })
    async deletePage(@Query('pageRoute') pageRoute: string, @Query('themeName') themeName: string): Promise<boolean | null> {
        logger.log('ThemeController::deletePage');

        if (!pageRoute)
            throw new HttpException('Page route is not valid: ' + pageRoute, HttpStatus.NOT_ACCEPTABLE);

        return await this.themeService.deletePage(pageRoute, themeName);
    }
Example #2
Source File: user.controller.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
@Delete(':id')
  @ApiOperation({ summary: '유저 삭제 API' })
  @ApiNoContentResponse({ description: 'Id가 일치하는 유저 정보를 삭제한다.' })
  async delete(
    @Param('id', new ParseIntPipe()) id: number,
    @Res() res: Response,
  ) {
    await this.userService.deleteUser(id);

    return res.status(HttpStatus.NO_CONTENT).send();
  }
Example #3
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiNoContentResponse({
    description: 'no content',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiBearerAuth()
  @Delete('logout-all')
  @Auth(RolesEnum.admin)
  @HttpCode(HttpStatus.NO_CONTENT)
  async logoutAll(): Promise<{}> {
    return this.authService.deleteAllTokens();
  }
Example #4
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 #5
Source File: collections.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiOperation({ summary: 'Delete specified collection' })
  @ApiNestNotFoundResponse('No collection was found with the specified id')
  @ApiParam({ name: 'collectionId', example: 1 })
  @UseGuards(CollectionGuard)
  @Delete(':collectionId')
  delete(@Param('collectionId', ParseIntPipe) collectionId: number) {
    return this.collectionsService.delete(collectionId);
  }
Example #6
Source File: assignment.controller.ts    From edu-server with MIT License 6 votes vote down vote up
@Delete('/:courseId/:assignmentId')
  @Roles(Role.ADMIN)
  @ApiParam(courseId)
  @ApiOperation({ summary: 'delete an Assignment' })
  @ApiOkResponse(responsedoc.deleteAssignment)
  async deleteAssignment(
    @Param('courseId') courseId: Schema.Types.ObjectId,
    @Param('assignmentId') assignmentId: Schema.Types.ObjectId,
  ) {
    return await this.assignmentService.deleteAssignment(
      courseId,
      assignmentId,
    );
  }
Example #7
Source File: post.controller.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
@Delete(':id')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @HasRoles(RoleType.ADMIN)
  deletePostById(
    @Param('id', ParseObjectIdPipe) id: string,
    @Res() res: Response,
  ): Observable<Response> {
    return this.postService.deleteById(id).pipe(
      map((post) => {
        return res.status(204).send();
      }),
    );
  }
Example #8
Source File: calendar.controller.ts    From life-helper-backend with MIT License 6 votes vote down vote up
/**
   * 删除一个日程项目
   */
  @Delete('project')
  async deleteProject(@User('id') userId: number, @Query() query: QueryId) {
    const projectId = query.id

    return this.calendarProjectService.delete(userId, projectId)
  }
Example #9
Source File: events.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  @UseGuards(ApiKeyGuard)
  async delete(
    @Param('id', new IntIsSafeForPrismaPipe())
    id: number,
  ): Promise<void> {
    const event = await this.eventsService.findOrThrow(id);
    await this.eventsService.delete(event);
  }
Example #10
Source File: admins.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@ApiOperation({ summary: 'Get admin by id' })
  @ApiOkResponse({ type: NoResponseBody })
  @ApiNotFoundResponse()
  @Delete('/users/:userId')
  async deleteAdminById(@Request() req, @Param('userId') userId: string): Promise<NoResponseBody> {
    const requestAdminUser: RequestAdminUser = req.user
    await this.adminsService.deleteOneAdminById(requestAdminUser, userId)

    return {}
  }
Example #11
Source File: article.controller.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Delete(':id')
  @ApiOperation({
    summary: 'Delete article by id API',
  })
  @ApiResponse({
    status: HttpStatus.NO_CONTENT,
  })
  @UseInterceptors(ClassSerializerInterceptor)
  @UseGuards(JwtAuthGuard)
  async deleteArticle(
    @ReqContext() ctx: RequestContext,
    @Param('id') id: number,
  ): Promise<void> {
    this.logger.log(ctx, `${this.deleteArticle.name} was called`);

    return this.articleService.deleteArticle(ctx, id);
  }
Example #12
Source File: auth.controller.ts    From Phantom with MIT License 6 votes vote down vote up
@UseGuards(AuthGuard('jwt'))
  @Delete('/me/delete')
  async deleteMe(@Request() req) {
    const user = await this.userService.getUserById(req.user._id);
    await this.userService.deleteUser(req.user._id);
    await this.email.sendEmail(
      user.email,
      null,
      'Delete account',
      user.firstName,
    );
  }
Example #13
Source File: documentType.controller.ts    From MyAPI with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiOperation({ summary: 'Delete document type' })
  @ApiOkResponse({ description: 'The document type has been deleted successfully' })
  @ApiBadRequestResponse({ description: 'The document type could not be deleted' })
  @ApiForbiddenResponse({ description: 'You do not have the necessary role to perform this action' })
  @UseGuards(AuthGuard(), RolesGuard)
  @Roles(DefaultRole.Admin)
  @Delete(':id')
  @HttpCode(HttpStatus.OK)
  async deleteDocumentType(
    @Param('id', ParseIntPipe) id: number
  ): Promise<void> {
    const usersWithDocumentType = await this.userService.countByDocumentTypeId(id)
    if (usersWithDocumentType > 0) {
      throw new BadRequestException(ERRORS.USER_HAS_DOCUMENT_TYPE)
    }
    try {
      await this.documentTypeService.delete(id)
    } catch (error) {
      switch (error.code) {
        default:
          this.logger.error(error.message, 'DELETE_DOCUMENT_TYPE')
          throw new BadRequestException(error.message)
      }
    }
  }
Example #14
Source File: MediaController.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Delete(':mediaId')
  @HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth()
  @ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
  public async removeMedia(@HttpUser() user: HttpUserPayload, @Param('mediaId') mediaId: string): Promise<CoreApiResponse<void>> {
    const adapter: RemoveMediaAdapter = await RemoveMediaAdapter.new({executorId: user.id, mediaId: mediaId,});
    await this.removeMediaUseCase.execute(adapter);
    
    return CoreApiResponse.success();
  }
Example #15
Source File: content.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Delete('/:entryUuid')
	@AuditLog('content/delete')
	public async delete(
		@Param('contentTypeUuid') contentTypeUuid: string,
		@Param('entryUuid') uuid: string,
		@Request() req,
	): Promise<void> {
		if (!await this.permissionService.hasPermission(req.user?.uuid || req.headers.authorization, [`content/${contentTypeUuid}/delete`])) {
			throw new ForbiddenException(`Missing permissions: content/${contentTypeUuid}/delete`)
		}

		return await this.contentService.delete(contentTypeUuid, uuid);
	}
Example #16
Source File: users.controller.ts    From nestjs-starter with MIT License 6 votes vote down vote up
/**
   * Softdelete users (SOFT DELETION)
   * @param ids User ID integers ?ids=1,2,3
   * @example DELETE /users/bulk
   */
  @ApiTags('Users batch operations')
  @ApiOperation({
    summary: 'Softdelete users - Batch',
    description: '(SOFT DELETION) Delete users. You will have to provide a query param of ids separated by comas example: ?ids=1,2,3',
  })
  @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' })
  @ApiQuery({ name: 'ids', required: true, type: 'string', example: '1,2,3' })
  @Delete('bulk')
  async deleteMany(@Query('ids', new ParseArrayPipe({ items: Number, separator: ',' })) ids: number[]) {
    return await this.service.softDeleteMany(ids);
  }
Example #17
Source File: course.controller.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
@Delete(':id/update_override')
  @UseGuards(JwtAuthGuard, CourseRolesGuard)
  @Roles(Role.PROFESSOR)
  async deleteOverride(
    @Param('id') courseId: number,
    @Body() overrideInfo: UpdateCourseOverrideBody,
  ): Promise<void> {
    const user = await UserModel.findOne({
      where: { email: overrideInfo.email },
    });
    if (!user)
      throw new BadRequestException(
        ERROR_MESSAGES.courseController.noUserFound,
      );
    const userId = user.id;
    const userCourse = await UserCourseModel.findOne({
      where: { courseId, userId, override: true },
    });
    await this.courseService.removeUserFromCourse(userCourse);
  }
Example #18
Source File: waiting.controller.ts    From 42_checkIn with GNU General Public License v3.0 5 votes vote down vote up
@UseGuards(JwtAuthGuard)
  @Delete('cancel')
  async cancelWaiting(@Req() req: any) {
    return this.waitingService.cancel(req.user._id);
  }
Example #19
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
@ApiNoContentResponse({
    description: 'no content',
  })
  @ApiUnauthorizedResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
      },
    },
    description: 'Token has been expired',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiBearerAuth()
  @Auth()
  @Delete('logout')
  @HttpCode(HttpStatus.NO_CONTENT)
  async logout(@AuthBearer() token: string): Promise<{} | never> {
    const decodedUser: DecodedUser | null = await this.authService.verifyToken(
      token,
      this.configService.get<string>('ACCESS_TOKEN') || '<%= config.accessTokenSecret %>',
    );

    if (!decodedUser) {
      throw new ForbiddenException('Incorrect token');
    }

    const deletedUsersCount = await this.authService.deleteTokenByEmail(
      decodedUser.email,
    );

    if (deletedUsersCount === 0) {
      throw new NotFoundException();
    }

    return {};
  }
Example #20
Source File: pledge.controller.ts    From The-TypeScript-Workshop with MIT License 5 votes vote down vote up
@Delete(':id')
  deletePledge(@Param('id') id: number): Promise<DeleteResult> {
    return this.pledgeService.delete(id);
  }
Example #21
Source File: delete-user.http-controller.ts    From domain-driven-hexagon with MIT License 5 votes vote down vote up
@Delete(routesV1.user.delete)
  async deleteUser(@Param('id') id: string): Promise<void> {
    const command = new DeleteUserCommand({ userId: id });
    await this.service.execute(command);
  }
Example #22
Source File: tag.controller.ts    From whispr with MIT License 5 votes vote down vote up
@Delete(':id')
  @HttpCode(204)
  async deleteTag(@Param('id') id: string): Promise<boolean> {
    return this.tagService.delete(id);
  }
Example #23
Source File: google-cloud.controller.ts    From aqualink-app with MIT License 5 votes vote down vote up
@ApiBearerAuth()
  @ApiOperation({ summary: 'Deletes all unused files stored' })
  @Delete('dangling')
  DeleteDanglingFiles(): Promise<void[]> {
    return this.googleCloudService.deleteDanglingFiles();
  }
Example #24
Source File: organizations.controller.ts    From nestjs-rest-microservices with MIT License 5 votes vote down vote up
@Delete(':name/comments')
  @Header('Content-Type', 'application/json')
  async deleteOrganizationComments(@Param('name') name: string): Promise<Count> {
    this.logger.info('OrganizationController#deleteOrganizationComments.call', name)

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

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

    const result: Count = await this.commentsService
      .destroy({
        where: JSON.stringify({ organization: organization.id })
      })
      .toPromise()

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

    return result
  }
Example #25
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 #26
Source File: announcement.controller.ts    From edu-server with MIT License 5 votes vote down vote up
@Delete('/:announcementId')
  @Roles(Role.ADMIN)
  @ApiParam(announcementId)
  @ApiOperation({ summary: 'Delete an Announcement by Id' })
  @ApiOkResponse(responsedoc.deleteAnnouncement)
  async deleteAnnouncement(@Param('announcementId') announcementId: string) {
    return await this.announcementService.deleteAnnouncement(announcementId);
  }
Example #27
Source File: product.controller.ts    From nest-keycloak-connect with MIT License 5 votes vote down vote up
@Delete(':code')
  @Scopes('Delete')
  async deleteByCode(@Param('code') code: string) {
    return await this.service.deleteByCode(code);
  }
Example #28
Source File: product.controller.ts    From nest-js-products-api with MIT License 5 votes vote down vote up
@Delete(':id')
  public async deleteProduct(
    @Res() request,
    @Param('id') id: string,
  ): Promise<any> {
    const product = await this.deleteProductUseCase.handler(id);
    return request.status(HttpStatus.OK).json(product);
  }
Example #29
Source File: calendar.controller.ts    From life-helper-backend with MIT License 5 votes vote down vote up
/**
   * 删除一条任务
   */
  @Delete('task/:id')
  async deleteTask(@User('id') userId: number, @Param('id') id: number) {
    return this.calendarTaskService.delete(userId, id)
  }