angular-in-memory-web-api
- Version 0.19.0
- Published
- 190 kB
- 1 dependency
- MIT license
Install
npm i angular-in-memory-web-api
yarn add angular-in-memory-web-api
pnpm add angular-in-memory-web-api
Overview
An in-memory web api for Angular demos and tests
Index
Variables
Functions
Classes
BackendService
- addDelay()
- applyQuery()
- bind()
- bodify()
- clone()
- collectionHandler()
- commands()
- config
- createErrorResponseOptions()
- createHeaders()
- createPassThruBackend()
- createQueryMap()
- createResponse$()
- createResponse$fromResponseOptions$()
- createResponseOptions$()
- db
- dbReady
- dbReadySubject
- delete()
- findById()
- genId()
- genIdDefault()
- get()
- getJsonBody()
- getLocation()
- getPassThruBackend()
- getRequestInfoUtils()
- getRequestMethod()
- handleRequest()
- handleRequest_()
- indexOf()
- inMemDbService
- isCollectionIdNumeric()
- parseId()
- parseRequestUrl()
- post()
- put()
- removeById()
- requestInfoUtils
- resetDb()
Interfaces
Type Aliases
Variables
variable STATUS
const STATUS: { CONTINUE: number; SWITCHING_PROTOCOLS: number; OK: number; CREATED: number; ACCEPTED: number; NON_AUTHORITATIVE_INFORMATION: number; NO_CONTENT: number; RESET_CONTENT: number; PARTIAL_CONTENT: number; MULTIPLE_CHOICES: number; MOVED_PERMANTENTLY: number; FOUND: number; SEE_OTHER: number; NOT_MODIFIED: number; USE_PROXY: number; TEMPORARY_REDIRECT: number; BAD_REQUEST: number; UNAUTHORIZED: number; PAYMENT_REQUIRED: number; FORBIDDEN: number; NOT_FOUND: number; METHOD_NOT_ALLOWED: number; NOT_ACCEPTABLE: number; PROXY_AUTHENTICATION_REQUIRED: number; REQUEST_TIMEOUT: number; CONFLICT: number; GONE: number; LENGTH_REQUIRED: number; PRECONDITION_FAILED: number; PAYLOAD_TO_LARGE: number; URI_TOO_LONG: number; UNSUPPORTED_MEDIA_TYPE: number; RANGE_NOT_SATISFIABLE: number; EXPECTATION_FAILED: number; IM_A_TEAPOT: number; UPGRADE_REQUIRED: number; INTERNAL_SERVER_ERROR: number; NOT_IMPLEMENTED: number; BAD_GATEWAY: number; SERVICE_UNAVAILABLE: number; GATEWAY_TIMEOUT: number; HTTP_VERSION_NOT_SUPPORTED: number; PROCESSING: number; MULTI_STATUS: number; IM_USED: number; PERMANENT_REDIRECT: number; UNPROCESSABLE_ENTRY: number; LOCKED: number; FAILED_DEPENDENCY: number; PRECONDITION_REQUIRED: number; TOO_MANY_REQUESTS: number; REQUEST_HEADER_FIELDS_TOO_LARGE: number; UNAVAILABLE_FOR_LEGAL_REASONS: number; VARIANT_ALSO_NEGOTIATES: number; INSUFFICIENT_STORAGE: number; NETWORK_AUTHENTICATION_REQUIRED: number;};
variable STATUS_CODE_INFO
const STATUS_CODE_INFO: { [key: string]: { code: number; text: string; description: string; spec_title: string; spec_href: string; };};
Functions
function getStatusText
getStatusText: (code: number) => string;
get the status text from StatusCode
function httpClientInMemBackendServiceFactory
httpClientInMemBackendServiceFactory: ( dbService: InMemoryDbService, options: InMemoryBackendConfig, xhrFactory: XhrFactory) => HttpBackend;
function isSuccess
isSuccess: (status: number) => boolean;
Returns true if the Http Status Code is 200-299 (success)
function parseUri
parseUri: (str: string) => UriInfo;
Return information (UriInfo) about a URI
function removeTrailingSlash
removeTrailingSlash: (path: string) => string;
Classes
class BackendService
abstract class BackendService {}
Base class for in-memory web api back-ends Simulate the behavior of a RESTy web api backed by the simple in-memory data store provided by the injected
InMemoryDbService
service. Conforms mostly to behavior described here: http://www.restapitutorial.com/lessons/httpmethods.html
constructor
constructor( inMemDbService: InMemoryDbService, config?: InMemoryBackendConfigArgs);
property config
protected config: InMemoryBackendConfigArgs;
property db
protected db: { [key: string]: any };
property dbReady
readonly dbReady: Observable<boolean>;
property dbReadySubject
protected dbReadySubject: any;
property inMemDbService
protected inMemDbService: InMemoryDbService;
property requestInfoUtils
protected requestInfoUtils: RequestInfoUtilities;
method addDelay
protected addDelay: (response: Observable<any>) => Observable<any>;
Add configured delay to response observable unless delay === 0
method applyQuery
protected applyQuery: (collection: any[], query: Map<string, string[]>) => any[];
Apply query/search parameters as a filter over the collection This impl only supports RegExp queries on string properties of the collection ANDs the conditions together
method bind
protected bind: <T extends Function>(methodName: string) => T | undefined;
Get a method from the
InMemoryDbService
(if it exists), bound to that service
method bodify
protected bodify: (data: any) => any;
method clone
protected clone: (data: any) => any;
method collectionHandler
protected collectionHandler: (reqInfo: RequestInfo_2) => ResponseOptions;
method commands
protected commands: (reqInfo: RequestInfo_2) => Observable<any>;
Commands reconfigure the in-memory web api service or extract information from it. Commands ignore the latency delay and respond ASAP.
When the last segment of the
apiBase
path is "commands", thecollectionName
is the command.Example URLs: commands/resetdb (POST) // Reset the "database" to its original state commands/config (GET) // Return this service's config object commands/config (POST) // Update the config (e.g. the delay)
Usage: http.post('commands/resetdb', undefined); http.get('commands/config'); http.post('commands/config', '{"delay":1000}');
method createErrorResponseOptions
protected createErrorResponseOptions: ( url: string, status: number, message: string) => ResponseOptions;
method createHeaders
protected abstract createHeaders: (headers: { [index: string]: string;}) => HttpHeaders;
Create standard HTTP headers object from hash map of header strings
Parameter headers
method createPassThruBackend
protected abstract createPassThruBackend: () => PassThruBackend;
create the function that passes unhandled requests through to the "real" backend.
method createQueryMap
protected abstract createQueryMap: (search: string) => Map<string, string[]>;
return a search map from a location query/search string
method createResponse$
protected createResponse$: ( resOptionsFactory: () => ResponseOptions, withDelay?: boolean) => Observable<any>;
Create a cold response Observable from a factory for ResponseOptions
Parameter resOptionsFactory
creates ResponseOptions when observable is subscribed
Parameter withDelay
if true (default), add simulated latency delay from configuration
method createResponse$fromResponseOptions$
protected abstract createResponse$fromResponseOptions$: ( resOptions$: Observable<ResponseOptions>) => Observable<any>;
Create a Response observable from ResponseOptions observable.
method createResponseOptions$
protected createResponseOptions$: ( resOptionsFactory: () => ResponseOptions) => Observable<ResponseOptions>;
Create a cold Observable of ResponseOptions.
Parameter resOptionsFactory
creates ResponseOptions when observable is subscribed
method delete
protected delete: ({ collection, collectionName, headers, id, url,}: RequestInfo_2) => ResponseOptions;
method findById
protected findById: <T extends { id: any }>( collection: T[], id: any) => T | undefined;
Find first instance of item in collection by
item.id
Parameter collection
Parameter id
method genId
protected genId: <T extends { id: any }>( collection: T[], collectionName: string) => any;
Generate the next available id for item in this collection Use method from
inMemDbService
if it exists and returns a value, else delegates togenIdDefault
.Parameter collection
collection of items with
id
key property
method genIdDefault
protected genIdDefault: <T extends { id: any }>( collection: T[], collectionName: string) => any;
Default generator of the next available id for item in this collection This default implementation works only for numeric ids.
Parameter collection
collection of items with
id
key propertyParameter collectionName
name of the collection
method get
protected get: ({ collection, collectionName, headers, id, query, url,}: RequestInfo_2) => ResponseOptions;
method getJsonBody
protected abstract getJsonBody: (req: any) => any;
Get JSON body from the request object
method getLocation
protected getLocation: (url: string) => UriInfo;
Get location info from a url, even on server where
document
is not defined
method getPassThruBackend
protected getPassThruBackend: () => PassThruBackend;
get or create the function that passes unhandled requests through to the "real" backend.
method getRequestInfoUtils
protected getRequestInfoUtils: () => RequestInfoUtilities;
Get utility methods from this service instance. Useful within an HTTP method override
method getRequestMethod
protected abstract getRequestMethod: (req: any) => string;
return canonical HTTP method name (lowercase) from the request object e.g. (req.method || 'get').toLowerCase();
Parameter req
request object from the http call
method handleRequest
protected handleRequest: (req: RequestCore) => Observable<any>;
Process Request and return an Observable of Http Response object in the manner of a RESTy web api.
Expect URI pattern in the form :base/:collectionName/:id? Examples: // for store with a 'customers' collection GET api/customers // all customers GET api/customers/42 // the character with id=42 GET api/customers?name=^j // 'j' is a regex; returns customers whose name starts with 'j' or 'J' GET api/customers.json/42 // ignores the ".json"
Also accepts direct commands to the service in which the last segment of the apiBase is the word "commands" Examples: POST commands/resetDb, GET/POST commands/config - get or (re)set the config
HTTP overrides: If the injected inMemDbService defines an HTTP method (lowercase) The request is forwarded to that method as in
inMemDbService.get(requestInfo)
which must return either an Observable of the response type for this http library or null|undefined (which means "keep processing").
method handleRequest_
protected handleRequest_: (req: RequestCore) => Observable<any>;
method indexOf
protected indexOf: (collection: any[], id: number) => number;
method isCollectionIdNumeric
protected isCollectionIdNumeric: <T extends { id: any }>( collection: T[], collectionName: string) => boolean;
return true if can determine that the collection's
item.id
is a number This implementation can't tell if the collection is empty so it assumes NO
method parseId
protected parseId: ( collection: any[], collectionName: string, id: string) => any;
Parse the id as a number. Return original value if not a number.
method parseRequestUrl
protected parseRequestUrl: (url: string) => ParsedRequestUrl;
Parses the request URL into a
ParsedRequestUrl
object. Parsing depends upon certain values ofconfig
:apiBase
,host
, andurlRoot
.Configuring the
apiBase
yields the most interesting changes toparseRequestUrl
behavior: When apiBase=undefined and url='http://localhost/api/collection/42' {base: 'api/', collectionName: 'collection', id: '42', ...} When apiBase='some/api/root/' and url='http://localhost/some/api/root/collection' {base: 'some/api/root/', collectionName: 'collection', id: undefined, ...} When apiBase='/' and url='http://localhost/collection' {base: '/', collectionName: 'collection', id: undefined, ...}The actual api base segment values are ignored. Only the number of segments matters. The following api base strings are considered identical: 'a/b' ~ 'some/api/' ~ `two/segments'
To replace this default method, assign your alternative to your InMemDbService['parseRequestUrl']
method post
protected post: ({ collection, collectionName, headers, id, req, resourceUrl, url,}: RequestInfo_2) => ResponseOptions;
method put
protected put: ({ collection, collectionName, headers, id, req, url,}: RequestInfo_2) => ResponseOptions;
method removeById
protected removeById: (collection: any[], id: number) => boolean;
method resetDb
protected resetDb: (reqInfo?: RequestInfo_2) => Observable<boolean>;
Tell your in-mem "database" to reset. returns Observable of the database because resetting it could be async
class HttpClientBackendService
class HttpClientBackendService extends BackendService implements HttpBackend {}
For Angular
HttpClient
simulate the behavior of a RESTy web api backed by the simple in-memory data store provided by the injectedInMemoryDbService
. Conforms mostly to behavior described here: https://www.restapitutorial.com/lessons/httpmethods.html### Usage
Create an in-memory data store class that implements
InMemoryDbService
. Callconfig
static method with this service class and optional configuration object:// other importsimport { HttpClientModule } from '@angular/common/http';import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';import { InMemHeroService, inMemConfig } from '../api/in-memory-hero.service';@NgModule({imports: [HttpModule,HttpClientInMemoryWebApiModule.forRoot(InMemHeroService, inMemConfig),...],...})export class AppModule { ... }
constructor
constructor( inMemDbService: InMemoryDbService, config: InMemoryBackendConfigArgs, xhrFactory: XhrFactory);
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration< HttpClientBackendService, [null, { optional: true }, null]>;
property ɵprov
static ɵprov: i0.ɵɵInjectableDeclaration<HttpClientBackendService>;
method createHeaders
protected createHeaders: (headers: { [index: string]: string }) => HttpHeaders;
method createPassThruBackend
protected createPassThruBackend: () => HttpXhrBackend;
method createQueryMap
protected createQueryMap: (search: string) => Map<string, string[]>;
method createResponse$fromResponseOptions$
protected createResponse$fromResponseOptions$: ( resOptions$: Observable<ResponseOptions>) => Observable<HttpResponse<any>>;
method getJsonBody
protected getJsonBody: (req: HttpRequest<any>) => any;
method getRequestMethod
protected getRequestMethod: (req: HttpRequest<any>) => string;
method handle
handle: (req: HttpRequest<any>) => Observable<HttpEvent<any>>;
class HttpClientInMemoryWebApiModule
class HttpClientInMemoryWebApiModule {}
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<HttpClientInMemoryWebApiModule, never>;
property ɵinj
static ɵinj: i0.ɵɵInjectorDeclaration<HttpClientInMemoryWebApiModule>;
property ɵmod
static ɵmod: i0.ɵɵNgModuleDeclaration< HttpClientInMemoryWebApiModule, never, never, never>;
method forFeature
static forFeature: ( dbCreator: Type<InMemoryDbService>, options?: InMemoryBackendConfigArgs) => ModuleWithProviders<HttpClientInMemoryWebApiModule>;
Enable and configure the in-memory web api in a lazy-loaded feature module. Same as
forRoot
. This is a feel-good method so you can follow the Angular style guide for lazy-loaded modules.
method forRoot
static forRoot: ( dbCreator: Type<InMemoryDbService>, options?: InMemoryBackendConfigArgs) => ModuleWithProviders<HttpClientInMemoryWebApiModule>;
Redirect the Angular
HttpClient
XHR calls to in-memory data store that implementsInMemoryDbService
. with class that implements InMemoryDbService and creates an in-memory database.Usually imported in the root application module. Can import in a lazy feature module too, which will shadow modules loaded earlier
Note: If you use the
FetchBackend
, make sure forRoot is invoked after in the providers listParameter dbCreator
Class that creates seed data for in-memory database. Must implement InMemoryDbService.
Parameter options
Example 1
HttpInMemoryWebApiModule.forRoot(dbCreator); HttpInMemoryWebApiModule.forRoot(dbCreator, {useValue: {delay:600}});
class InMemoryBackendConfig
class InMemoryBackendConfig implements InMemoryBackendConfigArgs {}
InMemoryBackendService configuration options Usage: InMemoryWebApiModule.forRoot(InMemHeroService, {delay: 600})
or if providing separately: provide(InMemoryBackendConfig, {useValue: {delay: 600}}),
constructor
constructor(config?: InMemoryBackendConfigArgs);
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<InMemoryBackendConfig, never>;
property ɵprov
static ɵprov: i0.ɵɵInjectableDeclaration<InMemoryBackendConfig>;
class InMemoryBackendConfigArgs
abstract class InMemoryBackendConfigArgs {}
Interface for InMemoryBackend configuration options
property apiBase
apiBase?: string;
The base path to the api, e.g, 'api/'. If not specified than
parseRequestUrl
assumes it is the first path segment in the request.
property caseSensitiveSearch
caseSensitiveSearch?: boolean;
false (default) if search match should be case insensitive
property dataEncapsulation
dataEncapsulation?: boolean;
false (default) put content directly inside the response body. true: encapsulate content in a
data
property inside the response body,{ data: ... }
.
property delay
delay?: number;
delay (in ms) to simulate latency
property delete404
delete404?: boolean;
false (default) should 204 when object-to-delete not found; true: 404
property host
host?: string;
host for this service, e.g., 'localhost'
property passThruUnknownUrl
passThruUnknownUrl?: boolean;
true, should pass unrecognized request URL through to original backend; false (default): 404
property post204
post204?: boolean;
true (default) should NOT return the item (204) after a POST. false: return the item (200).
property post409
post409?: boolean;
false (default) should NOT update existing item with POST. false: OK to update.
property put204
put204?: boolean;
true (default) should NOT return the item (204) after a POST. false: return the item (200).
property put404
put404?: boolean;
false (default) if item not found, create as new item; false: should 404.
property rootPath
rootPath?: string;
root path _before_ any API call, e.g., ''
class InMemoryDbService
abstract class InMemoryDbService {}
Interface for a class that creates an in-memory database
Its
createDb
method creates a hash of named collections that represents the databaseFor maximum flexibility, the service may define HTTP method overrides. Such methods must match the spelling of an HTTP method in lower case (e.g, "get"). If a request has a matching method, it will be called as in
get(info: requestInfo, db: {})
wheredb
is the database object described above.
method createDb
abstract createDb: ( reqInfo?: RequestInfo_2) => {} | Observable<{}> | Promise<{}>;
Creates an in-memory "database" hash whose keys are collection names and whose values are arrays of collection objects to return or update.
returns Observable of the database because could have to create it asynchronously.
This method must be safe to call repeatedly. Each time it should return a new object with new arrays containing new item objects. This condition allows the in-memory backend service to mutate the collections and their items without touching the original source data.
The in-mem backend service calls this method without a value the first time. The service calls it with the
RequestInfo
when it receives a POSTcommands/resetDb
request. Your InMemoryDbService can adjust its behavior accordingly.
class InMemoryWebApiModule
class InMemoryWebApiModule {}
property ɵfac
static ɵfac: i0.ɵɵFactoryDeclaration<InMemoryWebApiModule, never>;
property ɵinj
static ɵinj: i0.ɵɵInjectorDeclaration<InMemoryWebApiModule>;
property ɵmod
static ɵmod: i0.ɵɵNgModuleDeclaration<InMemoryWebApiModule, never, never, never>;
method forFeature
static forFeature: ( dbCreator: Type<InMemoryDbService>, options?: InMemoryBackendConfigArgs) => ModuleWithProviders<InMemoryWebApiModule>;
Enable and configure the in-memory web api in a lazy-loaded feature module. Same as
forRoot
. This is a feel-good method so you can follow the Angular style guide for lazy-loaded modules.
method forRoot
static forRoot: ( dbCreator: Type<InMemoryDbService>, options?: InMemoryBackendConfigArgs) => ModuleWithProviders<InMemoryWebApiModule>;
Redirect BOTH Angular
Http
andHttpClient
XHR calls to in-memory data store that implementsInMemoryDbService
. with class that implements InMemoryDbService and creates an in-memory database.Usually imported in the root application module. Can import in a lazy feature module too, which will shadow modules loaded earlier
Note: If you use the
FetchBackend
, make sure forRoot is invoked after in the providers listParameter dbCreator
Class that creates seed data for in-memory database. Must implement InMemoryDbService.
Parameter options
Example 1
InMemoryWebApiModule.forRoot(dbCreator); InMemoryWebApiModule.forRoot(dbCreator, {useValue: {delay:600}});
Interfaces
interface ParsedRequestUrl
interface ParsedRequestUrl {}
Interface for the result of the
parseRequestUrl
method: Given URL "http://localhost:8080/api/customers/42?foo=1 the default implementation returns base: 'api/' collectionName: 'customers' id: '42' query: this.createQuery('foo=1') resourceUrl: 'http://localhost/api/customers/'
property apiBase
apiBase: string;
property collectionName
collectionName: string;
property id
id: string;
property query
query: Map<string, string[]>;
property resourceUrl
resourceUrl: string;
interface PassThruBackend
interface PassThruBackend {}
method handle
handle: (req: any) => Observable<any>;
Handle an HTTP request and return an Observable of HTTP response Both the request type and the response type are determined by the supporting HTTP library.
interface RequestCore
interface RequestCore {}
Minimum definition needed by base class
property url
url: string;
property urlWithParams
urlWithParams?: string;
interface RequestInfo
interface RequestInfo_2 {}
Interface for object w/ info about the current request url extracted from an Http Request. Also holds utility methods and configuration data from this service
property apiBase
apiBase: string;
property collection
collection: any;
property collectionName
collectionName: string;
property headers
headers: HttpHeaders;
property id
id: any;
property method
method: string;
property query
query: Map<string, string[]>;
property req
req: RequestCore;
property resourceUrl
resourceUrl: string;
property url
url: string;
property utils
utils: RequestInfoUtilities;
interface RequestInfoUtilities
interface RequestInfoUtilities {}
Interface for utility methods from this service instance. Useful within an HTTP method override
property createResponse$
createResponse$: (resOptionsFactory: () => ResponseOptions) => Observable<any>;
Create a cold response Observable from a factory for ResponseOptions the same way that the in-mem backend service does.
Parameter resOptionsFactory
creates ResponseOptions when observable is subscribed
Parameter withDelay
if true (default), add simulated latency delay from configuration
method findById
findById: <T extends { id: any }>(collection: T[], id: any) => T | undefined;
Find first instance of item in collection by
item.id
Parameter collection
Parameter id
method getConfig
getConfig: () => InMemoryBackendConfigArgs;
return the current, active configuration which is a blend of defaults and overrides
method getDb
getDb: () => {};
Get the in-mem service's copy of the "database"
method getJsonBody
getJsonBody: (req: any) => any;
Get JSON body from the request object
method getLocation
getLocation: (url: string) => UriInfo;
Get location info from a url, even on server where
document
is not defined
method getPassThruBackend
getPassThruBackend: () => PassThruBackend;
Get (or create) the "real" backend
method isCollectionIdNumeric
isCollectionIdNumeric: <T extends { id: any }>( collection: T[], collectionName: string) => boolean;
return true if can determine that the collection's
item.id
is a number
method parseRequestUrl
parseRequestUrl: (url: string) => ParsedRequestUrl;
Parses the request URL into a
ParsedRequestUrl
object. Parsing depends upon certain values ofconfig
:apiBase
,host
, andurlRoot
.
interface ResponseOptions
interface ResponseOptions {}
property body
body?: string | Object | ArrayBuffer | Blob;
String, Object, ArrayBuffer or Blob representing the body of the Response.
property headers
headers?: HttpHeaders;
Response headers
property status
status?: number;
Http associated with the response.
property statusText
statusText?: string;
Status text for the status code
property url
url?: string;
request url
interface UriInfo
interface UriInfo {}
Interface of information about a Uri
property anchor
anchor: string;
property authority
authority: string;
property directory
directory: string;
property file
file: string;
property host
host: string;
property password
password: string;
property path
path: string;
property port
port: string;
property protocol
protocol: string;
property query
query: string;
property relative
relative: string;
property source
source: string;
property user
user: string;
property userInfo
userInfo: string;
Type Aliases
type ResponseInterceptor
type ResponseInterceptor = ( res: ResponseOptions, ri: RequestInfo_2) => ResponseOptions;
Provide a
responseInterceptor
method of this type in yourinMemDbService
to morph the response options created in thecollectionHandler
.
Package Files (1)
Dependencies (1)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (3)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/angular-in-memory-web-api
.
- Markdown[](https://www.jsdocs.io/package/angular-in-memory-web-api)
- HTML<a href="https://www.jsdocs.io/package/angular-in-memory-web-api"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 2341 ms. - Missing or incorrect documentation? Open an issue for this package.