How to use the @nestjs/swagger.ApiBadRequestResponse function in @nestjs/swagger

To help you get started, we’ve selected a few @nestjs/swagger 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 nartc / nest-mean / server / src / todo / todo.controller.ts View on Github external
}
        }

        try {
            const todos = await this._todoService.findAll(filter);
            return this._todoService.mapArray(map(todos, todo => todo.toJSON()), Todo, TodoVm);
        } catch (e) {
            throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Put()
    // @Roles(UserRole.Admin, UserRole.User)
    // @UseGuards(AuthGuard('jwt'), RolesGuard)
    @ApiOkResponse({ type: TodoVm })
    @ApiBadRequestResponse({ type: ApiException })
    @ApiOperation(GetOperationId(Todo.modelName, 'Update'))
    async update(@Body() vm: TodoVm): Promise {
        const { id, content, level, isCompleted } = vm;

        if (!vm || !id) {
            throw new HttpException('Missing parameters', HttpStatus.BAD_REQUEST);
        }

        const exist = await this._todoService.findById(id);

        if (!exist) {
            throw new HttpException(`${id} Not found`, HttpStatus.NOT_FOUND);
        }

        if (exist.isCompleted) {
            throw new HttpException('Already completed', HttpStatus.BAD_REQUEST);
github nartc / nest-mean / server / src / todo / todo.controller.ts View on Github external
exist.isCompleted = isCompleted;
        exist.level = level;

        try {
            const updated = await this._todoService.update(id, exist);
            return this._todoService.map(updated.toJSON(), Todo, TodoVm);
        } catch (e) {
            throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Delete(':id')
    // @Roles(UserRole.Admin)
    // @UseGuards(AuthGuard('jwt'), RolesGuard)
    @ApiOkResponse({ type: TodoVm })
    @ApiBadRequestResponse({ type: ApiException })
    @ApiOperation(GetOperationId(Todo.modelName, 'Delete'))
    async delete(@Param('id') id: string): Promise {
        try {
            const deleted = await this._todoService.delete(id);
            return this._todoService.map(deleted.toJSON(), Todo, TodoVm);
        } catch (e) {
            throw new InternalServerErrorException(e);
        }
    }
}

export function EnumToArray(enumVariable: any): string[] {
    return Object.keys(enumVariable).map(k => enumVariable[k]);
}
github nartc / nest-mean / server / src / user / user.controller.ts View on Github external
} catch (e) {
            throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        if (exist) {
            throw new HttpException(`${username} exists`, HttpStatus.BAD_REQUEST);
        }

        const newUser = await this._userService.register(vm);
        console.log(newUser);
        return this._userService.map(newUser, User, UserVm);
    }

    @Post('login')
    @ApiCreatedResponse({ type: LoginResponseVm })
    @ApiBadRequestResponse({ type: ApiException })
    @ApiOperation(GetOperationId(User.modelName, 'Login'))
    async login(@Body() vm: LoginVm): Promise {
        const fields = Object.keys(vm);
        fields.forEach(field => {
            if (!vm[field]) {
                throw new HttpException(`${field} is required`, HttpStatus.BAD_REQUEST);
            }
        });

        return this._userService.login(vm);
    }
}
github nartc / nest-mean / server / src / user / user.controller.ts View on Github external
import { GetOperationId } from '../shared/utilities/get-operation-id.helper';
import { User } from './models/user.model';
import { LoginResponseVm } from './models/view-models/login-response-vm.model';
import { LoginVm } from './models/view-models/login-vm.model';
import { RegisterVm } from './models/view-models/register-vm.model';
import { UserVm } from './models/view-models/user-vm.model';
import { UserService } from './user.service';

@Controller('user')
@ApiUseTags(User.modelName)
export class UserController {
    constructor(private readonly _userService: UserService) {}

    @Post('register')
    @ApiCreatedResponse({ type: UserVm })
    @ApiBadRequestResponse({ type: ApiException })
    @ApiOperation(GetOperationId(User.modelName, 'Register'))
    async register(@Body() vm: RegisterVm): Promise {
        const { username, password } = vm;

        if (!username) {
            throw new HttpException('Username is required', HttpStatus.BAD_REQUEST);
        }

        if (!password) {
            throw new HttpException('Password is required', HttpStatus.BAD_REQUEST);
        }

        let exist;
        try {
            exist = await this._userService.findOne({ username });
        } catch (e) {
github jiayisheji / jianshu / libs / database / src / lib / crud.controller.ts View on Github external
@Get()
  public async findAll(@Query() filter: PaginationParams>): Promise>> {
    return this.crudService.paginator(filter);
  }

  @ApiOperation({ title: 'Find by id' })
  @ApiOkResponse({ description: 'Found one record' })
  @ApiNotFoundResponse({ description: 'Record not found' })
  @Get(':id')
  public async findById(@Param('id') id: string): Promise> {
    return this.crudService.findOne(id);
  }

  @ApiOperation({ title: 'Create new record' })
  @ApiCreatedResponse({ description: 'The record has been successfully created.' })
  @ApiBadRequestResponse({ description: 'Invalid input, The response body may contain clues as to what went wrong' })
  @HttpCode(HttpStatus.CREATED)
  @Post()
  public async create(@Body() entity: Partial): Promise> {
    return this.crudService.create(entity);
  }

  @ApiOperation({ title: 'Update an existing record' })
  @ApiCreatedResponse({ description: 'The record has been successfully edited.' })
  @ApiNotFoundResponse({ description: 'Record not found' })
  @ApiBadRequestResponse({ description: 'Invalid input, The response body may contain clues as to what went wrong' })
  @HttpCode(HttpStatus.CREATED)
  @Put(':id')
  public async update(@Param('id') id: string, @Body() entity: Partial>): Promise> {
    return this.crudService.update(id, entity);
  }
github jiayisheji / jianshu / libs / database / src / lib / crud.controller.ts View on Github external
return this.crudService.findOne(id);
  }

  @ApiOperation({ title: 'Create new record' })
  @ApiCreatedResponse({ description: 'The record has been successfully created.' })
  @ApiBadRequestResponse({ description: 'Invalid input, The response body may contain clues as to what went wrong' })
  @HttpCode(HttpStatus.CREATED)
  @Post()
  public async create(@Body() entity: Partial): Promise> {
    return this.crudService.create(entity);
  }

  @ApiOperation({ title: 'Update an existing record' })
  @ApiCreatedResponse({ description: 'The record has been successfully edited.' })
  @ApiNotFoundResponse({ description: 'Record not found' })
  @ApiBadRequestResponse({ description: 'Invalid input, The response body may contain clues as to what went wrong' })
  @HttpCode(HttpStatus.CREATED)
  @Put(':id')
  public async update(@Param('id') id: string, @Body() entity: Partial>): Promise> {
    return this.crudService.update(id, entity);
  }

  @ApiOperation({ title: 'Delete record' })
  @ApiResponse({ status: HttpStatus.NO_CONTENT, description: 'The record has been successfully deleted' })
  @ApiNotFoundResponse({ description: 'Record not found' })
  @HttpCode(HttpStatus.NO_CONTENT)
  @Delete(':id')
  public async delete(@Param('id') id: string): Promise>> {
    return this.crudService.delete(id);
  }
}
github jiayisheji / jianshu / apps / client / src / app / auth / auth.controller.ts View on Github external
ApiOperation,
  ApiUnauthorizedResponse,
  ApiForbiddenResponse,
  ApiBadRequestResponse,
  ApiOkResponse,
  ApiBearerAuth,
  ApiCreatedResponse
} from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { CurrentUser } from './decorators/current-user.decorator';
import { LoginDto, RegisterDto, LoginDao } from '@jianshu/api-interfaces';
import { User } from '@jianshu/database';

@ApiUseTags('Auth')
@ApiBadRequestResponse({ description: 'Invalid input, The response body may contain clues as to what went wrong' })
@ApiUnauthorizedResponse({ description: 'Unauthorized' })
@ApiForbiddenResponse({ description: 'Forbidden' })
@Controller()
export class AuthController {
  private readonly logger = new Logger(AuthController.name, true);
  constructor(private readonly authService: AuthService) { }

  /**
   * 注册账号
   * @param {RegisterDto} registerDto
   * @returns
   * @memberof AuthController
   */
  @Post('/register')
  @ApiOperation({ title: '注册' })
  @ApiCreatedResponse({ description: '注册成功', type: LoginDao })
github nartc / nest-mean / server / src / todo / todo.controller.ts View on Github external
@ApiBadRequestResponse({ type: ApiException })
    @ApiOperation(GetOperationId(Todo.modelName, 'Create'))
    async create(@Body() params: TodoParams): Promise {
        try {
            const newTodo = await this._todoService.createTodo(params);
            return this._todoService.map(newTodo, Todo, TodoVm);
        } catch (e) {
            throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Get()
    @Roles(UserRole.Admin, UserRole.User)
    @UseGuards(AuthGuard('jwt'), RolesGuard)
    @ApiOkResponse({ type: TodoVm, isArray: true })
    @ApiBadRequestResponse({ type: ApiException })
    @ApiOperation(GetOperationId(Todo.modelName, 'GetAll'))
    @ApiImplicitQuery({ name: 'level', enum: EnumToArray(TodoLevel), required: false, isArray: true })
    @ApiImplicitQuery({ name: 'isCompleted', required: false })
    async get(
        @Query('level') level?: TodoLevel,
        @Query('isCompleted', new ToBooleanPipe())
            isCompleted?: boolean,
    ): Promise {
        let filter = {};

        if (level) {
            filter['level'] = { $in: isArray(level) ? [...level] : [level] };
        }

        if (isCompleted !== null) {
            if (filter['level']) {
github lonelyhentai / minellius / server / src / data / controllers / period-event.controller.ts View on Github external
@ApiBadRequestResponse({description: 'Invalid query.' })
  @HttpCode(HttpStatus.CREATED)
  @Post('query')
  async find(
    @Request() req,
    @Body(new ValidationPipe()) createPeriodEventQuery: CreatePeriodEventQueryDto,
  ): Promise {
    Logger.log(`${req.user?req.user.id:''} try to`,PeriodEventService.name+':query');
    const entities = await this.periodEventService.find(createPeriodEventQuery);
    return plainToClass(OutPeriodEventDto,entities);
  }

  @ApiBearerAuth()
  @ApiCreatedResponse({ description: 'Successfully created query and count values.', type: Number })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, description: 'Forbidden.' })
  @ApiBadRequestResponse({description: 'Invalid query.' })
  @HttpCode(HttpStatus.CREATED)
  @Post('count')
  async count(
    @Request() req,
    @Body(new ValidationPipe()) createPeriodEventQuery: CreatePeriodEventQueryDto,
  ): Promise {
    Logger.log(`${req.user?req.user.id:''} try to access`,PeriodEventService.name+':count');
    return await this.periodEventService.count(createPeriodEventQuery);
  }
}
github lonelyhentai / minellius / server / src / data / controllers / period-event.controller.ts View on Github external
import { plainToClass } from 'class-transformer';

@ApiUseTags('period-events')
@Controller('api/period-events')
@UseGuards(AccessGuard)
export class PeriodEventController {

  constructor(
    private readonly periodEventService: PeriodEventService,
  ) {
  }

  @ApiBearerAuth()
  @ApiCreatedResponse({ description: 'Successfully created query and query values.', type: OutPeriodEventDto, isArray: true })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, description: 'Forbidden.' })
  @ApiBadRequestResponse({description: 'Invalid query.' })
  @HttpCode(HttpStatus.CREATED)
  @Post('query')
  async find(
    @Request() req,
    @Body(new ValidationPipe()) createPeriodEventQuery: CreatePeriodEventQueryDto,
  ): Promise {
    Logger.log(`${req.user?req.user.id:''} try to`,PeriodEventService.name+':query');
    const entities = await this.periodEventService.find(createPeriodEventQuery);
    return plainToClass(OutPeriodEventDto,entities);
  }

  @ApiBearerAuth()
  @ApiCreatedResponse({ description: 'Successfully created query and count values.', type: Number })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, description: 'Forbidden.' })
  @ApiBadRequestResponse({description: 'Invalid query.' })
  @HttpCode(HttpStatus.CREATED)