Skip to content

Instantly share code, notes, and snippets.

@DScheglov
Last active November 16, 2020 13:44
Show Gist options
  • Save DScheglov/01dae7db0c7731da5454dc7bb674b061 to your computer and use it in GitHub Desktop.
Save DScheglov/01dae7db0c7731da5454dc7bb674b061 to your computer and use it in GitHub Desktop.
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { flatMap } from 'rxjs/operators';
import { fromFunctionCall } from '../common/utils';
@Injectable()
export class LoginInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const req = context.switchToHttp().getRequest();
return fromFunctionCall(req.logIn, req.user).pipe(
flatMap(() => next.handle())
);
}
import { Observable } from "rxjs";
type Fn<A extends any[], R> = (...args: A) => R;
type Cb<E extends Error, R> = (err?: E | null, result?: R) => void;
export const fromFunctionCall = <A extends any[], E extends Error, R>(
fn: Fn<[...A, Cb<E, R>], void>,
...args: A
): Observable<R> => new Observable(
observer => fn(...args, (err?: E | null, result?: R) => {
if (err) {
observer.error(err);
return;
}
observer.next(result);
observer.complete();
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment