feat(example): example of `use` operator
MODIFY
example/src/app.ts
example/src/app.ts
@@ -3,8 +3,13 @@ import { bodyParser$ } from '@marblejs/middleware-body';
import { logger$ } from '@marblejs/middleware-logger';
import { api$ } from './controllers/api.controller';
-const middlewares = [logger$, bodyParser$];
+const middlewares = [
+ logger$,
+ bodyParser$,
+];
-const effects = [api$];
+const effects = [
+ api$,
+];
export const app = httpListener({ middlewares, effects });

MODIFY
example/src/controllers/api.controller.ts
example/src/controllers/api.controller.ts
@@ -8,7 +8,7 @@ const root$: Effect = request$ => request$
matchType('GET'),
map(req => ({
body: `API root @ ${req.url}`,
- }))
+ })),
);
export const api$ = combineRoutes(

MODIFY
example/src/controllers/user.controller.ts
example/src/controllers/user.controller.ts
-import { Effect, combineRoutes, matchPath, matchType } from '@marblejs/core';
+import { Effect, combineRoutes, matchPath, matchType, use } from '@marblejs/core';
import { map, switchMap } from 'rxjs/operators';
import { Dao } from '../fakes/dao.fake';
+import { authorize$ } from '../middlewares/auth.middleware';
-const getUsers$: Effect = request$ => request$
- .pipe(
+const getUsers$: Effect = request$ =>
+ request$.pipe(
matchPath('/'),
matchType('GET'),
+ use(authorize$),
switchMap(Dao.getUsers),
- map(users => ({ body: users }))
+ map(users => ({ body: users })),
);
-const postUser$: Effect = request$ => request$
- .pipe(
+const postUser$: Effect = request$ =>
+ request$.pipe(
matchPath('/'),
matchType('POST'),
+ use(authorize$),
map(req => req.body),
switchMap(Dao.postUser),
- map(response => ({ body: response }))
+ map(response => ({ body: response })),
);
export const user$ = combineRoutes(

ADD
example/src/fakes/auth.fake.ts
+import { HttpRequest } from '@marblejs/core';
+
+export const isAuthorized = (request: HttpRequest) =>
+ request.headers.authorization
+ ? request.headers.authorization === 'Bearer FAKE'
+ : false;

MODIFY
example/src/fakes/dao.fake.ts
example/src/fakes/dao.fake.ts
@@ -9,7 +9,7 @@ export namespace Dao {
]);
export const postUser = (data: any) => of({
- data
+ data,
});
}

ADD
example/src/middlewares/auth.middleware.ts
+import { Effect, HttpError, HttpRequest, HttpStatus } from '@marblejs/core';
+import { Observable, merge, throwError } from 'rxjs';
+import { filter, switchMap } from 'rxjs/operators';
+import { isAuthorized } from '../fakes/auth.fake';
+
+const authorized$ = (req$: Observable<HttpRequest>) =>
+ req$.pipe(
+ filter(req => isAuthorized(req)),
+ );
+
+const unauthorized$ = (req$: Observable<HttpRequest>) =>
+ req$.pipe(
+ filter(req => !isAuthorized(req)),
+ switchMap(req =>
+ throwError(new HttpError('Unauthorized', HttpStatus.UNAUTHORIZED)),
+ ),
+ );
+
+export const authorize$: Effect<HttpRequest> = request$ =>
+ request$.pipe(
+ switchMap(() => merge(authorized$(request$), unauthorized$(request$))),
+ );

feat(example): example of `use` operator