@nestjs/websockets
Version:
WebSockets for NestJS: gateways with message handlers, guards, pipes and interceptors, on Socket.IO or ws.
33 lines (32 loc) • 1.37 kB
JavaScript
import { EMPTY, from, isObservable } from 'rxjs';
import { catchError, ignoreElements } from 'rxjs/operators';
import { ExecutionContextHost } from '@nestjs/core/internal';
export class WsProxy {
create(targetCallback, exceptionsHandler, targetPattern) {
return async (...args) => {
args = [...args, targetPattern ?? 'unknown'];
try {
const result = await targetCallback(...args);
return !isObservable(result)
? result
: result.pipe(catchError(error => {
const pending = this.handleError(exceptionsHandler, args, error);
return pending ? from(pending).pipe(ignoreElements()) : EMPTY;
}));
}
catch (error) {
// The message is being handled until an asynchronous exception filter
// is done, which is what the adapters count ("maxConcurrentMessages")
const pending = this.handleError(exceptionsHandler, args, error);
if (pending) {
await pending;
}
}
};
}
handleError(exceptionsHandler, args, error) {
const host = new ExecutionContextHost(args);
host.setType('ws');
return exceptionsHandler.handle(error, host);
}
}