rxjs/operators#throwIfEmpty TypeScript Examples

The following examples show how to use rxjs/operators#throwIfEmpty. 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: auth.service.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
validateUser(username: string, pass: string): Observable<UserPrincipal> {
    return this.userService.findByUsername(username).pipe(
      //if user is not found, convert it into an EMPTY.
      mergeMap((p) => (p ? of(p) : EMPTY)),

      // Using a general message in the authentication progress is more reasonable.
      // Concise info could be considered for security.
      // Detailed info will be helpful for crackers.
      // throwIfEmpty(() => new NotFoundException(`username:${username} was not found`)),
      throwIfEmpty(() => new UnauthorizedException(`username or password is not matched`)),

      mergeMap((user) => {
        const { _id, password, username, email, roles } = user;
        return user.comparePassword(pass).pipe(map(m => {
          if (m) {
            return { id: _id, username, email, roles } as UserPrincipal;
          }else {
            // The same reason above.
            //throw new UnauthorizedException('password was not matched.')
            throw new UnauthorizedException('username or password is not matched')
          }
        }))
      })
    );
  }
Example #2
Source File: post.service.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
update(id: string, data: UpdatePostDto): Observable<Post> {
    return from(
      this.postModel
        .findOneAndUpdate(
          { _id: id },
          { ...data, updatedBy: { _id: this.req.user.id } },
          { new: true },
        )
        .exec(),
    ).pipe(
      mergeMap((p) => (p ? of(p) : EMPTY)),
      throwIfEmpty(() => new NotFoundException(`post:$id was not found`)),
    );
    // const filter = { _id: id };
    // const update = { ...data, updatedBy: { _id: this.req.user.id } };
    // return from(this.postModel.findOne(filter).exec()).pipe(
    //   mergeMap((post) => (post ? of(post) : EMPTY)),
    //   throwIfEmpty(() => new NotFoundException(`post:$id was not found`)),
    //   switchMap((p, i) => {
    //     return from(this.postModel.updateOne(filter, update).exec());
    //   }),
    //   map((res) => res.nModified),
    // );
  }
Example #3
Source File: post.service.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
deleteById(id: string): Observable<Post> {
    return from(this.postModel.findOneAndDelete({ _id: id }).exec()).pipe(
      mergeMap((p) => (p ? of(p) : EMPTY)),
      throwIfEmpty(() => new NotFoundException(`post:$id was not found`)),
    );
    // const filter = { _id: id };
    // return from(this.postModel.findOne(filter).exec()).pipe(
    //   mergeMap((post) => (post ? of(post) : EMPTY)),
    //   throwIfEmpty(() => new NotFoundException(`post:$id was not found`)),
    //   switchMap((p, i) => {
    //     return from(this.postModel.deleteOne(filter).exec());
    //   }),
    //   map((res) => res.deletedCount),
    // );
  }
Example #4
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 #5
Source File: post.service.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
findById(id: string): Observable<Post> {
    return from(this.postModel.findOne({ _id: id }).exec()).pipe(
      mergeMap((p) => (p ? of(p) : EMPTY)),
      throwIfEmpty(() => new NotFoundException(`post:$id was not found`)),
    );
  }
Example #6
Source File: backend_srv.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
private handleStreamCancellation = (
    options: BackendSrvRequest,
    resultType: CancellationType
  ): MonoTypeOperatorFunction<FetchResponse | DataSourceSuccessResponse | SuccessResponse> => inputStream =>
    inputStream.pipe(
      takeUntil(
        this.inFlightRequests.pipe(
          filter(requestId => {
            let cancelRequest = false;
            if (options && options.requestId && options.requestId === requestId) {
              // when a new requestId is started it will be published to inFlightRequests
              // if a previous long running request that hasn't finished yet has the same requestId
              // we need to cancel that request
              cancelRequest = true;
            }
            return cancelRequest;
          })
        )
      ),
      // when a request is cancelled by takeUntil it will complete without emitting anything so we use throwIfEmpty to identify this case
      // in throwIfEmpty we'll then throw an cancelled error and then we'll return the correct result in the catchError or rethrow
      throwIfEmpty(() => ({
        cancelled: true,
      })),
      catchError(err => {
        if (!err.cancelled) {
          return throwError(err);
        }

        if (resultType === CancellationType.dataSourceRequest) {
          return of({
            data: [],
            status: this.HTTP_REQUEST_CANCELED,
            statusText: 'Request was aborted',
            config: options,
          });
        }

        return of([]);
      })
    );