@nestjs/common#NotFoundException TypeScript Examples

The following examples show how to use @nestjs/common#NotFoundException. 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: 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 #2
Source File: site.utils.ts    From aqualink-app with MIT License 7 votes vote down vote up
getSite = async (
  siteId: number,
  siteRepository: Repository<Site>,
  relations?: string[],
) => {
  const site = await siteRepository.findOne(siteId, { relations });

  if (!site) {
    throw new NotFoundException(`Site with id ${siteId} does not exist`);
  }

  return site;
}
Example #3
Source File: user.repository.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
// constructor(private readonly logger: MyLogger) {
  //   super();
  // }

  async findWithCard(id: number): Promise<User> {
    const user = await this.findOne(id, { relations: ['card'] });
    if (!user) throw new NotFoundException();
    return user;
  }
Example #4
Source File: board.service.ts    From Phantom with MIT License 6 votes vote down vote up
/**
   * @author Nada AbdElmaboud <[email protected]>
   * @description add board to user
   * @param {string} userId - the id of the user
   * @param {string} boardId - the id of the board
   * @returns  {Promise<boolean>}
   */
  async addBoardtoUser(userId, boardId) {
    if (
      (await this.ValidationService.checkMongooseID([userId, boardId])) == 0
    ) {
      throw new BadRequestException('not valid id');
    }
    boardId = mongoose.Types.ObjectId(boardId);
    userId = mongoose.Types.ObjectId(userId);
    let board = await this.boardModel.findById(boardId, {
      name: 1,
      createdAt: 1,
    });
    let user = await this.userModel.findById(userId, {
      boards: 1,
      sortType: 1,
    });
    if (!board) throw new NotFoundException();
    if (!user) throw new NotFoundException();
    let id = mongoose.Types.ObjectId(boardId);
    user.boards.push({
      boardId: id,
      name: board.name,
      createdAt: board.createdAt,
      isJoined: false,
      createdOrjoined: 'created',
    });
    await user.save().catch(err => {
      console.log(err);
    });
    return true;
  }
Example #5
Source File: prefectures.service.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
async getOnePrefectureById(
    requestAdminUser: RequestAdminUser,
    prefectureId: number
  ): Promise<Prefecture> {
    // Fetch resource and perform ACL check.
    const prefecture = await this.prefecturesRepository.findOneById(prefectureId)
    if (!prefecture) {
      throw new NotFoundException('Could not find prefecture with this id')
    }
    if (!canUserAccessResource(requestAdminUser.userAccessKey, prefecture)) {
      throw new UnauthorizedException('User does not have access on this resource')
    }

    return prefecture
  }
Example #6
Source File: user-points.service.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
async findOrThrow(userId: number): Promise<UserPoints> {
    const record = await this.prisma.userPoints.findUnique({
      where: {
        user_id: userId,
      },
    });

    if (!record) {
      throw new NotFoundException();
    }

    return record;
  }
Example #7
Source File: user.service.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
findById(id: string, withPosts = false): Observable<User> {
    const userQuery = this.userModel.findOne({ _id: id });
    if (withPosts) {
      userQuery.populate('posts');
    }
    return from(userQuery.exec()).pipe(
      mergeMap((p) => (p ? of(p) : EMPTY)),
      throwIfEmpty(() => new NotFoundException(`user:${id} was not found`)),
    );
  }
Example #8
Source File: access.service.ts    From nest-casl with MIT License 6 votes vote down vote up
public assertAbility(user: AuthorizableUser, action: string, subject: Subject): void {
    if (!this.hasAbility(user, action, subject)) {
      const userAbilities = this.abilityFactory.createForUser(user, Ability);
      const relatedRules = userAbilities.rulesFor(action, typeof subject === 'object' ? subject.constructor : subject);
      if (relatedRules.some((rule) => rule.conditions)) {
        throw new NotFoundException();
      }
      throw new UnauthorizedException();
    }
  }
Example #9
Source File: user.service.ts    From edu-server with MIT License 6 votes vote down vote up
// Delete Enrolled Course of User
  async deleteEnrolledCourse(courseId: Schema.Types.ObjectId): Promise<any> {
    let deletedFrom;
    try {
      const user = await this.userModel.findOne({
        email: this.request['user']['email'],
      });
      if (user) {
        const userId = user.id;
        deletedFrom = await this.enrolledModel.findOneAndRemove({
          studentId: userId,
          courseId: courseId,
        });
        if (deletedFrom) {
          return deletedFrom;
        } else {
          throw new NotFoundException('not found');
        }
      } else {
        throw new NotFoundException('User not found');
      }
    } catch (e) {
      throw new InternalServerErrorException(e);
    }
  }
Example #10
Source File: tracks.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Put(':trackId/reactivate')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiResponse({ status: HttpStatus.OK })
  @ApiBearerAuth()
  async enableTrack(@Param('trackId') trackId: string): Promise<void> {
    const track = await this.trackService.findByIdAsync(trackId);

    if (!track) throw new NotFoundException(`Track with ${trackId} not found`);

    await this.trackService.activateTrack(trackId);
  }
Example #11
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 #12
Source File: user.service.ts    From uniauth-backend with MIT License 6 votes vote down vote up
async reset(resetPasswordDto: ResetPasswordDto, isValidToken): Promise<User> {
    let { password_1 } = resetPasswordDto;
    password_1 = await bcrypt.hashSync(password_1, 10);
    const user = await this.userModel.findOneAndUpdate(isValidToken.id, { password: password_1 });
    if (user === null) {
      throw new NotFoundException('user not found');
    } else {
      return user;
    }
  }
Example #13
Source File: auth.service.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
public async validateUser(
    email: string,
    password: string,
  ): Promise<null | UserInterface> {
    const user = await this.usersRepository.getVerifiedUserByEmail(email) as UserDocument;

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

    const passwordCompared = await bcrypt.compare(password, user.password);

    if (passwordCompared) {
      return {
        _id: user._id,
        email: user.email,
        role: user.role,
      };
    }

    return null;
  }
Example #14
Source File: application.controller.ts    From uniauth-backend with MIT License 6 votes vote down vote up
//   @Put(':id')
  //   @UsePipes(ValidationPipe)
  //   update(@Param('id') id: string, @Body() updateApplicationDto: UpdateApplicationDto) {
  //     return this.applicationService.update(+id, updateApplicationDto);
  //   }

  @Delete(':id')
  @UsePipes(ValidationPipe)
  async remove(@Request() req, @Param('id') id: string) {
    const user: AuthorizedUser = req.user;
    const application = await this.applicationService.findOneById(id);
    if (application === null) {
      throw new NotFoundException();
    }
    if (String(application.admin) !== user.id) {
      throw new UnauthorizedException();
    }
    await application.remove();
    return 'removed';
  }
Example #15
Source File: entityPage.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
private async validateEntityInApp(
    entityId: string,
    appId: string
  ): Promise<void> {
    if (!this.entityService.isEntityInSameApp(entityId, appId)) {
      throw new NotFoundException(
        `Can't find persistent entity with ID ${entityId} in ${appId}`
      );
    }
  }
Example #16
Source File: user.service.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
/**
   * 유저 Id에 해당하는 유저 정보를 반환한다.
   *
   * @param {number} id - 유저 Id
   * @returns {Promise<User>}
   * @private
   */
  private async findUserById(id: number): Promise<User> {
    const user = await this.userRepository.findOne({
      where: { id: id },
    });

    if (isEmpty(user) === true) {
      throw new NotFoundException(Message.NOT_FOUND_USER);
    }

    return user;
  }