@nestjs/common#Res TypeScript Examples

The following examples show how to use @nestjs/common#Res. 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 8 votes vote down vote up
@Get(':id')
  @ApiOperation({ summary: '유저 정보 조회 API' })
  @ApiOkResponse({
    description: 'Id가 일치하는 유저 정보를 조회한다.',
    type: UserResponseDto,
  })
  async findOne(
    @Param('id', new ParseIntPipe()) id: number,
    @Res() res: Response,
  ) {
    const responseDto = await this.userService.findById(id);

    return res.status(HttpStatus.OK).json(instanceToPlain(responseDto));
  }
Example #2
Source File: user.controller.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@UseGuards(FtAuthGuard)
  @Get('login/callback')
  async callback(@Req() req: any, @Res({ passthrough: true }) res: Response) {
    if (req.user) {
      const token = await this.userService.login(req.user);
      res.cookie('w_auth', token);
      res.status(302).redirect('/submit');
    }
  }
Example #3
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 #4
Source File: app.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiOkResponse({
    type: Buffer,
    description: 'returns a favicon',
  })
  @Get('favicon.ico')
  async getFavicon(@Res() res: ExpressResponse) {
    fs.createReadStream(`${__dirname}/../../../public/favicon.png`)
      .on('data', (chunk: Buffer) => {
        res.write(chunk);
      })
      .on('close', () => {
        res.end();
      });
  }
Example #5
Source File: project.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Get('/:id/attributions/download')
  @Header('Content-Type', 'text/plain')
  @Header('Content-Disposition', 'attachment; filename=attribution.txt')
  async attributionsDownload(@Param('id') id: string, @Res() res: Response): Promise<any> {
    const project = await this.service.db.findOne(Number(id));
    if (project) {
      const attribution = await this.service.getprojectAttribution(project);
      return res.status(200).send(attribution.licenseText).end();
    }
  }
Example #6
Source File: file.controller.ts    From whispr with MIT License 6 votes vote down vote up
@Get('*')
  async getFile(@Param('*') key: string, @Res() response: FastifyReply): Promise<void> {
    try {
      const file = await this.fileService.getFile(key);
      response.type(file.ContentType);
      response.send(file.Body);
    } catch (error) {
      Logger.error(error);
      response.status(404);
      response.send();
    }
  }
Example #7
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 #8
Source File: LocalBlueprintController.ts    From rewind with MIT License 6 votes vote down vote up
@Get(":md5hash/folder/:file")
  async redirectToFolder(@Res() res: Response, @Param("md5hash") md5hash: string, @Param("file") file: string) {
    const blueprintMetaData = await this.blueprint(md5hash);
    const { folderName } = blueprintMetaData;
    // We need to encode the URI components for cases such as:
    // "E:\osu!\Songs\1192060 Camellia - #1f1e33\Camellia - #1f1e33 (Realazy) [Amethyst Storm].osu"
    // The two `#` characters need to be encoded to `%23` in both cases.
    const url = `/static/songs/${encodeURIComponent(folderName)}/${encodeURIComponent(file)}`;
    res.redirect(url);
  }
Example #9
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 #10
Source File: RemixController.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
@All("*")
  handler(
    @Req() request: Request,
    @Res() response: Response,
    @Next() next: NextFunction,
    @Body() body: any
  ) {
    if (this.isStaticAsset(request)) return next();
    this.purgeRequireCacheInDev();

    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 #11
Source File: app.controller.ts    From nestjs-file-streaming with MIT License 6 votes vote down vote up
@ApiOperation({ summary: 'Download a file.' })
  @Get(':id')
  downloadFile(
    @Param('id') id: string,
    @Req() request: Request,
    @Res({ passthrough: true }) response: Response,
  ): Promise<StreamableFile> {
    return this.appService.download(id, request, response)
  }
Example #12
Source File: market.controller.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
@Get('market/*')
  handleMarket(@Req() req: Request, @Res() res: Response) {
    const extension = path.extname(req.path);
    if (!extension) {
      res.sendFile(path.join(staticDir, 'market', 'index.html'));
    } else {
      res.sendFile(path.join(publicDir, req.path));
    }
  }
Example #13
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 #14
Source File: auth.controller.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
@UseGuards(LocalAuthGuard)
  @Post('login')
  login(@Req() req: AuthenticatedRequest, @Res() res: Response): Observable<Response> {
    return this.authService.login(req.user)
      .pipe(
        map(token => {
          return res
            .header('Authorization', 'Bearer ' + token.access_token)
            .json(token)
            .send()
        })
      );
  }
Example #15
Source File: auth.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@ApiExcludeEndpoint()
  @Post('login')
  async login(@Req() req: Request, @Res() res: Response): Promise<void> {
    if (this.config.get<boolean>('DISABLE_LOGIN')) {
      throw new UnauthorizedException();
    }

    let email;

    const { authorization } = req.headers;
    if (!authorization) {
      throw new UnauthorizedException();
    }

    try {
      email = await this.magicLinkService.getEmailFromHeader(authorization);
    } catch {
      throw new UnauthorizedException();
    }

    if (email) {
      const user = await this.usersService.findByEmail(email);
      if (user) {
        await this.usersService.updateLastLoginAt(user);
      } else {
        throw new UnauthorizedException({ error: 'user_invalid' });
      }
    }

    res.sendStatus(HttpStatus.OK);
  }
Example #16
Source File: auth.controller.ts    From Phantom with MIT License 6 votes vote down vote up
@Get('google/redirect')
  @UseGuards(AuthGuard('google'))
  async googleAuthRedirect(@Req() req, @Res() res) {
    const data = await this.authService.googleLogin(req);
    if (data) {
      res.redirect(
        process.env.FRONT_BASE_URL +
          '/aouth/google?token=' +
          data.token +
          '&type=' +
          data.type,
      );
    } else {
      throw new NotFoundException();
    }
  }
Example #17
Source File: transaction.controller.ts    From bank-server with MIT License 6 votes vote down vote up
@Get('/:uuid/:locale/confirmationFile')
  @HttpCode(HttpStatus.OK)
  @Roles(RoleType.USER, RoleType.ADMIN, RoleType.ROOT)
  @ApiOkResponse({
    status: HttpStatus.OK,
    description: 'get authorization key',
    type: TransactionAuthorizationKeyPayloadDto,
  })
  async getConfirmation(
    @Param('uuid') uuid: string,
    @Param('locale') locale: string,
    @AuthUser() user: UserEntity,
    @Res() res: Response,
  ): Promise<void> {
    const compiledHtmlContent = await this._transactionService.getConfirmationDocumentFile(
      user,
      uuid,
      locale,
    );
    const buffer = await this._transactionService.htmlToPdfBuffer(
      compiledHtmlContent,
    );
    const stream = this._transactionService.getReadableStream(buffer);

    res.set({
      'Content-Type': 'application/pdf',
      'Content-Length': buffer.length,
    });

    stream.pipe(res);
  }
Example #18
Source File: banner.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Get('/:bannerSlug/image')
	public async getImage(@Param('bannerSlug') bannerSlug: string, @Res() res): Promise<any> {
		const banner = await this.bannerService.findOne({ slug: bannerSlug });

		if (!banner) {
			throw new NotFoundException()
		}

		return res.redirect(302, banner.image);
	}
Example #19
Source File: login.controller.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
// NOTE: Although the two routes below are on the backend,
  // they are meant to be visited by the browser so a cookie can be set

  // This is the real admin entry point
  @Get('/login/entry')
  async enterFromKhoury(
    @Res() res: Response,
    @Query('token') token: string,
  ): Promise<void> {
    const isVerified = await this.jwtService.verifyAsync(token);

    if (!isVerified) {
      throw new UnauthorizedException();
    }

    const payload = this.jwtService.decode(token) as { userId: number };

    if (payload === null || payload === undefined) {
      console.error('Decoded JWT is invalid');
      throw new HttpException(
        ERROR_MESSAGES.loginController.invalidPayload,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }

    this.enter(res, payload.userId);
  }
Example #20
Source File: pusher.controller.ts    From nativescript-plugins with Apache License 2.0 6 votes vote down vote up
@Post('auth')
  handleAuth(@Body() body, @Res() res, @Query() query, @Request() req) {
    const socketId = body.socket_id;
    const channel = body.channel_name;
    const presenceData = {
      user_id: 'unique_user_id_868',
      user_info: {name: `${query.first} ${query.last}`, twitter_id: '@triniwiz', place: req.headers.place},
    };
    const auth = this.pusherService.pusher.authenticate(socketId, channel, presenceData);
    return res(auth);
  }
Example #21
Source File: app.controller.ts    From 42_checkIn with GNU General Public License v3.0 5 votes vote down vote up
@Get('token/:token')
  async getToken(
    @Param('token') ftToken: string,
    @Res({ passthrough: true }) res: Response,
  ) {
    const token = await this.appService.getToken(ftToken);
    res.cookie('w_auth', token);
  }
Example #22
Source File: app.controller.ts    From pelisplushd with MIT License 5 votes vote down vote up
@Get('/GetAllMovies/:page')
  async getALLMovies(@Res() res, @Param('page') page: number) {
    const movies = await this.service.getALLMovies(page);
    return res.status(HttpStatus.OK).json({movies: movies[0]});
  }
Example #23
Source File: health.controller.ts    From nestjs-api-example with MIT License 5 votes vote down vote up
@Get('/health')
  @ApiOperation({ description: 'health check' })
  healthCheck(@Res() res: Response) {
    const result: string = this.appService.sendOk();

    return res.status(HttpStatus.OK).send(result);
  }
Example #24
Source File: account.controller.ts    From uniauth-backend with MIT License 5 votes vote down vote up
/**
   * To handle login form submission on client-initiated-auth
   */
  @Post('o/login')
  @UsePipes(
    new ValidationPipe({
      disableErrorMessages: false,
    }),
  )
  async processLoginPageAsAuth(@Res() res: Response, @Body() incomingAuthDto: IncomingAuthLoginDto) {
    const { client_id } = incomingAuthDto;

    /**
     * validate and get application details from incoming dto
     */
    try {
      const applicationDetails = await this.accountService.validateAccessRequest(incomingAuthDto);

      /**
       * ensure authentication for users
       */
      try {
        const { token, user } = await this.accountService.authenticateAndGenerateToken(incomingAuthDto);

        /** push user into application participant list set */
        this.applicationService.pushUserIntoApplicationParticipantList(applicationDetails, user);
        this.userService.pushApplicationIntoUserParticipantList(applicationDetails, user);
        res.redirect(`${incomingAuthDto.redirect_uri}/?access_token=${token}`);
      } catch (e) {
        /**
         * Render login page with error message from server
         */
        this.logger.error(`${e.message} for ${client_id}`);
        return res.render('account/o/login', {
          app: applicationDetails,
          project_name: appData.Name,
          server: { message: e.message },
        });
      }
    } catch (e) {
      /**
       * Render error page with validation error mesage
       */
      this.logger.error(`POST ${e.message} for ${client_id}`);
      return res.render('error', e.response);
    }
  }
Example #25
Source File: LocalBlueprintController.ts    From rewind with MIT License 5 votes vote down vote up
@Get(":md5hash")
  async getBlueprintByMD5(@Res() res: Response, @Param("md5hash") md5hash: string) {
    const blueprintMetaData = await this.blueprintService.getBlueprintByMD5(md5hash);
    res.json(blueprintMetaData);
    // const path = this.songsFolder(blueprintMetaData.folderName, blueprintMetaData.osuFileName);
  }
Example #26
Source File: health.controller.base.ts    From amplication with Apache License 2.0 5 votes vote down vote up
@Get("live")
  healthLive(@Res() response: Response): Response<void> {
    return response.status(HttpStatus.NO_CONTENT).send();
  }
Example #27
Source File: health-check.controller.ts    From nestjs-rest-microservices with MIT License 5 votes vote down vote up
@Get()
  healthCheck(@Res() res: Response) {
    res.status(HttpStatus.OK).send('OK')
  }
Example #28
Source File: version.controller.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
@Get()
  handle(@Res() res: Response) {
    res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0');
    res.sendFile(path.resolve(publicDir, 'version.json'));
  }
Example #29
Source File: product.controller.ts    From nest-js-products-api with MIT License 5 votes vote down vote up
@Get()
  public async getProducts(@Res() request): Promise<any> {
    const products = await this.getAllProductsUseCase.handler();
    return request.status(HttpStatus.OK).json(products);
  }