@nestjs/common#Post TypeScript Examples

The following examples show how to use @nestjs/common#Post. 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
  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: plugin-newsletter.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
    /** Use ThrottlerGuard to limit number of requests from one IP address. Allow max 4 requests in 20 seconds: */
    @Throttle(4, 20)
    @ApiOperation({ description: 'Post email to subscribe for newsletters' })
        status: 200,
        type: Boolean,
    @ApiBody({ type: PluginNewsletterSubscription })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async placeSubscription(@Body() input: PluginNewsletterSubscription): Promise<boolean | undefined> {
        const email = input?.email;
        if (!email || !/\[email protected]\S+\.\S+/.test(email)) {
            throw new HttpException(`Invalid email`, HttpStatus.BAD_REQUEST);

        const hasSubscribed = await getManager().findOne(PluginNewsletter, {
            where: {
        if (hasSubscribed) return true;

        const newsletter = new PluginNewsletter();
        newsletter.email = email;
        await getManager().save(newsletter);
        return true;
Example #3
Source File: app.controller.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
  async register(@Body() body: Partial<UserEntity>) {
    try {
      const salt = await genSalt(10);
      const { password, ...reset } = body;
      const u: Partial<UserEntity> = {
        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 #4
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
  @ApiBody({ type: SignInDto })
  @ApiMovedPermanentlyResponse({ description: 'Returns 301 if login is ok' })
    description: 'Returns 500 if smth has been failed',
  public login(): void {}
Example #5
Source File: bom-license-exception.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
  @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(
        `A license exception has been created for project [${project.name}].`,

    return exception;
Example #6
Source File: create-user.http.controller.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
  @ApiOperation({ summary: 'Create a user' })
    status: HttpStatus.OK,
    type: IdResponse,
    status: HttpStatus.CONFLICT,
    description: UserAlreadyExistsError.message,
    status: HttpStatus.BAD_REQUEST,
  async create(@Body() body: CreateUserRequest): Promise<IdResponse> {
    const command = new CreateUserCommand(body);

    const result: Result<
    > = 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 #7
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
  async processLoginPage(@Res() res: Response, @Body() loginDto: LoginDto) {
    try {
      const user = await this.userService.login(loginDto);
      const jwtData = { id: user._id, email: user.collegeEmail };
      const cookieData = await this.authService.generateJwt(jwtData);
      res.cookie('vitAuth', cookieData);
      //   res.render('profile/homepage', user);
    } catch (e) {
      return res.render('account/login', { server: { message: e.message }, project_name: appData.Name });
Example #8
Source File: DesktopConfigController.ts    From rewind with MIT License 6 votes vote down vote up
  async saveOsuStablePath(@Res() res: Response, @Body() { osuStablePath }: UpdateOsuStablePathDto) {
    this.logger.log(`Received request to update the OsuStablePath to ${osuStablePath}`);

    const sanityCheckPassed = await osuFolderSanityCheck(osuStablePath);
    if (sanityCheckPassed) {
      await this.desktopConfigService.saveOsuStablePath(osuStablePath);
      res.status(200).json({ result: "OK" });
    } else {
      res.status(400).json({ error: `Given folder '${osuStablePath}' does not seem to be a valid osu!stable folder` });
Example #9
Source File: app.controller.ts    From nest_transact with MIT License 6 votes vote down vote up
    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 #10
Source File: app.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
    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 #11
Source File: paddle.controller.ts    From amplication with Apache License 2.0 6 votes vote down vote up
  async paddleWebhook(
    @Body() body: PaddleEvent,
    @Res() response: Response
  ): Promise<void> {
    await this.paddleService.handlePaddleWebhook(body);
Example #12
Source File: app.controller.ts    From nestjs-keycloak-admin with MIT License 6 votes vote down vote up
  async create(@Request() req: any): Promise<Resource> {
    let resource = new Resource({
      name: 'resource',
      displayName: 'My Resource'
    } as UMAResource)
      .setScopes([new Scope('organization:read'), new Scope('organization:write')])
        valid: true,
        types: ['customer', 'any']

    resource = await this.keycloak.resourceManager.create(resource)

    // create organization on your resource server and add link to resource.id, to access it later.

    return resource 
Example #13
Source File: sites.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
  @ApiOperation({ summary: 'Creates a new site and its site application' })
    @Req() request: AuthRequest,
    @Body('siteApplication') siteApplication: CreateSiteApplicationDto,
    @Body('site') site: CreateSiteDto,
  ): Promise<SiteApplication> {
    return this.sitesService.create(siteApplication, site, request.user);
Example #14
Source File: organizations.controller.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
  @Header('Content-Type', 'application/json')
  async createOrganizationComment(@Param('name') name: string, @Body() comment: CommentDto): Promise<Comment> {
    this.logger.info('OrganizationController#createOrganizationComment.call', name)

    const organization: Organization = await this.organizationsService

    if (!organization) throw new NotFoundException('NOT_FOUND', 'Organization not found.')

    const result: Comment = await this.commentsService
        organization: organization.id

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

    return result
Example #15
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
  @ApiOkResponse({ type: LoginResDto })
  @ApiUnauthorizedResponse({ type: ApiException })
  async login(
    @Body() _: LoginReqDto,
    @Req() req?: Request
  ): Promise<LoginResDto> {
    const accessToken = await this.authService.getAuthToken(req.user as User);
    return { accessToken };
Example #16
Source File: announcement.controller.ts    From edu-server with MIT License 6 votes vote down vote up
  @ApiOperation({ summary: 'add an Announcement' })
  async addAnnouncement(@Body() CreateAnnouncementDTO: CreateAnnouncementDTO) {
    return await this.announcementService.addAnnouncement(
Example #17
Source File: app.controller.ts    From nestjs-file-streaming with MIT License 6 votes vote down vote up
    summary: 'Upload a file.',
    requestBody: {
      content: {
        'multipart/form-data': {
          schema: {
            type: 'object',
            properties: { file: { type: 'string', format: 'binary' } },
    schema: {
      properties: {
        id: {
          type: 'string',
          example: '5e2b4cb75876c93e38b6e6aa',
  uploadFile(@Req() request: Request): Promise<{ id: string }> {
    return this.appService.upload(request)
Example #18
Source File: test.controller.ts    From nestjs-form-data with MIT License 6 votes vote down vote up
  uploadSingleFile(@Body() singleFileDto: UploadSingleFileDto) {
    return {
      filename: singleFileDto.file.originalName,
      mimetype: singleFileDto.file.mimetype,
Example #19
Source File: api-gateway.controller.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
  async rpc(@Req() { body, ip }: { body: IRpcRequest; ip: string }) {
    if (Array.isArray(body)) {
      const testBalance = body.find((value) => value.method === 'testBalance.get');
      if (testBalance && !(await verifyCaptcha(testBalance.params.token))) {
        return getResponse(body, errors.Forbidden.name);
    } else {
      if (body.method === 'testBalance.get' && !(await verifyCaptcha(body.params['token']))) {
        return getResponse(body, errors.Forbidden.name);
    const response = await this.service.requestMessage(body);
    return response;
Example #20
Source File: auth.controller.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
  login(@Req() req: AuthenticatedRequest, @Res() res: Response): Observable<Response> {
    return this.authService.login(req.user)
        map(token => {
          return res
            .header('Authorization', 'Bearer ' + token.access_token)
Example #21
Source File: offer.controller.ts    From pandaid with MIT License 6 votes vote down vote up
  @UseGuards(JwtAuthGuard, RolesGuard)
  public create(@Body() createRequestRequest: OfferBase) {
    const id = this.offerService.getOffers().length
      id: id,
      state: OfferStates.OPEN
      //TODO add fields