@nestjs/common#Controller TypeScript Examples

The following examples show how to use @nestjs/common#Controller. 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: app.controller.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@Controller('api')
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
  @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 #2
Source File: api.controller.ts    From nestjs-consul with MIT License 6 votes vote down vote up
@Controller()
export class ApiController {
	constructor(private readonly consul: ConsulService<ConfigInterface>) {
	}

	async testConfig() {
		return this.consul.configs;
	}

	async setConfig(value: string) {
		return this.consul.set<ITest>('am-cli/test', {
			valueNum: 1,
			valuesString: value
		});
	}

	async getConfig() {
		return this.consul.get<ITest>('am-cli/test');
	}

	async deleteConfig() {
		return this.consul.delete('am-cli/test');
	}
}
Example #3
Source File: app.controller.ts    From nr-apm-stack with Apache License 2.0 6 votes vote down vote up
@Controller()
/**
 * Generic NestJS app controller.
 */
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post()
  /**
   * Handle data received as a mock Kinesis event.
   */
  handleData(@Body() data: OsDocumentData, @Query('print') print: string): Promise<OpenSearchBulkResult> {
    return this.appService.handleKinesisEvent(data, print === 'true');
  }
}
Example #4
Source File: application.controller.ts    From nest-nuxt-starter with MIT License 6 votes vote down vote up
@Controller()
export class ApplicationController {
  constructor(private readonly appService: ApplicationService) {}

  @Get('/ping')
  ping(): string {
    return 'pong';
  }

  @Get('/users')
  async fetchAll(): Promise<User[]> {
    return this.appService.fetchAll();
  }
}
Example #5
Source File: health.controller.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
@Controller('')
@ApiTags('')
export class HealthController {
  constructor(private readonly appService: HealthService) {}

  @Get('/health')
  @ApiOperation({ description: 'health check' })
  healthCheck(@Res() res: Response) {
    const result: string = this.appService.sendOk();

    return res.status(HttpStatus.OK).send(result);
  }
}
Example #6
Source File: status.controller.ts    From nest-react with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Controller()
export class StatusController {
  constructor(private readonly statusService: StatusService) {}

  @Get()
  getStatus(): string {
    return this.statusService.getStatus();
  }

  @Get('version')
  getVersion(): Dictionary<string> {
    return this.statusService.getVersion();
  }
}
Example #7
Source File: app.controller.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly authService: AuthService) {}

  @UseGuards(LocalAuthGuard)
  @Post('auth/login')
  async login(@Request() req: Express.Request) {
    return this.authService.login(req.user);
  }

  @Post('auth/register')
  async register(@Body() body: Partial<UserEntity>) {
    try {
      const salt = await genSalt(10);
      const { password, ...reset } = body;
      const u: Partial<UserEntity> = {
        salt,
        ...reset,
        password: hashSync(password, salt),
        role: Roles.user,
      };
      const user = await this.authService.register(u);
      const logedInUser = await this.authService.login(user);
      delete logedInUser.password;
      delete logedInUser.salt;
      return logedInUser;
    } catch (error) {
      throw error;
    }
  }
}
Example #8
Source File: app.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Controller()
export default class AppController {
  constructor(private readonly appService: AppService) {}

  @ApiOkResponse({ description: 'Returns you Hello world!' })
  @Get()
  sayHello(): string {
    return this.appService.getHello();
  }
}
Example #9
Source File: app.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('/status')
  @ApiResponse({ status: 200, type: AppStatus })
  appStatus(): string {
    return this.appService.appStatus();
  }
}
Example #10
Source File: app.controller.ts    From The-TypeScript-Workshop with MIT License 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(@Query('name') name = 'World'): Promise<string> {
    return this.appService.getHello(name);
  }
}
Example #11
Source File: health.controller.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
@Controller('health')
export class HealthController {
  constructor(
    private readonly eventStoreHealthIndicator: EventStoreHealthIndicator,
  ) {}

  @Get()
  @HealthCheck()
  public async healthCheck(): Promise<HealthIndicatorResult> {
    return this.eventStoreHealthIndicator.check();
  }
}
Example #12
Source File: create-user.http.controller.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
@Controller(routesV1.version)
export class CreateUserHttpController {
  constructor(private readonly commandBus: CommandBus) {}

  @Post(routesV1.user.root)
  @ApiOperation({ summary: 'Create a user' })
  @ApiResponse({
    status: HttpStatus.OK,
    type: IdResponse,
  })
  @ApiResponse({
    status: HttpStatus.CONFLICT,
    description: UserAlreadyExistsError.message,
  })
  @ApiResponse({
    status: HttpStatus.BAD_REQUEST,
  })
  async create(@Body() body: CreateUserRequest): Promise<IdResponse> {
    const command = new CreateUserCommand(body);

    const result: Result<
      ID,
      UserAlreadyExistsError
    > = await this.commandBus.execute(command);

    // Deciding what to do with a Result (similar to Rust matching)
    // if Ok we return a response with an id
    // if Error decide what to do with it depending on its type
    return match(result, {
      Ok: id => new IdResponse(id.value),
      Err: error => {
        if (error instanceof UserAlreadyExistsError)
          throw new ConflictException(error.message);
        throw error;
      },
    });
  }
}
Example #13
Source File: app.controller.ts    From whispr with MIT License 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}
Example #14
Source File: app.controller.ts    From adminjs-nestjs with MIT License 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  public getHello(): string {
    return this.appService.getHello();
  }

  @Post()
  public postHello(@Body() testBody: Hello): string {
    return testBody.hello;
  }
}
Example #15
Source File: app.controller.ts    From svvs with MIT License 6 votes vote down vote up
/**
 * Base controller backend-api app
 */
@Controller()
export class AppController {
  /**
   * Return welcome string
   */
  @Get()
  getData() {
    return {message: 'Welcome to backend/api!'}
  }
}
Example #16
Source File: app.controller.ts    From rewind with MIT License 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getData() {
    return this.appService.getData();
  }
}
Example #17
Source File: datastore.controller.ts    From runebot with MIT License 6 votes vote down vote up
@Controller()
export class DataStoreController {
  constructor(private readonly service: DataStoreService) {}

  @Get('wizard')
  async getWizard(@Query('id') id: string): Promise<Wizard> {
    return await this.service.getWizard(id);
  }
}
Example #18
Source File: app.controller.ts    From nest_transact with MIT License 6 votes vote down vote up
@Controller()
@ApiTags('app')
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly appServiceV2: PurseSavingService,
    /**
     * This is deprecated in typeorm for now,
     * but the DataSource object still not injectable in Nest.js,
     * because of that we should use deprecated [Connection] until [DataSource]
     * will be injectable
     */
    private readonly connection: Connection,
  ) {
  }

  @Post('transfer')
  @ApiResponse({
    type: TransferOperationResultDto,
  })
  async makeRemittanceWithTransaction(@Body() remittanceDto: TransferParamsDTO) {
    return this.connection.transaction(manager => {
      return this.appService.withTransaction(manager)/* <-- this is interesting new thing */.makeTransfer(remittanceDto.userIdFrom, remittanceDto.userIdTo, remittanceDto.sum, remittanceDto.withError);
    });
  }
}
Example #19
Source File: app.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @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 #20
Source File: auth.controller.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@Controller('/')
export class AuthController {
  private host: string;
  constructor(
    private readonly authService: AuthService,
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger
  ) {
    this.host = process.env.CLIENT_HOST || 'http://localhost:3001';
  }

  @UseInterceptors(MorganInterceptor('combined'))
  @Get('/github')
  @UseGuards(AuthGuard('github'))
  async github() {
    return;
  }

  @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 #21
Source File: TodoListEventsController.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
@Controller("events/l")
export class TodoListEventsController {
  constructor(
    @Inject(AUTHENTICATOR)
    private readonly authenticator: Authenticator,
    private readonly todoListEvents: TodoListEventsConsumer
  ) {}

  @Sse("/:todoListId")
  async getEvents(@Param("todoListId") todoListId: string) {
    const currentUser = await this.authenticator.currentUser();
    const heartbeat$ = interval(30_000).pipe(
      map(() => ({ type: "heartbeat", data: "_" }))
    );

    const updates$ = this.todoListEvents.events.pipe(
      filter(
        (event) =>
          event.todoListId === todoListId &&
          event.sessionId !== currentUser.sessionId
      ),
      map((event) => ({ type: "update", data: event.type } as MessageEvent))
    );

    return merge(heartbeat$, updates$);
  }
}
Example #22
Source File: app.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@Controller('')
export class AppController {
  private readonly logger = new Logger(AppController.name);

  @ApiExcludeEndpoint()
  @Get()
  @Redirect('/api/docs')
  getDocs() {
    this.logger.log('Redirecting to /api/docs');
  }
}
Example #23
Source File: UserQueriesController.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Controller()
export class UserQueriesController {
  constructor(private readonly userQueriesService: UserQueriesService) {}

  @GrpcMethod('IdentityService', 'getUsers')
  getProducts({ pager, order, filters }) {
    return this.userQueriesService.getUsers(pager, order, filters)
  }
}
Example #24
Source File: users.controller.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
@Controller()
export class UsersController {
  constructor(@Inject('UsersService') private readonly usersService: UsersService, private readonly logger: PinoLogger) {
    logger.setContext(UsersController.name)
  }

  @GrpcMethod('UsersService', 'findAll')
  async findAll(query: Query): Promise<UserServiceQueryResult> {
    this.logger.info('UsersController#findAll.call', query)

    const result: Array<User> = await this.usersService.findAll({
      attributes: !isEmpty(query.attributes) ? query.attributes : undefined,
      where: !isEmpty(query.where) ? JSON.parse(query.where) : undefined,
      order: !isEmpty(query.order) ? JSON.parse(query.order) : undefined,
      offset: query.offset ? query.offset : 0,
      limit: query.limit ? query.limit : 25
    })

    this.logger.info('UsersController#findAll.result', result)

    return { data: result }
  }

  @GrpcMethod('UsersService', 'count')
  async count(query: Query): Promise<Count> {
    this.logger.info('UsersController#count.call', query)

    const count: number = await this.usersService.count({
      where: !isEmpty(query.where) ? JSON.parse(query.where) : undefined
    })

    this.logger.info('UsersController#count.result', count)

    return { count }
  }
}
Example #25
Source File: test-controller.ts    From google-recaptcha with MIT License 6 votes vote down vote up
@Controller('test')
export class TestController {
    @Recaptcha()
    submit(): void {}

    @Recaptcha({response: req => req.body.customRecaptchaField})
    submitOverridden(): void {}

    @SetRecaptchaOptions({action: 'TestOptions', score: 0.5})
    @UseGuards(GoogleRecaptchaGuard)
    submitWithSetRecaptchaOptionsDecorator(): void {}
}
Example #26
Source File: app.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Controller()
@ApiTags("Health-Check")
export class AppController {
  constructor(private readonly appService: AppService) { }

  @Get()
  getHello(): string {
    return this.appService.getWelcome();
  }
}
Example #27
Source File: app.controller.ts    From trading-bot with MIT License 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getStatus(): { status: number; body: string } {
    return this.appService.getStatus()
  }
}
Example #28
Source File: app.controller.ts    From nestjs-jaeger-tracing with MIT License 6 votes vote down vote up
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  @ExceptTracing()
  getHello(): string {
    return this.appService.getHello();
  }

  @Get('error')
  getError(@Tracing() tracing: TracingData): never {
    Logger.log({ getError: tracing });
    throw new NotImplementedException();
  }

  @Get('sum')
  execute(): Observable<number> {
    return this.appService.execute();
  }

  @UseInterceptors(TracingInterceptor)
  @MessagePattern({ cmd: 'echoMessage' })
  echoMessage(
    @Tracing() tracing: TracingData,
    @Payload() message: string,
  ): string {
    Logger.log({ echoMessage: tracing });
    return message;
  }
}
Example #29
Source File: app.controller.ts    From bad-cards-game with GNU Affero General Public License v3.0 6 votes vote down vote up
@Controller()
export class AppController {
  @Get('version')
  reportVersion() {
    return { version: process.env.npm_package_version };
  }

  @Get()
  home() {
    return { status: 'ok' };
  }
}