How to use the @nestjs/common.Post function in @nestjs/common

To help you get started, weโ€™ve selected a few @nestjs/common examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github xmlking / ngx-starter-kit / apps / api / src / app / user / email / email.controller.ts View on Github external
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { ApiOAuth2, ApiTags } from '@nestjs/swagger';
import { CurrentUser } from '../../auth/decorators';
import { EmailService } from '../../email';
import { User } from '../user.entity';
import { EmailDto } from './dto/email.dto';

@ApiOAuth2(['read'])
@ApiTags('Email', 'User')
@Controller('email')
export class EmailController {
  constructor(private readonly emailService: EmailService) {}

  // @ApiExcludeEndpoint()
  @Post()
  @HttpCode(HttpStatus.CREATED)
  async sendEmail(@Body() email: EmailDto, @CurrentUser() user: User): Promise {
    return this.emailService.sendMail({
      to: user.email,
      subject: email.title,
      template: 'welcome', // The `.pug` extension is appended automatically.
      context: {
        // Data to be sent to PugJS template files.
        title: email.title,
        comments: email.comments,
        name: email.name,
      },
    });
  }
}
github bojidaryovchev / nest-angular / src / server / modules / auth / auth.controller.ts View on Github external
@Post('twitter/token')
  async requestJsonWebTokenAfterTwitterSignIn(@Req() req: Request): Promise {
    return await this.authService.createToken(req.user);
  }

  @Get('google/uri')
  async requestGoogleRedirectUri(): Promise {
    return await this.authService.requestGoogleRedirectUri();
  }

  @Post('google/signin')
  async googleSignIn(@Req() req: Request): Promise {
    return await this.authService.googleSignIn(req.body.code);
  }

  @Post('google/token')
  async requestJsonWebTokenAfterGoogleSignIn(@Req() req: Request): Promise {
    return await this.authService.createToken(req.user);
  }

  @Get('authorized')
  @Roles('user')
  @UseGuards(AuthGuard('jwt'), RolesGuard)
  public async authorized() {
    console.log('Authorized route...');
  }
}
github ubiq / shokku / src / server / jsonrpc / jsonrpc.controller.ts View on Github external
return this.jsonRpcService.methods(req)
    } catch (err) {
      throw HttpExceptionAdapter.toHttpException(err)
    }
  }

  @Get(':network/:chain/:method')
  getMethod(@NetworkChain() req: NetworkChainRequestEntity) {
    try {
      return this.jsonRpcService.rpcMethod(req)
    } catch (err) {
      throw HttpExceptionAdapter.toHttpException(err)
    }
  }

  @Post(':network/:chain')
  postMethod(@NetworkChain() req: NetworkChainRequestEntity) {
    try {
      return this.jsonRpcService.rpcMethod(req)
    } catch (err) {
      throw HttpExceptionAdapter.toHttpException(err)
    }
  }
}
github BMalaichik / nestjs-starter-kit / packages / backend / src / modules / auth / auth.controller.ts View on Github external
import { ValidationExceptionFilter } from "../../http/filters";
import { InvalidPasswordExceptionFilter } from "./filters/invalid-password.exception-filter";
import { UserLoginDto, ResendInviteDto, ResetPasswordDto } from "./auth.interfaces";


@Controller("/auth")
@UseGuards(AuthorizeGuard)
@UseFilters(InvalidPasswordExceptionFilter, ValidationExceptionFilter)
export class AuthController {

    public constructor(
        @Inject(AuthDiToken.AUTH_SERVICE) private readonly authService: AuthService,
    ) {}

    @HttpCode(200)
    @Post("/login")
    @Public()
    public async login(@Body() userInfo: UserLoginDto): Promise<{ token: string }> {
        return this.authService.login(userInfo);
    }

    @HttpCode(200)
    @Post("/invite/verify")
    @Public()
    public async verifyInvite(@Body("token") token: string): Promise {
        return this.authService.verifyInvite(token);
    }

    @HttpCode(200)
    @Post("/invite/resend")
    @Public()
    public async resendInvite(@Body() data: ResendInviteDto): Promise {
github ZhiXiao-Lin / nestify / server / src / api / controllers / user.controller.ts View on Github external
@Get('details')
    async details(@Query() payload, @CurrentUser() user) {

        payload.userId = user.id;

        return await this.userService.details(payload);
    }

    @Get('current')
    @UseInterceptors(ClassSerializerInterceptor)
    async current(@CurrentUser() user) {
        return await this.userService.findOneById(user.id);
    }

    @Post('apply')
    async apply(@Body() dto: any, @CurrentUser() user) {
        if (!dto.id) dto.id = user.id;
        return await this.userService.applyVolunteer(dto);
    }

    @Put('password')
    @UsePipes(new ValidationPipe())
    async changePassword(@CurrentUser() user, @Body() dto: PasswordDto) {
        return await this.userService.changePassword(user.id, dto);
    }

    @Post()
    async create(@Body() dto: any) {
        return await this.userService.save(dto);
    }
github vellengs / nestx-server / packages / common / src / services / controller.service.ts View on Github external
async findAll(
    @Param("page", new ParseIntPipe()) page: number = 1,
    @Param("size", new ParseIntPipe()) size: number = 10,
    @Query() query: any
  ): Promise> {
    return await this.service.findAll(page, size, query);
  }

  @Get(":id")
  async findOne(
    @Param("id") id: string | number | Date | ObjectID
  ): Promise {
    return await this.service.findOne(id);
  }

  @Post()
  async create(@Body() entity: any): Promise {
    return await this.service.create(entity);
  }

  @Put()
  async update(@Body() entity: any): Promise {
    return await this.service.update(entity);
  }

  @Delete(":id")
  async remove(@Param("id") id: string): Promise {
    return await this.service.remove(id);
  }
}
github Caballerog / clock-in-out / server / src / app.controller.ts View on Github external
import { Get, Controller, Post, Body } from '@nestjs/common';
import { AuthDto } from 'modules/auth/dto/auth.dto';
import { AuthResponseDto } from 'modules/auth/dto/auth.response.dto';
import { AppService } from 'app.service';
import { User } from 'modules/users/entities/user.entity';

@Controller()
export class AppController {
  constructor(private appService: AppService) {}

  @Post('in')
  async authIn(@Body() ticket: AuthDto): Promise {
    return await this.appService.authIn(ticket);
  }

  @Post('out')
  async authOut(@Body() ticket: AuthDto): Promise {
    return await this.appService.authOut(ticket);
  }
  @Get('users')
  async usersTicketing(): Promise<{ users: User[]; timestamp: number }> {
    return await this.appService.usersTicketing();
  }
}
github EndyKaufman / nest-permissions-seed / src / libs / core / controllers / content-types.controller.ts View on Github external
export class ContentTypesController {
    constructor(
        @InjectRepository(ContentType)
        private readonly contentTypeRepository: Repository
    ) {

    }
    @Roles('isSuperuser')
    @Permissions('add_content-type')
    @HttpCode(HttpStatus.CREATED)
    @ApiResponse({
        status: HttpStatus.CREATED, type: OutContentTypeDto,
        description: 'The record has been successfully created.'
    })
    @ApiResponse({ status: HttpStatus.FORBIDDEN, description: 'Forbidden.' })
    @Post()
    async create(
        @Body() dto: InContentTypeDto
        ) {
        try {
            let object = plainToClass(ContentType, dto);
            object = await this.contentTypeRepository.save(object)
            return plainToClass(OutContentTypeDto, object);
        } catch (error) {
            throw error;
        }
    }
    @Roles('isSuperuser')
    @Permissions('change_content-type')
    @HttpCode(HttpStatus.OK)
    @ApiResponse({
        status: HttpStatus.OK, type: OutContentTypeDto,
github neoteric-eu / nestjs-auth / src / app / auth / auth.controller.ts View on Github external
@Post('password/new')
	@HttpCode(204)
	@ApiImplicitBody({ required: true, type: PasswordTokenDto, name: 'PasswordTokenDto' })
	@ApiResponse({ status: 204, description: 'NO CONTENT' })
	public async passwordNew(@Body() body: PasswordTokenDto): Promise {
		this.logger.debug(`[passwordNew] Token ${body.resetToken}`);
		const token = await verifyToken(body.resetToken, config.session.password_reset.secret);
		const user = await this.userService.updatePassword({id: token.id, password: body.password});
		this.logger.debug(`[passwordNew] Send change password email for user ${user.email}`);
		this.client.send({cmd: USER_CMD_PASSWORD_NEW}, user).subscribe(() => {}, error => {
			this.logger.error(error, '');
		});
	}

	@Post('refresh')
	@HttpCode(200)
	@ApiResponse({ status: 200, description: 'OK', type: JwtDto })
	public async refreshToken(@Body() body: RefreshTokenDto): Promise {
		this.logger.debug(`[refresh] Token ${body.refreshToken}`);
		const token = await verifyToken(body.refreshToken, config.session.refresh.secret);
		return await createAuthToken({id: token.id});
	}

	@Post('facebook')
	@HttpCode(200)
	@UseGuards(AuthGuard('facebook-token'))
	@ApiResponse({ status: 200, description: 'OK', type: JwtDto })
	public async fbSignIn(@Body() fbToken: FacebookTokenDto, @Profile() profile: FacebookProfile): Promise {
		this.logger.debug(`[fbSignIn] Facebook socialId ${profile.id}`);
		let user = await this.userService.findOne({where: {socialId: profile.id}});
		if (!user) {
github RobertYoung / mean-stack-typescript-docker / server / src / users / users.controller.ts View on Github external
@Controller()
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  async getAll(): Promise {
    return this.usersService.findAllUsers();
  }

  @Get('/:id')
  public async getUser(@Param('id') id) {
    return await this.usersService.getUser(id);
  }

  @Post()
  async createUser(@Body() user: User) {
    return this.usersService.createUser(user);
  }

  @Put('/:id')
  public async updateUser(@Param('id') id, @Body() user: User) {
    return this.usersService.updateUser(id, user);
  }

  @Delete('/:id')
  public async deleteUser(@Param('id') id) {
    return this.usersService.deleteUser(id);
  }
}