UNPKG

@nestjs/microservices

Version:

Nest - modern, fast, powerful node.js web framework (@microservices)

32 lines (31 loc) • 1.47 kB
import { from as fromPromise, isObservable, of } from 'rxjs'; import { catchError, mergeMap } from 'rxjs/operators'; import { ExecutionContextHost } from '@nestjs/core/internal'; export class RpcProxy { create(targetCallback, exceptionsHandler, reportUnhandledErrors = false) { return async (...args) => { try { const result = await targetCallback(...args); return !isObservable(result) ? result : result.pipe(catchError(error => this.transformToObservable(this.handleError(exceptionsHandler, args, error, reportUnhandledErrors)))); } catch (error) { return this.handleError(exceptionsHandler, args, error, reportUnhandledErrors); } }; } handleError(exceptionsHandler, args, error, reportUnhandledErrors = false) { const host = new ExecutionContextHost(args); host.setType('rpc'); return exceptionsHandler.handle(error, host, reportUnhandledErrors); } // `catchError()` would emit the stream an async filter resolves to, iterate // a string or an array, and fail on other plain values. Resolve what the // filter returns as when the handler rejects instead. transformToObservable(result) { return isObservable(result) ? result : fromPromise(Promise.resolve(result)).pipe(mergeMap(val => (isObservable(val) ? val : of(val)))); } }