Last active
November 16, 2020 13:44
-
-
Save DScheglov/01dae7db0c7731da5454dc7bb674b061 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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