improvement - handle case if endpint is not found
MODIFY
example/controllers.ts
example/controllers.ts
import { filter, map } from 'rxjs/operators';
import { RequestEffect } from '../src';
+import { StatusCode } from '../src/util';
export const root$: RequestEffect = request$ => request$
.pipe(
filter(http => http.url === '/'),
map(http => ({
- status: 200,
+ status: StatusCode.OK,
body: { data: `API root @ ${http.url}` },
}))
);
@@ -14,7 +15,7 @@ export const hello$: RequestEffect = request$ => request$
.pipe(
filter(http => http.url === '/hello'),
map(http => ({
- status: 200,
+ status: StatusCode.OK,
body: { data: `Hello, world! @ ${http.url}` },
}))
);

MODIFY
src/effects/effects.interface.ts
src/effects/effects.interface.ts
import { Observable } from 'rxjs';
import { HttpRequest, HttpResponse } from '../http.interface';
+import { StatusCode } from '../util';
export type EffectResponse = {
- status: number,
+ status: StatusCode,
body?: object,
headers?: Record<string, string>,
};

MODIFY
src/http.interface.ts
src/http.interface.ts
@@ -8,7 +8,3 @@ export type Http = {
req: HttpRequest,
res: HttpResponse,
};
-
-export enum ContentType {
- APPLICATION_JSON = 'application/json',
-}

MODIFY
src/http.listener.ts
src/http.listener.ts
import * as http from 'http';
import { Subject, of } from 'rxjs';
-import { map, tap, switchMap } from 'rxjs/operators';
+import { defaultIfEmpty, map, tap, switchMap } from 'rxjs/operators';
import { Http, HttpRequest, HttpResponse } from './http.interface';
import { combineEffects, RequestEffect, EffectResponse } from './effects';
import { loggerMiddleware } from './middlewares';
import { handleResponse } from './response';
+import { StatusCode } from './util';
export const httpListener = (...effects: RequestEffect[]) => {
const request$ = new Subject<Http>();
@@ -13,7 +14,10 @@ export const httpListener = (...effects: RequestEffect[]) => {
map(loggerMiddleware),
switchMap(({ req, res }) =>
combineEffects(...effects)(of(req), res)
- .pipe(tap(effect => handleResponse(res)(effect)))
+ .pipe(
+ defaultIfEmpty({ status: StatusCode.NOT_FOUND }),
+ tap(effect => handleResponse(res)(effect))
+ )
),
);

MODIFY
src/response/responseHeaders.factory.ts
src/response/responseHeaders.factory.ts
import { HttpHeaders } from '../http.interface';
+import { ContentType } from '../util';
export const DEFAULT_HEADERS = {
- 'Content-Type': 'application/json',
+ 'Content-Type': ContentType.APPLICATION_JSON,
};
export const headersFactory = (headers?: HttpHeaders) => ({

ADD
src/util/content-type.util.ts
+export enum ContentType {
+ APPLICATION_JSON = 'application/json',
+}

ADD
src/util/index.ts
+export * from './content-type.util';
+export * from './status-code.util';

ADD
src/util/status-code.util.ts
+export enum StatusCode {
+ OK = 200,
+ NOT_FOUND = 404,
+}

improvement - handle case if endpint is not found