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

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

        const newsletter = new PluginNewsletter();
        newsletter.email = email;
        await getManager().save(newsletter);
        return true;
    }
Example #2
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 #3
Source File: auth.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Post('login')
    @UseGuards(ThrottlerGuard)
    @Throttle(10, 30)
    @ApiOperation({
        description: 'Authenticates a human user via cookies.',
    })
    @ApiBody({ type: LoginDto })
    @ApiResponse({
        status: 200,
        type: UserDto
    })
    async login(@Request() req: TRequestWithUser, @Response() response: FastifyReply, @Body() input: LoginDto) {

        let authInfo: TLoginInfo = null;
        try {
            authInfo = await this.authService.logIn(input);
        } catch (error) {
            logger.error(error);
        }

        if (!authInfo) {
            response.status(403);
            response.send({ message: 'Login failed', statusCode: 403 });
            return;
        }

        req.user = authInfo.userInfo;

        if (authInfo.refreshToken && authInfo.accessToken) {
            this.authService.setAccessTokenCookie(response, req,
                this.authService.getAccessTokenInfo(authInfo.accessToken));

            this.authService.setRefreshTokenCookie(response, req,
                this.authService.getRefreshTokenInfo(authInfo.refreshToken));
        }
        response.code(200).send(authInfo.userDto);
    }
Example #4
Source File: app.controller.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@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 #5
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiCookieAuth()
  @ApiBody({ type: SignInDto })
  @ApiMovedPermanentlyResponse({ description: 'Returns 301 if login is ok' })
  @ApiInternalServerErrorResponse({
    description: 'Returns 500 if smth has been failed',
  })
  @HttpCode(HttpStatus.MOVED_PERMANENTLY)
  @UseGuards(LocalAuthGuard)
  @Post('/login')
  @Redirect('/v1/home')
  public login(): void {}
Example #6
Source File: bom-license-exception.controller.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Post('/')
  @UseInterceptors(CrudRequestInterceptor)
  @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(
        project.id,
        LogProjectChangeCommand.Actions.licenseExceptionCreated,
        `A license exception has been created for project [${project.name}].`,
        userId,
      ),
    );

    return exception;
  }
Example #7
Source File: create-user.http.controller.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
@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 #8
Source File: account.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Post('login')
  @UsePipes(ValidationPipe)
  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);
      res.redirect('./../dashboard');
    } catch (e) {
      return res.render('account/login', { server: { message: e.message }, project_name: appData.Name });
    }
  }
Example #9
Source File: DesktopConfigController.ts    From rewind with MIT License 6 votes vote down vote up
@Post()
  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 #10
Source File: app.controller.ts    From nest_transact with MIT License 6 votes vote down vote up
@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 #11
Source File: app.controller.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
@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 #12
Source File: paddle.controller.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@Post('paddle-webhook')
  @UseInterceptors(MorganInterceptor('combined'))
  async paddleWebhook(
    @Body() body: PaddleEvent,
    @Res() response: Response
  ): Promise<void> {
    await this.paddleService.handlePaddleWebhook(body);
    response.sendStatus(200);
  }
Example #13
Source File: app.controller.ts    From nestjs-keycloak-admin with MIT License 6 votes vote down vote up
@Post('/')
  @DefineScope('create')
  async create(@Request() req: any): Promise<Resource> {
    let resource = new Resource({
      name: 'resource',
      displayName: 'My Resource'
    } as UMAResource)
      .setOwner(req.user._id)
      .setScopes([new Scope('organization:read'), new Scope('organization:write')])
      .setType('urn:resource-server:type:organization')
      .setUris(['/organization/123'])
      .setAttributes({
        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 #14
Source File: sites.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiCreateSiteBody()
  @ApiOperation({ summary: 'Creates a new site and its site application' })
  @OverrideLevelAccess()
  @Post()
  create(
    @Req() request: AuthRequest,
    @Body('siteApplication') siteApplication: CreateSiteApplicationDto,
    @Body('site') site: CreateSiteDto,
  ): Promise<SiteApplication> {
    return this.sitesService.create(siteApplication, site, request.user);
  }
Example #15
Source File: organizations.controller.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
@Post(':name/comments')
  @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
      .findByName({
        name
      })
      .toPromise()

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

    const result: Comment = await this.commentsService
      .create({
        ...comment,
        organization: organization.id
      })
      .toPromise()

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

    return result
  }
Example #16
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('login')
  @HttpCode(HttpStatus.OK)
  @ApiOkResponse({ type: LoginResDto })
  @ApiUnauthorizedResponse({ type: ApiException })
  @UseGuards(AuthenticationGuard)
  async login(
    @Body() _: LoginReqDto,
    @Req() req?: Request
  ): Promise<LoginResDto> {
    const accessToken = await this.authService.getAuthToken(req.user as User);
    return { accessToken };
  }
Example #17
Source File: announcement.controller.ts    From edu-server with MIT License 6 votes vote down vote up
@Post()
  @Roles(Role.ADMIN)
  @ApiOperation({ summary: 'add an Announcement' })
  @ApiCreatedResponse(responsedoc.addAnnouncement)
  async addAnnouncement(@Body() CreateAnnouncementDTO: CreateAnnouncementDTO) {
    return await this.announcementService.addAnnouncement(
      CreateAnnouncementDTO,
    );
  }
Example #18
Source File: app.controller.ts    From nestjs-file-streaming with MIT License 6 votes vote down vote up
@ApiOperation({
    summary: 'Upload a file.',
    requestBody: {
      content: {
        'multipart/form-data': {
          schema: {
            type: 'object',
            properties: { file: { type: 'string', format: 'binary' } },
          },
        },
      },
    },
  })
  @ApiConsumes('multipart/form-data')
  @ApiCreatedResponse({
    schema: {
      properties: {
        id: {
          type: 'string',
          example: '5e2b4cb75876c93e38b6e6aa',
        },
      },
    },
  })
  @Post()
  uploadFile(@Req() request: Request): Promise<{ id: string }> {
    return this.appService.upload(request)
  }
Example #19
Source File: test.controller.ts    From nestjs-form-data with MIT License 6 votes vote down vote up
@Post('single-file')
  @UsePipes(ValidationPipe)
  @FormDataRequest()
  @HttpCode(HttpStatus.OK)
  uploadSingleFile(@Body() singleFileDto: UploadSingleFileDto) {
    return {
      filename: singleFileDto.file.originalName,
      mimetype: singleFileDto.file.mimetype,
    };
  }
Example #20
Source File: api-gateway.controller.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
@Post()
  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))) {
        logger.warn(ip);
        return getResponse(body, errors.Forbidden.name);
      }
    } else {
      if (body.method === 'testBalance.get' && !(await verifyCaptcha(body.params['token']))) {
        logger.warn(ip);
        return getResponse(body, errors.Forbidden.name);
      }
    }
    const response = await this.service.requestMessage(body);
    return response;
  }
Example #21
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 #22
Source File: offer.controller.ts    From pandaid with MIT License 6 votes vote down vote up
@Post()
  @HttpCode(204)
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(Role.ADMIN, Role.SUPERVISOR, Role.VOLUNTEER)
  public create(@Body() createRequestRequest: OfferBase) {
    const id = this.offerService.getOffers().length
    this.offerService.addOffer({
      id: id,
      state: OfferStates.OPEN
      //TODO add fields
    })
  }