-
Notifications
You must be signed in to change notification settings - Fork 73
/
body.middleware.ts
37 lines (34 loc) · 1.09 KB
/
body.middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { HttpError, HttpStatus, HttpMiddlewareEffect } from '@marblejs/core';
import { of, throwError, iif } from 'rxjs';
import { catchError, map, switchMap, tap, mapTo, mergeMap } from 'rxjs/operators';
import { defaultParser } from './parsers';
import { RequestBodyParser } from './body.model';
import { matchType, getBody, hasBody, isMultipart } from './body.util';
const PARSEABLE_METHODS = ['POST', 'PUT', 'PATCH'];
interface BodyParserOptions {
parser?: RequestBodyParser;
type?: string[];
}
export const bodyParser$ = ({
type = ['*/*'],
parser = defaultParser,
}: BodyParserOptions = {}): HttpMiddlewareEffect => req$ =>
req$.pipe(
switchMap(req => iif(
() =>
PARSEABLE_METHODS.includes(req.method)
&& !hasBody(req)
&& !isMultipart(req)
&& matchType(type)(req),
of(req).pipe(
mergeMap(getBody),
map(parser(req)),
tap(body => req.body = body),
mapTo(req),
catchError(() => throwError(
new HttpError('Request body parse error', HttpStatus.BAD_REQUEST),
))
),
of(req),
)),
);