@nestjs/common#Query TypeScript Examples

The following examples show how to use @nestjs/common#Query. 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: card.controller.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@UseGuards(JwtAuthGuard)
  @Post('create/:type')
  async createCard(
    @Req() req: any,
    @Query('start') start: number,
    @Query('end') end: number,
    @Param('type') type: number,
  ) {
    return await this.cardServcie.createCard(req.user._id, start, end, type);
  }
Example #2
Source File: cms.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Get('read-public-dir')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator', 'guest', 'author')
    @ApiOperation({
        description: 'Read files and directories in specified subfolder of "public" files',
        parameters: [{ name: 'path', in: 'query' }]
    })
    @ApiResponse({
        status: 200,
    })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async readPublicDir(@Query('path') path: string): Promise<string[] | null> {
        const fullPath = join(getPublicDir(), path ?? '');
        if (! await fs.pathExists(fullPath)) return null;
        return (await fs.readdir(fullPath)).filter(dir => !publicSystemDirs.includes(dir));
    }
Example #3
Source File: bom-license-exception.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Get('/search')
  @UseInterceptors(CrudRequestInterceptor)
  @ApiResponse({ status: 200, type: [BomLicenseException] })
  async filteredProjects(
    @Query('projectId') projectId: number,
    @Query('filterText') filter: string,
    @Query('page') page: number,
    @Query('pageSize') pageSize: number,
  ): Promise<GetManyDefaultResponse<BomLicenseException>> {
    return await this.service.search(projectId, filter, page, pageSize);
  }
Example #4
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
/**
   * OAUTH FLOW HANDLERS :: Displayed only when invoded mid-way auth flow
   */

  /**
   * to display login form on client-initiated-auth
   */
  @Get('o/login')
  @UsePipes(
    new ValidationPipe({
      disableErrorMessages: false,
    }),
  )
  async showLoginPageAsAuth(@Res() res: Response, @Query() incomingAuthDto: IncomingAuthDto) {
    const { client_id } = incomingAuthDto;
    try {
      const applicationDetails = await this.accountService.validateAccessRequest(incomingAuthDto);
      return res.render('account/o/login', { app: applicationDetails, project_name: appData.Name });
    } catch (e) {
      this.logger.error(`${e.message} for ${client_id}`);
      return res.render('error', e.response);
    }
  }
Example #5
Source File: SkinController.ts    From rewind with MIT License 6 votes vote down vote up
@Get()
  async getSkinInfo(@Res() res: Response, @Query() query: { hd: number; animated: number; name: string }) {
    // We can take these in case user config does not exist
    const { hd, animated, name } = query;
    const hdIfExists = hd === 1;
    const animatedIfExists = animated === 1;
    const decodedName = decodeURIComponent(name);
    this.logger.log(`Skin requested ${decodedName} with hd=${hdIfExists} animated=${animatedIfExists}`);
    // TODO: Inject these parameters ...
    const info = await this.skinService.getSkinInfo(decodedName);
    res.json(info);
  }
Example #6
Source File: quiz.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
@Get('/')
  @ApiPaginatedResponse({ model: Quiz, description: 'List of quizzes' })
  async getAllQuiz(
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number = 1,
    @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number = 1,
  ): Promise<Pagination<Quiz>> {
    const options: IPaginationOptions = {
      limit,
      page,
    };
    return await this.quizService.paginate(options);
  }
Example #7
Source File: collections.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiOperation({ summary: "Fetch all user's private collections" })
  @Get()
  find(
    @Query() filterCollectionDto: FilterCollectionDto,
    @Req() request: AuthRequest,
  ) {
    return this.collectionsService.find(filterCollectionDto, request.user);
  }
Example #8
Source File: organizations.controller.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
@Get()
  @Header('Content-Type', 'application/json')
  async findOrganizations(@Query() query: RequestQuery): Promise<QueryResponse> {
    this.logger.info('OrganizationController#findOrganizations.call', query)

    const args = {
      ...(await this.queryUtils.getQueryParams(query))
    }

    const { count } = await this.organizationsService
      .count({
        where: !isEmpty(query.q) ? JSON.stringify({ name: { $like: query.q } }) : undefined
      })
      .toPromise()

    const data: OrganizationsQueryResult = await this.organizationsService
      .findAll({
        attributes: args.attributes,
        where: !isEmpty(query.q) ? JSON.stringify({ name: { $like: query.q } }) : undefined,
        order: JSON.stringify(args.order),
        offset: args.offset,
        limit: args.limit
      })
      .toPromise()

    const result: QueryResponse = {
      totalRecords: count,
      totalPages: Math.ceil(count / args.limit),
      page: args.page,
      limit: args.limit,
      ...data
    }

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

    return result
  }
Example #9
Source File: mentor.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Get('submissions')
  @HttpCode(HttpStatus.OK)
  @ApiResponse({ status: HttpStatus.OK, type: PagedListSubmissionDto })
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.MENTOR)
  @ApiBearerAuth()
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
  async getSubmissions(
    @Query() query: FindDto,
    @Req() req: Request
  ): Promise<PagedListSubmissionDto> {
    const { skip, limit, search, opts } = query;
    const conditions = search && JSON.parse(search);
    const options = opts && JSON.parse(opts);
    const mentorId = req.user['userId'];
    const submissions = await this.SubmissionModel.find(
      { ...conditions, mentor: mentorId },
      null,
      { ...options, limit, skip }
    );

    const items = plainToClass(SubmissionDto, submissions, {
      enableImplicitConversion: true,
      excludeExtraneousValues: true
    }) as any;
    const totalCount = await this.mentorService.countSubmissions(mentorId);
    return { totalCount, items };
  }
Example #10
Source File: notification.controller.ts    From aws-nestjs-starter with The Unlicense 6 votes vote down vote up
@Get()
  find(@Query() { userId, targetId }: { userId?: string; targetId?: string }) {
    if (userId && !targetId) {
      return this.notificationService.findByUserId(userId);
    }
    if (targetId && !userId) {
      return this.notificationService.findByTargetId(targetId);
    }
    throw new BadRequestException();
  }
Example #11
Source File: login.controller.ts    From life-helper-backend with MIT License 6 votes vote down vote up
/**
   * 扫码登录
   *
   *
   * ### 说明
   *
   * ```markdown
   * 1. 这个 API 可能存在高负载,Web 端使用“轮询”(间隔 1 秒)的方式查询扫码结果。
   * ```
   */
  @Get('scan')
  async scanLogin(@Query() query: ScanLoginQueryDto): Promise<ScanLoginResponseDto> {
    const code = query.code

    const authen = await this.qrcodeService.query(code)

    if (authen.status === AuthenticationStatus.Confirmed) {
      /** 登录凭证有效时长:10 天 */
      const expiration = 3600 * 24 * 10

      /** 登录凭证 */
      const token = await this.tokenService.createToken(authen.confirmUserId, expiration)

      const status = authen.status

      await this.qrcodeService.consume(code)

      return { status, token, expiration }
    } else {
      return { status: authen.status }
    }
  }
Example #12
Source File: blocks.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@ApiOperation({ summary: `Gets a specific block by 'hash' or 'sequence'` })
  @Get('find')
  async find(
    @Query(
      new ValidationPipe({
        errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        transform: true,
      }),
    )
    { hash, sequence, with_transactions }: BlockQueryDto,
  ): Promise<SerializedBlock | SerializedBlockWithTransactions> {
    const block = await this.blocksService.find({
      hash,
      sequence,
      withTransactions: with_transactions,
    });
    if (block !== null && 'transactions' in block) {
      return serializedBlockFromRecordWithTransactions(block);
    } else if (block !== null) {
      return serializedBlockFromRecord(block);
    } else {
      throw new NotFoundException();
    }
  }
Example #13
Source File: admins.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
// TODO @yashmurty : Investigate pagination for this later.
  @UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Get all admin users' })
  @ApiOkResponse({ type: [Admin] })
  @Get('/users')
  async getAdminUsers(@Request() req, @Query() query: PaginationParamsDto): Promise<Admin[]> {
    const requestAdminUser: RequestAdminUser = req.user
    return this.adminsService.findAllAdminUsers(requestAdminUser, query.limit, query.offset)
  }
Example #14
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 } };
  }