@nestjs/swagger#ApiOkResponse TypeScript Examples

The following examples show how to use @nestjs/swagger#ApiOkResponse. 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: user.controller.ts    From nestjs-api-example with MIT License 9 votes vote down vote up
@Get(':id')
  @ApiOperation({ summary: '유저 정보 조회 API' })
  @ApiOkResponse({
    description: 'Id가 일치하는 유저 정보를 조회한다.',
    type: UserResponseDto,
  })
  async findOne(
    @Param('id', new ParseIntPipe()) id: number,
    @Res() res: Response,
  ) {
    const responseDto = await this.userService.findById(id);

    return res.status(HttpStatus.OK).json(instanceToPlain(responseDto));
  }
Example #2
Source File: users.controller.ts    From nest-js-boilerplate with MIT License 8 votes vote down vote up
@ApiOkResponse({
    schema: {
      type: 'object',
      properties: {
        data: {
          $ref: getSchemaPath(User),
        },
      },
    },
    description: '200. Success. Returns a user',
  })
  @ApiNotFoundResponse({
    description: '404. NotFoundException. User was not found',
  })
  @ApiUnauthorizedResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
      },
    },
    description: '401. UnauthorizedException.',
  })
  @ApiParam({ name: 'id', type: String })
  @Get(':id')
  @Serialize(UserResponseDto)
  @Auth()
  async getById(
    @Param('id', ParseObjectIdPipe) id: Types.ObjectId,
  ): Promise<User> {
    const foundUser = await this.usersService.getVerifiedUserById(id);

    if (!foundUser) {
      throw new NotFoundException('The user does not exist');
    }

    return foundUser;
  }
Example #3
Source File: user.controller.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
@Put(':id')
  @ApiOperation({ summary: '유저 정보 수정 API' })
  @ApiOkResponse({
    description: 'Id가 일치하는 유저 정보를 수정한다.',
    type: User,
  })
  async update(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() requestDto: UserUpdateRequestDto,
    @Res() res: Response,
  ) {
    const updatedUser = await this.userService.updateUser(id, requestDto);

    return res.status(HttpStatus.OK).json(updatedUser);
  }
Example #4
Source File: users.controller.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@ApiOkResponse({
    description: '200. Success. Returns all users',
    schema: {
      type: 'object',
      properties: {
        data: {
          $ref: getSchemaPath(User),
        },
      },
    },
  })
  @ApiUnauthorizedResponse({
    schema: {
      type: 'object',
      example: {
        message: 'string',
      },
    },
    description: '401. UnauthorizedException.',
  })
  @Get()
  @Serialize(UsersResponseDto)
  @Auth()
  async getAllVerifiedUsers() {
    const foundUsers = await this.usersService.getVerifiedUsers();

    return foundUsers;
  }
Example #5
Source File: api-pagination.response.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
ApiPaginatedResponse = <TModel extends Type<any>>(
  options: IPaginatedDecoratorApiResponse,
) => {
  return applyDecorators(
    ApiExtraModels(PaginatedDto),
    ApiOkResponse({
      description: options.description || 'Successfully received model list',
      schema: {
        allOf: [
          { $ref: getSchemaPath(PaginatedDto) },
          {
            properties: {
              items: {
                type: 'array',
                items: { $ref: getSchemaPath(options.model) },
              },
              meta: {
                type: 'any',
                default: {
                  totalItems: 2,
                  itemCount: 2,
                  itemsPerPage: 2,
                  totalPages: 1,
                  currentPage: 1,
                },
              },
            },
          },
        ],
      },
    }),
  );
}
Example #6
Source File: google-cloud.controller.ts    From aqualink-app with MIT License 6 votes vote down vote up
@ApiBearerAuth()
  @ApiOkResponse({
    description: 'An array of all dangling files',
    schema: {
      type: 'array',
      items: {
        type: 'string',
        example:
          'https://storage.googleapis.com/storage/reef-image-a5b5f5c5d5da5d5e.jpg',
      },
    },
  })
  @ApiOperation({ summary: 'Returns all files stored that are not used' })
  @Get('dangling')
  findDanglingFiles(): Promise<string[]> {
    return this.googleCloudService.findDanglingFiles();
  }
Example #7
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 #8
Source File: announcement.controller.ts    From edu-server with MIT License 6 votes vote down vote up
@Get('/:announcementId')
  @ApiParam(announcementId)
  @ApiOperation({
    summary: 'Fetch a particular Announcement using ID',
  })
  @ApiOkResponse(responsedoc.getAnnouncement)
  async getAnnouncement(@Param('announcementId') announcementId: string) {
    return await this.announcementService.getAnnouncement(announcementId);
  }
Example #9
Source File: app.controller.ts    From nestjs-file-streaming with MIT License 6 votes vote down vote up
@ApiOperation({
    summary: 'Get a list of all uploaded files.',
  })
  @ApiOkResponse({
    schema: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          _id: { type: 'string', example: '5e2b447e4aadb800bccfb339' },
          length: { type: 'number', example: 730416 },
          chunkSize: { type: 'number', example: 261120 },
          uploadDate: { type: 'Date', example: '2020-01-24T19:24:46.366Z' },
          filename: { type: 'string', example: 'IMG_0359.jpeg' },
          md5: { type: 'string', example: 'ba230f0322784443c84ffbc5b6160c30' },
          contentType: { type: 'string', example: 'image/jpeg' },
        },
      },
    },
  })
  @Get()
  getAllFiles(): Promise<File[]> {
    return this.appService.getList()
  }
Example #10
Source File: admins.controller.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
// TODO @yashmurty : Investigate pagination for this later.
  @UsePipes(new ValidationPipe(VALIDATION_PIPE_OPTIONS))
  @ApiOperation({ summary: 'Get all admin users' })
  @ApiOkResponse({ type: [Admin] })
  @Get('/users')
  async getAdminUsers(@Request() req, @Query() query: PaginationParamsDto): Promise<Admin[]> {
    const requestAdminUser: RequestAdminUser = req.user
    return this.adminsService.findAllAdminUsers(requestAdminUser, query.limit, query.offset)
  }
Example #11
Source File: auth.controller.ts    From bank-server with MIT License 6 votes vote down vote up
@Post('login')
  @HttpCode(HttpStatus.OK)
  @ApiOkResponse({
    status: HttpStatus.OK,
    type: LoginPayloadDto,
    description: 'User info with access token',
  })
  async userLogin(
    @Body() userLoginDto: UserLoginDto,
  ): Promise<LoginPayloadDto> {
    const user = await this._authService.validateUser(userLoginDto);
    const token = await this._authService.createToken(user);

    return new LoginPayloadDto(user.toDto(), token);
  }
Example #12
Source File: app.controller.ts    From MyAPI with MIT License 6 votes vote down vote up
@ApiOperation({ summary: 'Check API status' })
  @ApiOkResponse({ description: 'The service is operating correctly' })
  @ApiInternalServerErrorResponse({ description: 'Internal Server Error' })
  @ApiBadRequestResponse({ description: 'Communication error with the server' })
  @ApiServiceUnavailableResponse({ description: 'The service is not available' })
  @HttpCode(HttpStatus.OK)
  @Get('api/help')
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  getHelp(): void {}
Example #13
Source File: tenant.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Post()
	@ApiOkResponse({ type: Tenant })
	public async create(@Body() tenant: any, @Request() req): Promise<any> { 
		if (await this.tenantService.findOne()) {
			throw new ForbiddenException('The installation process has already concluded')
		}

		tenant.uuid = uuid.v4();
		tenant.slug = slugify(tenant.name);
		tenant.createdAt = new Date();
		tenant.updatedAt = new Date();
		await this.tenantService.create(tenant);

		const permissionsList = permissions([], []).reduce((acc, permissionGroup) => {
			return {
				...acc,
				...permissionGroup.groups.reduce((groupAcc, group) => {
					return {
						...groupAcc,
						...group.permissions.reduce((permissionAcc, permission) => ({ ...permissionAcc, [permission.value]: true }), {})
					}
				}, {})
			}
		}, {}) as any;

		const createdRole = await this.roleService.create({
			name: 'Admin',
			uuid: uuid.v4(),
			createdAt: new Date(),
			updatedAt: new Date(),
			permissions: permissionsList,
		});

		const existingUser = await this.userService.findOne({ uuid: req.user?.uuid });
		await this.userService.assignRole(existingUser.uuid, createdRole.uuid);

		return this.tenantService.findOne();
	}
Example #14
Source File: app.controller.ts    From nestjs-starter with MIT License 6 votes vote down vote up
/**
   * Create User - User Registration
   * @param dto User Form
   */
  @ApiOperation({
    summary: 'Get my profile',
    description: 'You will get prompt with your user data, keep in mind that you need to provide the Bearer Token for Authentication',
  })
  @ApiOkResponse({ status: 200, description: 'Success response', type: User })
  @ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized' })
  @ApiBadGatewayResponse({ status: 502, description: 'Login user authentication' })
  @ApiBadRequestResponse({ status: 400, description: 'You will prompt with the validation issues' })
  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Get('auth/profile')
  async profile(@Request() req) {
    return { output: req.user };
  }
Example #15
Source File: user.controller.ts    From nestjs-api-example with MIT License 5 votes vote down vote up
@Get()
  @ApiOperation({ summary: '모든 유저 조회 API' })
  @ApiOkResponse({ description: '모든 유저를 조회한다.', type: User })
  async findAll(@Res() res: Response) {
    const users = await this.userService.findAll();

    return res.status(HttpStatus.OK).json(users);
  }
Example #16
Source File: app.controller.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
@ApiOkResponse({ description: 'Returns you Hello world!' })
  @Get()
  sayHello(): string {
    return this.appService.getHello();
  }