From b297f4e46064738fb0832a154e67588f85a21cfe Mon Sep 17 00:00:00 2001 From: Jason Burns Date: Fri, 7 Jul 2017 18:15:27 -0700 Subject: [PATCH] Allow default behavior with http interceptors Allow an HTTP interceptor method to return null to signal to the service that it should run the collection handler or the fallback handler for the request. --- README.md | 10 +++++++++- src/in-memory-backend.service.ts | 16 ++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 3874869..433c229 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,15 @@ The `InMemoryDbService` method name must be the same as the HTTP method name but This service calls it with an `HttpMethodInterceptorArgs` object. For example, your HTTP GET interceptor would be called like this: e.g., `yourInMemDbService["get"](interceptorArgs)`. -Your method must **return an `Observable`** which _should be "cold"_. + +Your method can have two possible returns: +* `null` - the service will continue on with its default processing (checking the collection or +falling back to a different backend). This is useful if you only wish to handle processing +for certain paths in the given HTTP method. +* `Observable` - your code has handled the request and the response is available from this +observable. It _should be "cold"_. + +Your method must **return one of these two values**. The `HttpMethodInterceptorArgs` (as of this writing) are: ```ts diff --git a/src/in-memory-backend.service.ts b/src/in-memory-backend.service.ts index 8c70cff..d091997 100644 --- a/src/in-memory-backend.service.ts +++ b/src/in-memory-backend.service.ts @@ -343,7 +343,10 @@ export class InMemoryBackendService { if (/commands\/$/i.test(reqInfo.base)) { return this.commands(reqInfo); - } else if (this.inMemDbService[reqMethodName]) { + } + + // Don't do an else if to allow interceptor to fall back to default behavior below. + if (this.inMemDbService[reqMethodName]) { // InMemoryDbService has an overriding interceptor for this HTTP method; call it // The interceptor result must be an Observable const interceptorArgs: HttpMethodInterceptorArgs = { @@ -352,10 +355,15 @@ export class InMemoryBackendService { config: this.config, passThruBackend: this.passThruBackend }; - const interceptorResponse = this.inMemDbService[reqMethodName](interceptorArgs) as Observable; - return this.addDelay(interceptorResponse); - } else if (reqInfo.collection) { + const interceptorResponse = this.inMemDbService[reqMethodName](interceptorArgs); + if (interceptorResponse !== null) { + return this.addDelay(interceptorResponse as Observable); + } + } + + // Standard behavior without interceptors + if (reqInfo.collection) { // request is for a collection created by the InMemoryDbService return this.addDelay(this.collectionHandler(reqInfo));