@nestjs/common#UseInterceptors TypeScript Examples

The following examples show how to use @nestjs/common#UseInterceptors. 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: project.controller.ts    From barista with Apache License 2.0 7 votes vote down vote up
@Get('/:id/obligations')
  @UseInterceptors(CrudRequestInterceptor)
  async obligations(@Param('id') id: string): Promise<any> {
    const project = await this.service.db.findOne(Number(id));
    if (project) {
      return this.service.distinctObligations(project);
    } else {
      return [];
    }
  }
Example #2
Source File: article.controller.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Get(':id')
  @ApiOperation({
    summary: 'Get article by id API',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: SwaggerBaseApiResponse(ArticleOutput),
  })
  @ApiResponse({
    status: HttpStatus.NOT_FOUND,
    type: BaseApiErrorResponse,
  })
  @UseInterceptors(ClassSerializerInterceptor)
  @UseGuards(JwtAuthGuard)
  async getArticle(
    @ReqContext() ctx: RequestContext,
    @Param('id') id: number,
  ): Promise<BaseApiResponse<ArticleOutput>> {
    this.logger.log(ctx, `${this.getArticle.name} was called`);

    const article = await this.articleService.getArticleById(ctx, id);
    return { data: article, meta: {} };
  }
Example #3
Source File: waiting.controller.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@UseInterceptors(IpInterceptor)
  @UseGuards(JwtAuthGuard)
  @Post('create/:type')
  async createWaiting(
    @Req() req: any,
    @Param('type')
    type: number,
  ) {
    return this.waitingService.create(req.user._id, type);
  }
Example #4
Source File: article.controller.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Get()
  @ApiOperation({
    summary: 'Get articles as a list API',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: SwaggerBaseApiResponse([ArticleOutput]),
  })
  @UseInterceptors(ClassSerializerInterceptor)
  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  async getArticles(
    @ReqContext() ctx: RequestContext,
    @Query() query: PaginationParamsDto,
  ): Promise<BaseApiResponse<ArticleOutput[]>> {
    this.logger.log(ctx, `${this.getArticles.name} was called`);

    const { articles, count } = await this.articleService.getArticles(
      ctx,
      query.limit,
      query.offset,
    );

    return { data: articles, meta: { count } };
  }
Example #5
Source File: security-scan-result-item.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
/**
   * Retrieves the Full Details, including Raw Results for the supplied Security Scan Result Item Id
   *
   * @param id
   */
  @Get(':id/full-details')
  @UseInterceptors(CrudRequestInterceptor)
  index(@Param('id') id: string): Promise<any> {
    return this.service.db.findOne(id);
  }
Example #6
Source File: app.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
@Post('/file')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, callback) => {
          const uniqueSuffix =
            Date.now() + '-' + Math.round(Math.random() * 1e9);
          const ext = extname(file.originalname);
          const filename = `${uniqueSuffix}${ext}`;
          callback(null, filename);
        },
      }),
    }),
  )
  handleUpload(@UploadedFile() file: Express.Multer.File) {
    console.log('file', file);
    return 'File upload API';
  }
Example #7
Source File: launcher.controller.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
@UseInterceptors(ZLibDeflateJSONInterceptor)
  @Get('/launcher/server/connect')
  launcher_server_connect(): Record<string, any> {
    return {
      backendUrl: `https://${this.common.serverConfig.address}:${this.common.serverConfig.port}`,
      name: SystemService.Server,
      editions: this.profile.getAccountTypes(),
    };
  }
Example #8
Source File: auth.controller.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@UseInterceptors(MorganInterceptor('combined'))
  @UseFilters(GithubAuthExceptionFilter)
  @Get('/github/callback')
  @UseGuards(AuthGuard('github'))
  async githubCallback(@Req() request: Request, @Res() response: Response) {
    const user: AuthUser = request.user as AuthUser;
    this.logger.log({
      level: 'info',
      message: `receive login callback from github account_id=${user.account.id}`
    });
    const token = await this.authService.prepareToken(user);
    response.redirect(301, `${this.host}?token=${token}`);
  }
Example #9
Source File: time-series.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiOperation({ summary: 'Upload time series data' })
  @UseGuards(IsSiteAdminGuard)
  @Auth(AdminLevel.SiteManager, AdminLevel.SuperAdmin)
  @Post('sites/:siteId/site-survey-points/:surveyPointId/upload')
  @UseInterceptors(
    FilesInterceptor('files', MAX_FILE_COUNT, {
      dest: './upload',
      fileFilter,
      limits: {
        fileSize: MAX_FILE_SIZE_MB * 10 ** 6,
      },
    }),
  )
  uploadTimeSeriesData(
    @Param() surveyPointDataRangeDto: SurveyPointDataRangeDto,
    @UploadedFiles() files: Express.Multer.File[],
    @Body('sensor') sensor: SourceType,
    @Query('failOnWarning', ParseBoolPipe) failOnWarning?: boolean,
  ) {
    return this.timeSeriesService.uploadData(
      surveyPointDataRangeDto,
      sensor,
      files,
      failOnWarning,
    );
  }
Example #10
Source File: profile.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('upload_profile_photo')
  @UseInterceptors(FileInterceptor('file'))
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: 'Upload avatar photo',
    type: AvatarUploadDto
  })
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiResponse({ type: UserDto, status: HttpStatus.OK })
  @HttpCode(HttpStatus.OK)
  async uploadFile(
    @UploadedFile() file: BufferedFile,
    @Req() req: Request
  ): Promise<UserDto> {
    if (!file) throw new BadRequestException('File image cannot be empty');

    if (file.mimetype.split('/')[0] !== 'image')
      throw new UnsupportedMediaTypeException('File is not an image');

    if (file.size / 1024 > 200)
      throw new BadRequestException('File cannot be larger than 200KB');

    const id = req.user['userId'];
    await this.profileService.uploadAvatar(file, id);
    const user = await this.userService.findByIdAsync(id);

    return plainToClass(UserDto, user, {
      enableImplicitConversion: true,
      excludeExtraneousValues: true
    });
  }
Example #11
Source File: launcher.controller.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
@UseInterceptors(ZLibDeflateJSONInterceptor)
  @Post('/launcher/profile/login')
  launcher_profile_login(@Req() request: Request): string {
    if (!request.body) {
      return 'FAILED';
    }
    return this.profile.getProfileByUsername(request.body['username'])[
      'account'
    ]['aid'];
  }
Example #12
Source File: app.controller.ts    From nestjs-jaeger-tracing with MIT License 6 votes vote down vote up
@UseInterceptors(TracingInterceptor)
  @MessagePattern({ cmd: 'echoMessage' })
  echoMessage(
    @Tracing() tracing: TracingData,
    @Payload() message: string,
  ): string {
    Logger.log({ echoMessage: tracing });
    return message;
  }
Example #13
Source File: project.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Get('/search')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: [Project] })
  async filteredProjects(
    @Query('filterText') filter: string,
    @Query('page') page: number,
    @Query('pageSize') pageSize: number,
    @Query('developmentType') developmentType: string,
  ): Promise<GetManyDefaultResponse<Project>> {
    const query = await this.service.db
      .createQueryBuilder('project')
      .leftJoinAndSelect('project.developmentType', 'developmentType')
      .where('(lower(name) like :filter or lower(git_url) like :filter) AND developmentType.code = :code', {
        filter: '%' + filter.toLocaleLowerCase() + '%',
        code: developmentType || 'organization',
      });

    return await PaginateArrayResult(query, +page, +pageSize);
  }
Example #14
Source File: storage.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Post()
	@HttpCode(204)
	@UseInterceptors(FileInterceptor('file'))
	@Permissions('storage/upload')
	public async upload(
		@Query('dir') dir = '',
		@UploadedFile() file: any
	): Promise<void> {
		const tenant = await this.tenantService.findOne();
		const StorageClient = this.storageLoader.load(tenant.settings.storageMedium || 'fs');
		const client = new StorageClient(tenant.settings.storageConfig);
		await client.init();

		return await client.put(`${dir}/${file.originalname}`.replace(/^(\/uploads)/, '').replace(/^\//, ''), file.buffer);
	}
Example #15
Source File: MediaController.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Post()
  @HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
  @HttpCode(HttpStatus.OK)
  @UseInterceptors(FileInterceptor('file'))
  @ApiBearerAuth()
  @ApiConsumes('multipart/form-data')
  @ApiBody({type: HttpRestApiModelCreateMediaBody})
  @ApiQuery({name: 'name', type: 'string', required: false})
  @ApiQuery({name: 'type', enum: MediaType})
  @ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
  public async createMedia(
    @Req() request: HttpRequestWithUser,
    @UploadedFile() file: MulterFile,
    @Query() query: HttpRestApiModelCreateMediaQuery
    
  ): Promise<CoreApiResponse<MediaUseCaseDto>> {
  
    const adapter: CreateMediaAdapter = await CreateMediaAdapter.new({
      executorId: request.user.id,
      name      : query.name || parse(file.originalname).name,
      type      : query.type,
      file      : file.buffer,
    });
    
    const createdMedia: MediaUseCaseDto = await this.createMediaUseCase.execute(adapter);
    this.setFileStorageBasePath([createdMedia]);
    
    return CoreApiResponse.success(createdMedia);
  }
Example #16
Source File: files.controller.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: (req: Express.Request, file: Express.Multer.File, cb) =>
          cb(null, 'public/uploads'),
        filename: (req: Express.Request, file: Express.Multer.File, cb) => {
          // mimetype: 'image/jpeg',
          const [, ext] = file.mimetype.split('/');
          FilesController.genericSercive.pcoket.filename = `${v4()}.${ext}`;
          cb(null, FilesController.genericSercive.pcoket.filename);
        },
      }),
      limits: {
        fileSize: 1e7, // the max file size in bytes, here it's 100MB,
        files: 1,
      },
    }),
  )
  uploadFile(@UploadedFile() file: Express.Multer.File): Promise<FileEntity> {
    const [, ext] = file.mimetype.split('/');
    this.saveImages(ext, file);
    return this.service.dbSave(
      file,
      FilesController.genericSercive.pcoket.filename,
    );
  }
Example #17
Source File: user.controller.ts    From bank-server with MIT License 6 votes vote down vote up
@Patch('/')
  @UseGuards(AuthGuard, RolesGuard)
  @UseInterceptors(AuthUserInterceptor)
  @ApiBearerAuth()
  @Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
  @HttpCode(HttpStatus.OK)
  @ApiResponse({
    status: HttpStatus.OK,
    description: 'Update user',
    type: UserDto,
  })
  async setUserData(
    @AuthUser() user: UserEntity,
    @Body() userUpdateDto: UserUpdateDto,
  ): Promise<UserDto> {
    const userWithNewData = await this._userService.updateUserData(
      user,
      userUpdateDto,
    );
    return userWithNewData.toDto();
  }
Example #18
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 #19
Source File: user.controller.ts    From bank-server with MIT License 6 votes vote down vote up
@Get('/')
  @UseGuards(AuthGuard, RolesGuard)
  @UseInterceptors(AuthUserInterceptor)
  @ApiBearerAuth()
  @Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
  @HttpCode(HttpStatus.OK)
  @ApiResponse({
    status: HttpStatus.OK,
    description: 'Get user',
    type: UserDto,
  })
  async getUserData(@AuthUser() user: UserEntity): Promise<UserDto> {
    const userEntity = await this._userService.getUser({ uuid: user.uuid });
    return userEntity.toDto();
  }
Example #20
Source File: bom-manual-license.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Get('/search')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: [BomManualLicense] })
  async search(
    @Query('projectId') projectId: number,
    @Query('filterText') filter: string,
    @Query('page') page: number,
    @Query('pageSize') pageSize: number,
  ): Promise<GetManyDefaultResponse<BomManualLicense>> {
    return await this.service.search(projectId, filter, page, pageSize);
  }
Example #21
Source File: auth.controller.ts    From bank-server with MIT License 6 votes vote down vote up
@Patch('logout')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiNoContentResponse({
    description: 'Successfully Logout',
  })
  @UseGuards(AuthGuard, RolesGuard)
  @UseInterceptors(AuthUserInterceptor)
  @ApiBearerAuth()
  @Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
  async userLogout(@AuthUser() user: UserEntity): Promise<void> {
    await this._userAuthService.updateLastLogoutDate(user.userAuth);
  }
Example #22
Source File: images.controller.ts    From Phantom with MIT License 6 votes vote down vote up
@Post('/me/uploadImage')
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(FilesInterceptor('file'))
  async uploadImage(@UploadedFiles() files, @Request() req) {
    return await this.ImagesService.uploadFile(
      files[0].originalname,
      files[0].mimetype,
      files[0].buffer,
    );
  }
Example #23
Source File: license.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Get('/search')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: License, isArray: true })
  async filteredLicense(
    @Query('filterText') filter: string,
    @Query('page') page: number,
    @Query('pageSize') pageSize: number,
  ): Promise<GetManyDefaultResponse<License>> {
    return await this.service.search(filter, page, pageSize);
  }
Example #24
Source File: user.controller.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
// TODO: ADD RoleGuard
  // NOTE : This can be made a admin only endpoint. For normal users they can use PATCH /me
  @Patch(':id')
  @ApiOperation({
    summary: 'Update user API',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: SwaggerBaseApiResponse(UserOutput),
  })
  @ApiResponse({
    status: HttpStatus.NOT_FOUND,
    type: BaseApiErrorResponse,
  })
  @UseInterceptors(ClassSerializerInterceptor)
  async updateUser(
    @ReqContext() ctx: RequestContext,
    @Param('id') userId: number,
    @Body() input: UpdateUserInput,
  ): Promise<BaseApiResponse<UserOutput>> {
    this.logger.log(ctx, `${this.updateUser.name} was called`);

    const user = await this.userService.updateUser(ctx, userId, input);
    return { data: user, meta: {} };
  }
Example #25
Source File: license-status-deployment-type.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Get('/get-exceptions-for-license')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, isArray: true, type: LicenseStatusDeploymentType })
  async getExceptionsForLicense(
    @Query('licenseCode') licenseCode: string,
    @Query('page') page: number,
    @Query('perPage') perPage: number,
  ): Promise<GetManyDefaultResponse<LicenseStatusDeploymentType>> {
    return await this.service.getExceptionsForLicense(licenseCode, page, perPage);
  }
Example #26
Source File: auth.controller.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Post('refresh-token')
  @ApiOperation({
    summary: 'Refresh access token API',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: SwaggerBaseApiResponse(AuthTokenOutput),
  })
  @ApiResponse({
    status: HttpStatus.UNAUTHORIZED,
    type: BaseApiErrorResponse,
  })
  @HttpCode(HttpStatus.OK)
  @UseGuards(JwtRefreshGuard)
  @UseInterceptors(ClassSerializerInterceptor)
  async refreshToken(
    @ReqContext() ctx: RequestContext,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    @Body() credential: RefreshTokenInput,
  ): Promise<BaseApiResponse<AuthTokenOutput>> {
    this.logger.log(ctx, `${this.refreshToken.name} was called`);

    const authToken = await this.authService.refreshToken(ctx);
    return { data: authToken, meta: {} };
  }
Example #27
Source File: obligation.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Get('/search')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: ObligationSearchDto, isArray: true })
  async filteredObligations(
    @Query('filterText') filter: string,
    @Query('page') page: number,
    @Query('pageSize') pageSize: number,
  ): Promise<GetManyDefaultResponse<Obligation>> {
    const query = await this.service.db
      .createQueryBuilder('project')
      .where('lower(name) like :filter or lower("desc") like :filter', {
        filter: '%' + filter.toLocaleLowerCase() + '%',
      });

    return await PaginateArrayResult(query, +page, +pageSize);
  }
Example #28
Source File: launcher.controller.ts    From emutypekov with GNU General Public License v3.0 5 votes vote down vote up
@UseInterceptors(ZLibDeflateJSONInterceptor)
  @Post('/launcher/profile/get')
  launcher_profile_get(@Req() request: Request): Record<string, any> {
    return this.profile.getProfileByUsername(request.body['username'])[
      'account'
    ];
  }
Example #29
Source File: scan.controller.ts    From barista with Apache License 2.0 5 votes vote down vote up
@Post('/project/:id/branch/')
  @UseInterceptors(CrudRequestInterceptor)
  async doScanbyBranch(@Param('id') id: number, @Body() branch: ScanBranchDto, @Request() request: any): Promise<any> {
    return this.performScan(id, branch.branch, request);
  }