@nestjs/swagger#ApiBody TypeScript Examples

The following examples show how to use @nestjs/swagger#ApiBody. 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: api-properties.ts    From aqualink-app with MIT License 9 votes vote down vote up
ApiFileUpload = () => {
  const maxFileSizeMB = process.env.STORAGE_MAX_FILE_SIZE_MB
    ? parseInt(process.env.STORAGE_MAX_FILE_SIZE_MB, 10)
    : 1;

  return applyDecorators(
    ApiConsumes('multipart/form-data'),
    ApiBody({
      schema: {
        type: 'object',
        properties: {
          file: {
            description: `The image to upload (image/jpeg, image/png, image/tiff). Max size: ${maxFileSizeMB}MB`,
            type: 'string',
            format: 'binary',
          },
        },
      },
    }),
  );
}
Example #2
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 #3
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 #4
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 #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('/home')
  public login(): void {}
Example #6
Source File: api-properties.ts    From aqualink-app with MIT License 6 votes vote down vote up
ApiUpdateSiteApplicationBody = () => {
  return applyDecorators(
    ApiBody({
      schema: {
        type: 'object',
        properties: {
          site: {
            $ref: getSchemaPath(UpdateSiteWithApplicationDto),
          },
          siteApplication: {
            $ref: getSchemaPath(UpdateSiteApplicationDto),
          },
        },
      },
    }),
  );
}
Example #7
Source File: profile.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('upload_profile_photo')
  @UseInterceptors(FileInterceptor('file'))
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: 'Upload avatar photo',
    type: AvatarUploadDto
  })
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiResponse({ type: UserDto, status: HttpStatus.OK })
  @HttpCode(HttpStatus.OK)
  async uploadFile(
    @UploadedFile() file: BufferedFile,
    @Req() req: Request
  ): Promise<UserDto> {
    if (!file) throw new BadRequestException('File image cannot be empty');

    if (file.mimetype.split('/')[0] !== 'image')
      throw new UnsupportedMediaTypeException('File is not an image');

    if (file.size / 1024 > 200)
      throw new BadRequestException('File cannot be larger than 200KB');

    const id = req.user['userId'];
    await this.profileService.uploadAvatar(file, id);
    const user = await this.userService.findByIdAsync(id);

    return plainToClass(UserDto, user, {
      enableImplicitConversion: true,
      excludeExtraneousValues: true
    });
  }
Example #8
Source File: swagger-schema.decorator.ts    From bank-server with MIT License 6 votes vote down vote up
ApiFile = (
  fileName = 'file',
  options: Partial<{ required: boolean; isArray: boolean }> = {},
): MethodDecorator => (
  target: any,
  propertyKey: string,
  descriptor: PropertyDescriptor,
) => {
  const { required = false, isArray = false } = options;
  let fileSchema: SchemaObject = {
    type: 'string',
    format: 'binary',
  };

  if (isArray) {
    fileSchema = {
      type: 'array',
      items: fileSchema,
    };
  }
  ApiBody({
    required,
    type: 'multipart/form-data',
    schema: {
      type: 'object',
      properties: {
        [fileName]: fileSchema,
      },
    },
  })(target, propertyKey, descriptor);
}
Example #9
Source File: auth.controller.ts    From MyAPI with MIT License 6 votes vote down vote up
@ApiOperation({ summary: 'Authenticate user' })
  @ApiBody({ description: 'User credentials', type: AuthLogin })
  @ApiOkResponse({ description: 'Authentication token', type: AuthToken })
  @ApiUnauthorizedResponse({ description: 'The username or password entered are not valid' })
  @UseGuards(AuthGuard('local'))
  @Post()
  @HttpCode(HttpStatus.OK)
  authenticate(
    @Request() request: { user: User }
  ): Promise<AuthToken> {
    return this.authService.getAccessToken(request.user)
  }
Example #10
Source File: MediaController.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Post()
  @HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
  @HttpCode(HttpStatus.OK)
  @UseInterceptors(FileInterceptor('file'))
  @ApiBearerAuth()
  @ApiConsumes('multipart/form-data')
  @ApiBody({type: HttpRestApiModelCreateMediaBody})
  @ApiQuery({name: 'name', type: 'string', required: false})
  @ApiQuery({name: 'type', enum: MediaType})
  @ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
  public async createMedia(
    @Req() request: HttpRequestWithUser,
    @UploadedFile() file: MulterFile,
    @Query() query: HttpRestApiModelCreateMediaQuery
    
  ): Promise<CoreApiResponse<MediaUseCaseDto>> {
  
    const adapter: CreateMediaAdapter = await CreateMediaAdapter.new({
      executorId: request.user.id,
      name      : query.name || parse(file.originalname).name,
      type      : query.type,
      file      : file.buffer,
    });
    
    const createdMedia: MediaUseCaseDto = await this.createMediaUseCase.execute(adapter);
    this.setFileStorageBasePath([createdMedia]);
    
    return CoreApiResponse.success(createdMedia);
  }
Example #11
Source File: app.controller.ts    From nestjs-starter with MIT License 6 votes vote down vote up
/**
   * Login user authentication
   * @param dto User Form
   * @example /auth/login
   */
  @ApiOperation({ summary: 'Login user authentication', description: 'In this way you will get the Token for Bearer authentication' })
  @ApiCreatedResponse({ status: 201, description: 'Login success, you will receive the "accessToken" there' })
  @ApiBadRequestResponse({ status: 400, description: 'Invalid credentials' })
  @ApiForbiddenResponse({ status: 403, description: 'Account is disabled, contact with administrator' })
  @ApiNotFoundResponse({ status: 404, description: 'Your account does not exist' })
  @ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
  @ApiBadGatewayResponse({ status: 502, description: 'Login user authentication' })
  @ApiBody({ type: LoginDto })
  @UseGuards(LocalAuthGuard)
  @Post('auth/login')
  async login(@Request() req, @Body() loginDto: LoginDto) {
    return await this.authService.login(req.user);
  }
Example #12
Source File: cms.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Post('place-order')
    @UseGuards(ThrottlerGuard)
    @Throttle(3, 20)
    @ApiOperation({
        description: 'Creates new Order in the shop',
    })
    @ApiBody({ type: CreateOrderDto })
    @ApiResponse({
        status: 200,
    })
    async placeOrder(@Body() input: CreateOrderDto): Promise<TOrder | undefined> {
        if (!input || !input.customerEmail
            || !input.customerPhone) throw new HttpException('Order form is incomplete', HttpStatus.NOT_ACCEPTABLE);

        const order = await this.storeService.placeOrder(input);
        serverFireAction('create_order', order);
        return order;
    }
Example #13
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 #14
Source File: theme.controller.ts    From Cromwell with MIT License 6 votes vote down vote up
@Post('palette')
    @UseGuards(JwtAuthGuard)
    @Roles('administrator')
    @ApiOperation({
        description: `Update palette of an active theme`,
        parameters: [
            { name: 'themeName', in: 'query', required: true },
        ],
    })
    @ApiResponse({
        status: 201,
        type: Boolean
    })
    @ApiBody({ type: ThemePaletteDto })
    @ApiForbiddenResponse({ description: 'Forbidden.' })
    async saveThemePalette(@Body() input: ThemePaletteDto, @Query('themeName') themeName: string): Promise<boolean> {
        logger.log('ThemeController::saveThemePalette');
        if (input && typeof input === 'object') {
            return await this.themeService.saveThemePalette(input, themeName);
        }
        return false;
    }
Example #15
Source File: registration.controller.ts    From pandaid with MIT License 5 votes vote down vote up
@Post('organization')
  @ApiBody({ type: OrganizationDto })
  @ApiResponse({ status: 200, type: OrganizationResponse })
  organization(@Body() registerRequest: OrganizationDto): OrganizationResponse {
    return this.registrationService.registerOrganization(registerRequest)
  }
Example #16
Source File: AuthController.ts    From typescript-clean-architecture with MIT License 5 votes vote down vote up
@Post('login')
  @HttpCode(HttpStatus.OK)
  @UseGuards(HttpLocalAuthGuard)
  @ApiBody({type: HttpRestApiModelLogInBody})
  @ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseLoggedInUser})
  public async login(@Req() request: HttpRequestWithUser): Promise<CoreApiResponse<HttpLoggedInUser>> {
    return CoreApiResponse.success(this.authService.login(request.user));
  }
Example #17
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
@ApiBody({ type: SignInDto })
  @ApiOkResponse({
    schema: {
      type: 'object',
      properties: {
        data: {
          $ref: getSchemaPath(JwtTokensDto),
        },
      },
    },
    description: 'Returns jwt tokens',
  })
  @ApiBadRequestResponse({
    schema: {
      type: 'object',
      example: {
        message: [
          {
            target: {
              email: 'string',
              password: 'string',
            },
            value: 'string',
            property: 'string',
            children: [],
            constraints: {},
          },
        ],
        error: 'Bad Request',
      },
    },
    description: '400. ValidationException',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiBearerAuth()
  @HttpCode(HttpStatus.OK)
  @UseGuards(LocalAuthGuard)
  @Post('sign-in')
  async signIn(@Request() req: ExpressRequest): Promise<JwtTokensDto> {
    const user = req.user as User;

    return this.authService.login(user);
  }
Example #18
Source File: base.controller.ts    From codeclannigeria-backend with MIT License 5 votes vote down vote up
export function BaseCrudController<
  TEntity extends BaseEntity,
  TEntityDto,
  TCreateDto,
  TUpdateDto = Partial<TCreateDto>,
  TPagedListDto = any
>(
  options: BaseControllerWithSwaggerOpts<
    TEntity,
    TEntityDto,
    TCreateDto,
    TUpdateDto,
    TPagedListDto
  >
): Type<
  IBaseController<
    TEntityDto,
    TCreateDto,
    TUpdateDto,
    FindDto,
    IPagedListDto<TEntityDto>
  >
> {
  const {
    entity: Entity,
    entityDto: EntityDto,
    createDto: CreateDto,
    updateDto: UpdateDto,
    pagedListDto: PagedListDto
  } = options;
  const auth = getAuthObj(options.auth);
  @ApiTags(pluralize(Entity.name))
  @Controller(pluralize(Entity.name.toLowerCase()))
  class BaseController {
    constructor(
      @Inject(BaseService)
      protected service: BaseService<TEntity>
    ) {}

    @Post()
    @ApiResponse({ type: EntityDto, status: HttpStatus.CREATED })
    @ApiBody({ type: CreateDto })
    @ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
    @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
    @Authenticate(auth.create.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.create.enableAuth, Roles(...auth.create.authRoles))
    @Authenticate(auth.create.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'Create' })
    async create(@Body() input: TCreateDto) {
      const entity = this.service.createEntity(input);
      await this.service.insertAsync(entity);
      return plainToClass(EntityDto, entity, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
    }

    @Get()
    @ApiResponse({ type: PagedListDto, status: HttpStatus.OK })
    @ApiResponse({ type: ApiException, status: HttpStatus.UNAUTHORIZED })
    @Authenticate(auth.find.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.find.enableAuth, Roles(...auth.find.authRoles))
    @Authenticate(auth.find.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'FindAll' })
    async findAll(@Query() query: FindDto) {
      const { skip, limit, search, opts } = query;
      const conditions = JSON.parse(search || '{}');
      const options = JSON.parse(opts || '{}');

      if (options?.sort) {
        const sort = { ...options.sort };
        Object.keys(sort).map((key) => {
          if (sort[key] === 'ascend') sort[key] = 1;
          else if (sort[key] === 'descend') sort[key] = -1;
          return sort;
        });
        options.sort = sort;
      }
      const entities = await this.service
        .findAll(conditions, options)
        .limit(limit)
        .skip(skip);

      const totalCount = await this.service.countAsync();
      const items = plainToClass(EntityDto, entities, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
      return { totalCount, items };
    }

    @Get(':id')
    @ApiResponse({ type: EntityDto, status: HttpStatus.OK })
    @ApiResponse({ status: HttpStatus.NOT_FOUND, type: ApiException })
    @Authenticate(auth.findById.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.findById.enableAuth, Roles(...auth.findById.authRoles))
    @Authenticate(auth.findById.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'FindById' })
    async findById(@Param('id') id: string) {
      const entity = await this.service.findByIdAsync(id);
      if (!entity)
        throw new NotFoundException(`Entity with id ${id} does not exist`);
      return plainToClass(EntityDto, entity, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
    }

    @Put(':id')
    @ApiBody({ type: UpdateDto })
    @ApiResponse({ status: HttpStatus.OK, type: EntityDto })
    @ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
    @ApiResponse({ status: HttpStatus.NOT_FOUND, type: ApiException })
    @Authenticate(auth.update.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.update.enableAuth, Roles(...auth.update.authRoles))
    @Authenticate(auth.update.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'Update' })
    async update(@Param('id') id: string, @Body() input: TUpdateDto) {
      const existingEntity = await this.service.findByIdAsync(id);
      if (!existingEntity)
        throw new NotFoundException(`Entity with Id ${id} does not exist`);
      const value = plainToClass(Entity, existingEntity, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
      const toBeUpdatedEntity = { ...value, ...input };
      const result = await this.service.updateAsync(id, toBeUpdatedEntity);
      return plainToClass(EntityDto, result, {
        enableImplicitConversion: true,
        excludeExtraneousValues: true
      });
    }

    @Delete(':id')
    @ApiResponse({ status: HttpStatus.OK })
    @Authenticate(auth.delete.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.delete.enableAuth, Roles(...auth.delete.authRoles))
    @Authenticate(auth.delete.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'Delete' })
    async delete(
      @Param('id') id: string,
      @Query('isHardDelete') isHardDelete: boolean
    ) {
      isHardDelete
        ? await this.service.hardDeleteById(id)
        : await this.service.softDeleteByIdAsync(id);
    }

    @Delete()
    @ApiResponse({ status: HttpStatus.OK })
    @Authenticate(auth.delete.enableAuth, UseGuards(JwtAuthGuard, RolesGuard))
    @Authenticate(auth.delete.enableAuth, Roles(...auth.delete.authRoles))
    @Authenticate(auth.delete.enableAuth, ApiBearerAuth())
    @ApiSwaggerOperation({ title: 'Delete many' })
    async deleteMany(
      @Body() input: DeleteManyType,
      @Query('isHardDelete') isHardDelete: boolean
    ) {
      isHardDelete
        ? await this.service.hardDeleteMany({ _id: { $in: [...input.ids] } })
        : await this.service.softDeleteMany({ _id: { $in: [...input.ids] } });
    }
  }
  return BaseController;
}
Example #19
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
@ApiBody({ type: SignInDto })
  @ApiOkResponse({
    schema: {
      type: 'object',
      properties: {
        data: {
          $ref: getSchemaPath(JwtTokensDto),
        },
      },
    },
    description: 'Returns jwt tokens',
  })
  @ApiBadRequestResponse({
    schema: {
      type: 'object',
      example: {
        message: [
          {
            target: {
              email: 'string',
              password: 'string',
            },
            value: 'string',
            property: 'string',
            children: [],
            constraints: {},
          },
        ],
        error: 'Bad Request',
      },
    },
    description: '400. ValidationException',
  })
  @ApiInternalServerErrorResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
        details: {},
      },
    },
    description: '500. InternalServerError',
  })
  @ApiBearerAuth()
  @HttpCode(HttpStatus.OK)
  @UseGuards(LocalAuthGuard)
  @Post('sign-in')
  async signIn(@Request() req: ExpressRequest): Promise<JwtTokensDto> {
    const user = req.user as UserEntity;

    return this.authService.login(user);
  }
Example #20
Source File: auth.controller.ts    From pandaid with MIT License 5 votes vote down vote up
@UseGuards(LocalAuthGuard)
  @Post('login')
  @ApiBody({ type: LoginDto })
  @ApiResponse({ status: 200, type: LoginResponse })
  login(@UserSession() user: User): LoginResponse {
    return this.authService.login(user)
  }