From 87a679b210b265d584ba8c46da87845ad1bd5845 Mon Sep 17 00:00:00 2001 From: crisbeto Date: Fri, 12 Jun 2020 18:25:08 +0200 Subject: [PATCH] build: import in-memory-web-api project (#37182) Moves the `angular-in-memory-web-api` project into the main repository in order to make it easier to maintain and release. PR Close #37182 --- .pullapprove.yml | 15 + karma-js.conf.js | 1 + package.json | 2 + .../angular-in-memory-web-api/BUILD.bazel | 29 + .../angular-in-memory-web-api/CHANGELOG.md | 497 +++++++++++++ .../misc/angular-in-memory-web-api/index.ts | 14 + .../angular-in-memory-web-api/package.json | 22 + .../angular-in-memory-web-api/public_api.ts | 11 + .../src/backend-service.ts | 663 ++++++++++++++++++ .../src/delay-response.ts | 38 + .../src/http-client-backend-service.ts | 100 +++ .../http-client-in-memory-web-api-module.ts | 65 ++ .../src/http-status-codes.ts | 523 ++++++++++++++ .../src/in-memory-web-api-module.ts | 58 ++ .../src/in-memory-web-api.ts | 14 + .../src/interfaces.ts | 316 +++++++++ .../test/BUILD.bazel | 34 + .../hero-in-mem-data-override-service.ts | 89 +++ .../test/fixtures/hero-in-mem-data-service.ts | 79 +++ .../test/fixtures/hero-service.ts | 21 + .../test/fixtures/hero.ts | 14 + .../test/fixtures/http-client-hero-service.ts | 76 ++ .../test/http-client-backend-service_spec.ts | 574 +++++++++++++++ packages/tsconfig.json | 3 +- test-main.js | 2 + yarn.lock | 10 + 26 files changed, 3269 insertions(+), 1 deletion(-) create mode 100644 packages/misc/angular-in-memory-web-api/BUILD.bazel create mode 100644 packages/misc/angular-in-memory-web-api/CHANGELOG.md create mode 100644 packages/misc/angular-in-memory-web-api/index.ts create mode 100644 packages/misc/angular-in-memory-web-api/package.json create mode 100644 packages/misc/angular-in-memory-web-api/public_api.ts create mode 100644 packages/misc/angular-in-memory-web-api/src/backend-service.ts create mode 100644 packages/misc/angular-in-memory-web-api/src/delay-response.ts create mode 100644 packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts create mode 100644 packages/misc/angular-in-memory-web-api/src/http-client-in-memory-web-api-module.ts create mode 100644 packages/misc/angular-in-memory-web-api/src/http-status-codes.ts create mode 100644 packages/misc/angular-in-memory-web-api/src/in-memory-web-api-module.ts create mode 100644 packages/misc/angular-in-memory-web-api/src/in-memory-web-api.ts create mode 100644 packages/misc/angular-in-memory-web-api/src/interfaces.ts create mode 100644 packages/misc/angular-in-memory-web-api/test/BUILD.bazel create mode 100644 packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-override-service.ts create mode 100644 packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-service.ts create mode 100644 packages/misc/angular-in-memory-web-api/test/fixtures/hero-service.ts create mode 100644 packages/misc/angular-in-memory-web-api/test/fixtures/hero.ts create mode 100644 packages/misc/angular-in-memory-web-api/test/fixtures/http-client-hero-service.ts create mode 100644 packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts diff --git a/.pullapprove.yml b/.pullapprove.yml index f0c6cc9955..8c5e6a8d66 100644 --- a/.pullapprove.yml +++ b/.pullapprove.yml @@ -696,6 +696,21 @@ groups: - JiaLiPassion - mhevery + # ========================================================= + # in-memory-web-api + # ========================================================= + in-memory-web-api: + conditions: + - *can-be-global-approved + - *can-be-global-docs-approved + - > + contains_any_globs(files, [ + 'packages/misc/angular-in-memory-web-api/**', + ]) + reviewers: + users: + - IgorMinar + - crisbeto # ========================================================= # Benchpress diff --git a/karma-js.conf.js b/karma-js.conf.js index 5beafbe25e..ce31b84a83 100644 --- a/karma-js.conf.js +++ b/karma-js.conf.js @@ -36,6 +36,7 @@ module.exports = function(config) { {pattern: 'node_modules/angular-mocks/angular-mocks.js', included: false, watched: false}, 'node_modules/core-js/client/core.js', + 'node_modules/jasmine-ajax/lib/mock-ajax.js', 'dist/bin/packages/zone.js/npm_package/bundles/zone.umd.js', 'dist/bin/packages/zone.js/npm_package/bundles/zone-testing.umd.js', 'dist/bin/packages/zone.js/npm_package/bundles/task-tracking.umd.js', diff --git a/package.json b/package.json index bb34ff5a15..1dacfe48a5 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,7 @@ "@types/hammerjs": "2.0.35", "@types/inquirer": "^6.5.0", "@types/jasmine": "3.5.10", + "@types/jasmine-ajax": "^3.3.1", "@types/jasminewd2": "^2.0.8", "@types/minimist": "^1.2.0", "@types/node": "^12.11.1", @@ -111,6 +112,7 @@ "http-server": "^0.11.1", "incremental-dom": "0.4.1", "jasmine": "^3.5.0", + "jasmine-ajax": "^4.0.0", "jasmine-core": "^3.5.0", "jquery": "3.0.0", "js-levenshtein": "^1.1.6", diff --git a/packages/misc/angular-in-memory-web-api/BUILD.bazel b/packages/misc/angular-in-memory-web-api/BUILD.bazel new file mode 100644 index 0000000000..6c77cda79c --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/BUILD.bazel @@ -0,0 +1,29 @@ +load("//tools:defaults.bzl", "ng_module", "ng_package") + +package(default_visibility = ["//visibility:public"]) + +ng_module( + name = "angular-in-memory-web-api", + srcs = glob( + [ + "*.ts", + "src/**/*.ts", + ], + ), + module_name = "angular-in-memory-web-api", + deps = [ + "//packages/common", + "//packages/common/http", + "//packages/core", + "@npm//rxjs", + ], +) + +ng_package( + name = "npm_package", + srcs = ["package.json"], + entry_point = ":index.ts", + deps = [ + ":angular-in-memory-web-api", + ], +) diff --git a/packages/misc/angular-in-memory-web-api/CHANGELOG.md b/packages/misc/angular-in-memory-web-api/CHANGELOG.md new file mode 100644 index 0000000000..847d31e697 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/CHANGELOG.md @@ -0,0 +1,497 @@ +# "angular-in-memory-web-api" versions +>This in-memory-web-api exists primarily to support the Angular documentation. +It is not supposed to emulate every possible real world web API and is not intended for production use. +> +>Most importantly, it is ***always experimental***. + +We will make breaking changes and we won't feel bad about it +because this is a development tool, not a production product. +We do try to tell you about such changes in this `CHANGELOG.md` +and we fix bugs as fast as we can. + + +## 0.11.0 (2020-05-13) + +* update to support Angular v10. +* no functional changes. + + +## 0.9.0 (2019-06-20) + +* update to support Angular version 8.x and forward +* no functional changes + + +## 0.8.0 (2018-12-06) + +* remove `@angular/http` support +* no functional changes + +**BREAKING CHANGE** +This version no longer supports any functionality for `@angular/http`. Please use +`@angular/common/http` instead. + + +## 0.7.0 (2018-10-31) + +* update to support Angular v7. +* no functional changes + + +## 0.6.1 (2018-05-04) + +* update to Angular and RxJS v6 releases + + +## 0.6.0 (2018-03-22) + +*Migrate to Angular v6 and RxJS v6 (rc and beta)* + +Note that this release is pinned to Angular "^6.0.0-rc.0" and RxJS "^6.0.0-beta.1". +Will likely update again when they are official. + +**BREAKING CHANGE** +This version depends on RxJS v6 and is not backward compatible with earlier RxJS versions. + + +## 0.5.4 (2018-03-09) + +Simulated HTTP error responses were not delaying the prescribed time when using RxJS `delay()` +because it was short-circuited by the ErrorResponse. +New `delayResponse` function does it right. +Should not break you unless you incorrectly expected no delay for errors. + +Also, this library no longer calls RxJS `delay()` which may make testing with it easier +(Angular TestBed does not handle RxJS `delay()` well because that operator uses `interval()`). + +Also fixes type error (issue #180). + + +## 0.5.3 (2018-01-06) +Can make use of `HttpParams` which yields a `request.urlWithParams`. +Added supporting `HeroService.searchHeroes(term: string)` and test. + + +## 0.5.2 (2017-12-10) +No longer modify the request data coming from client. Fixes #164 + + +## 0.5.1 (2017-10-21) +Support Angular v5. + + +## 0.5.0 (2017-10-05) +**BREAKING CHANGE**: HTTP response data no longer wrapped in object w/ `data` property by default. + +In this release, the `dataEncapsulation` configuration default changed from `false` to `true`. The HTTP response body holds the data values directly rather than an object that encapsulates those values, `{data: ...}`. This is a **breaking change that affects almost all existing apps!** + +Changing the default to `false` is a **breaking change**. Pre-existing apps that did not set this property explicitly will be broken because they expect encapsulation and are probably mapping +the HTTP response results from the `data` property like this: +``` + .map(data => data.data as Hero[]) +``` +**To migrate, simply remove that line everywhere.** + +If you would rather keep the web api's encapsulation, `{data: ...}`, set `dataEncapsulation` to `true` during configuration as in the following example: +``` +HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, { dataEncapsulation: true }) +``` + +We made this change because + +1. Almost everyone seems to hate the encapsulation + +2. Encapsulation requires mapping to get the desired data out. With old `Http` that isn't _too_ bad because you needed to map to get data anyway (`res => res.json()`). But it is really ugly for `HttpClient` because you can't use the type HTTP method type parameter (e.g., `get`) and you have to map out of the data property (`.map(data => data.data as Hero[]`). That extra step requires explanations that distract from learning `HttpClient` itself. +Now you just write `http.get()` and you’ve got data (please add error handling). + +3. While you could have turned off encapsulation with configuration as of v.0.4, to do so took yet another step that you’d have to discover and explain. A big reason for the in-mem web api is to make it easy to introduce and demonstrate HTTP operations in Angular. The _out-of-box_ experience is more important than avoiding a breaking change. + +4. The [security flaw](http://stackoverflow.com/questions/3503102/what-are-top-level-json-arrays-and-why-are-they-a-security-risk) +that prompted encapsulation seems to have been mitigated by all (almost all?) the browsers that can run an Angular (v2+) app. We don’t think it’s needed anymore. + +5. A most real world APIs today will not encapsulate; they’ll return the data in the body without extra ceremony. + + +## 0.4.6 (2017-09-13) +- improves README +- updates v0.4.0 entry in the CHANGELOG to describe essential additions to SystemJS configuration. +- no important functional changes. + + +## 0.4.5 (2017-09-11) +Feature - offer separate `HttpClientInMemoryWebApiModule` and `HttpInMemoryWebApiModule`. + +closes #140 + + +## 0.4.4 (2017-09-11) +closes #136 + +A **breaking change** if you expected `genId` to generate ids for a collection +with non-numeric `item.id`. + + +## 0.4.3 (2017-09-11) +Refactoring for clarity and to correctly reflect intent. +A **breaking change** only if your customizations depend directly and explicitly on `RequestInfo` or the `get`, `delete`, `post`, or `put` methods. + +- replace all `switchMap` with `concatMap` because, in all previous uses of `switchMap`, +I really meant to wait for the source observable to complete _before_ beginning the inner observable whereas `switchMap` starts the inner observable right away. + +- restored `collection` to the `RequestInfo` interface and set it in `handleRequest_` +- `get`, `delete`, `post`, and `put` methods get the `collection` from `requestInfo`; simplifies their signatures to one parameter. + + +## 0.4.2 (2017-09-08) +- Postpones the in-memory database initialization (via `resetDb`) until the first HTTP request. + +- Your `createDb` method _can_ be asynchronous. +You may return the database object (synchronous), an observable of it, or a promise of it. Issue #113. + +- fixed some rare race conditions. + + +## 0.4.1 (2017-09-08) +**Support PassThru.** + +The passthru feature was broken by 0.4.0 +- add passthru to both `Http` and `HttpClient` +- test passThru feature with jasmine-ajax mock-ajax plugin +to intercept Angular's attempt to call browser's XHR +- update devDependency packages +- update karma.conf with jasmine-ajax plugin + + +## 0.4.0 (2017-09-07) +**Theme: Support `HttpClient` and add tests**. +See PR #130. + +The 0.4.0 release was a major overhaul of this library. + +You don't have to change your existing application _code_ if your app uses this library without customizations. + +But this release's **breaking changes** affect developers who used the customization features or loaded application files with SystemJS. + +**BREAKING CHANGES**: Massive refactoring. +Many low-level and customization options have changed. +Apps that stuck with defaults should be (mostly) OK. + +If you're loading application files with **SystemJS** (as you would in a plunker), see the [instructions below](#v-0-4-systemjs). + +* added support for `HttpClient` -> renaming of backend service classes +* added tests +* refactor existing code to support tests +* correct bugs and clarify choices as result of test +* add some configuration options + - dataEncapsulation (issue #112, pr#123) + - post409 + - put404b +* `POST commands/resetDb` passes the request to your `resetDb` method +so you can optionally reset the database dynamically +to arbitrary initial states (issue #128) +* when HTTP method interceptor returns null/undefined, continue with service's default processing (pr #120) +* can substitute your own id generator, `geniD` +* parseUrl -> parseRequestUrl +* utility methods exposed in `RequestInfo.utils` +* reorganize files into src/app and src/in-mem +* adjust gulp tasks accordingly + +--- + + +### Plunkers and SystemJS + +If you’re loading application files with **SystemJS** (as you would in a plunker), you’ll have to configure it to load Angular’s `umd.js` for `HttpModule` and the `tslib` package. + +To see how, look in the `map` section of the +[`src/systemjs.config.js` for this project](https://github.com/angular/in-memory-web-api/blob/master/src/systemjs.config.js) for the following two _additional_ lines : + +``` +'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js', +... +'tslib': 'npm:tslib/tslib.js', + +``` + +You've already made these changes if you are using `HttpClient` today. + +If you’re sticking with the original Angular `Http` module, you _must make this change anyway!_ Your app will break as soon as you run `npm install` and it installs >=v0.4.0. + +If you're using webpack (as CLI devs do), you don't have to worry about this stuff because webpack bundles the dependencies for you. + +--- + + +## 0.3.2 (2017-05-02) +* Bug fixes PRs #91, 95, 106 + + +## 0.3.1 (2017-03-08) +* Now runs in node so can use in "universal" demos. +See PR #102. + + +## 0.3.0 (2017-02-27) +* Support Angular version 4 + + +## 0.2.4 (2017-01-02) +* Remove reflect-matadata and zone.js as peerDependencies + + +## 0.2.3 (2016-12-28) +* Unpin RxJs + + +## 0.2.2 (2016-12-20) +* Update to Angular 2.4.0 + + +## 0.2.1 (2016-12-14) +* Fixed regression in handling commands, introduced in 0.2.0 +* Improved README + + +## 0.2.0 (2016-12-11) + +* BREAKING CHANGE: The observables returned by the `handleCollections` methods that process requests against the supplied in-mem-db collections are now "cold". +That means that requests aren't processed until something subscribes to the observable ... just like real-world `Http` calls. + + Previously, these request were "hot" meaning that the operation was performed immediately + (e.g., an in-memory collection was updated) and _then_ we returned an `Observable`. + That was a mistake! Fixing that mistake _might_ break your app which is why bumped the _minor_ version number from 1 to 2. + + We hope _very few apps are broken by this change_. Most will have subscribed anyway. + But any app that called an `http` method with fire-and-forget ... and didn't subscribe ... + expecting the database to be updated (for example) will discover that the operation did ***not*** happen. + +* BREAKING CHANGE: `createErrorResponse` now requires the `Request` object as its first parameter +so it can prepare a proper error message. +For example, a 404 `errorResponse.toString()` now shows the request URL. + +* Commands remain "hot" — processed immediately — as they should be. + +* The `HTTP GET` interceptor in example `hero-data.service` shows how to create your own "cold" observable. + +* While you can still specify the `inMemDbService['responseInterceptor']` to morph the response options, +the previously exported `responseInterceptor` function no longer exists as it served no useful purpose. +Added the `ResponseInterceptor` _type_ to remind you of the signature to implement. + +* Allows objects with `id===0` (issue #56) + +* The default `parseUrl` method is more flexible, thanks in part to the new `config.apiBase` property. +See the ReadMe to learn more. + +* Added `config.post204` and `config.put204` to control whether PUT and POST return the saved entity. +It is `true` by default which means they do not return the entity (`status=204`) — the same behavior as before. (issue #74) + +* `response.url` is set to `request.url` when this service itself creates the response. + +* A few new methods (e.g., `emitResponse`) to assist in HTTP method interceptors. + +
+ + +## 0.1.17 (2016-12-07) +* Update to Angular 2.2.0. + + +## 0.1.16 (2016-11-20) +* Swap `"lib": [ "es2015", "dom" ]` in `tsconfig.json` for @types/core-js` in `package.json` issue #288 + + +## 0.1.15 (2016-11-14) +* Update to Angular 2.2.0. + + +## 0.1.14 (2016-10-29) +* Add `responseInterceptor` for [issue #61](https://github.com/angular/in-memory-web-api/issues/61) + + +## 0.1.13 (2016-10-20) +* Update README for 0.1.11 breaking change: npm publish as `esm` and a `umd` bundle + + Going to `umd` changes your `systemjs.config` and the way you import the library. + + In `systemjs.config.js` you should change the mapping to: + ``` + 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js' + ``` + then delete from `packages`: + ``` + 'angular-in-memory-web-api': { + main: './index.js', + defaultExtension: 'js' + } + ``` + You must ES import the in-mem module (typically in `AppModule`) like this: + ``` + import { InMemoryWebApiModule } from 'angular-in-memory-web-api'; + ``` + +## 0.1.12 (2016-10-19) +* exclude travis.yml and rollup.config.js from npm package + + +## 0.1.11 (2016-10-19) +* BREAKING CHANGE: npm publish as `esm` and a `umd` bundle. +Does not change the API but does change the way you register and import the +in-mem module. Documented in later release, v.0.1.13 + + +## 0.1.10 (2016-10-19) +* Catch a `handleRequest` error and return as a failed server response. + + +## 0.1.9 (2016-10-18) +* Restore delay option, issue #53. + + +## 0.1.7 (2016-10-12) +* Angular 2.1.x support. + + +## 0.1.6 (2016-10-09) +* Do not add delay to observable if delay value === 0 (issue #47) +* Can override `parseUrl` method in your db service class (issue #46, #35) +* README.md explains `parseUrl` override. +* Exports functions helpful for custom HTTP Method Interceptors + * `createErrorResponse` + * `createObservableResponse` + * `setStatusText` +* Added `examples/hero-data.service.ts` to show overrides (issue #44) + + +## 0.1.5 (2016-10-03) +* project.json license changed again to match angular.io package.json + + +## 0.1.4 (2016-10-03) +* project.json license is "MIT" + + +## 0.1.3 (2016-09-29) +* Fix typos + + +## 0.1.2 (2016-09-29) +* AoT support from Tor PR #36 +* Update npm packages +* `parseId` fix from PR #33 + + +## 0.1.1 (2016-09-26) +* Exclude src folder and its TS files from npm package + + +## 0.1.0 (2016-09-25) +* Renamed package to "angular-in-memory-web-api" +* Added "passThruUnknownUrl" options +* Simplified `forRoot` and made it acceptable to AoT +* Support case sensitive search (PR #16) + +# "angular2-in-memory-web-api" versions +The last npm package named "angular2-in-memory-web-api" was v.0.0.21 + + +## 0.0.21 (2016-09-25) +* Add source maps (PR #14) + + +## 0.0.20 (2016-09-15) +* Angular 2.0.0 +* Typescript 2.0.2 + + +## 0.0.19 (2016-09-13) +* RC7 + + +## 0.0.18 (2016-08-31) +* RC6 (doesn't work with older versions) + + +## 0.0.17 (2016-08-19) +* fix `forRoot` type constraint +* clarify `forRoot` param + + +## 0.0.16 (2016-08-19) +* No longer exports `HttpModule` +* Can specify configuration options in 2nd param of `forRoot` +* jsDocs for `forRoot` + + +## 0.0.15 (2016-08-09) +* RC5 +* Support for NgModules + + +## 0.0.14 (2016-06-30) +* RC4 + + +## 0.0.13 (2016-06-21) +* RC3 + + +## 0.0.12 (2016-06-15) +* RC2 + + +## 0.0.11 (2016-05-27) +* add RegExp query support +* find-by-id is sensitive to string ids that look like numbers + + +## 0.0.10 (2016-05-21) +* added "main:index.js" to package.json +* updated to typings v.1.0.4 (a breaking release) +* dependencies -> peerDependencies|devDependencies +* no es6-shim dependency. +* use core-js as devDependency. + + +## 0.0.9 (2016-05-19) +* renamed the barrel core.js -> index.js + + +## 0.0.8 (2016-05-19) +* systemjs -> commonjs +* replace es6-shim typings w/ core-js typings + + +## 0.0.7 (2016-05-03) +* RC1 +* update to 2.0.0-rc.1 + + +## 0.0.6 (2016-05-03) +* RC0 +* update to 2.0.0-rc.0 + + +## 0.0.5 (2016-05-01) +* PROVISIONAL - refers to @angular packages +* update to 0.0.0-5 + + +## 0.0.4 (2016-04-30) +* PROVISIONAL - refers to @angular packages +* update to 0.0.0-3 +* rxjs: "5.0.0-beta.6" + + +## 0.0.3 (2016-04-29) +* PROVISIONAL - refers to @angular packages +* update to 0.0.0-2 + + +## 0.0.2 (2016-04-27) +* PROVISIONAL - refers to @angular packages + + +## 0.0.1 (2016-04-27) +* DO NOT USE. Not adapted to new package system. +* Initial cut for Angular 2 repackaged + * target forthcoming Angular 2 RC diff --git a/packages/misc/angular-in-memory-web-api/index.ts b/packages/misc/angular-in-memory-web-api/index.ts new file mode 100644 index 0000000000..7ef6571cd5 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/index.ts @@ -0,0 +1,14 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +// This file is not used to build this module. It is only used during editing +// by the TypeScript language service and during build for verification. `ngc` +// replaces this file with production index.ts when it rewrites private symbol +// names. + +export * from './public_api'; diff --git a/packages/misc/angular-in-memory-web-api/package.json b/packages/misc/angular-in-memory-web-api/package.json new file mode 100644 index 0000000000..b0f4c6d5d1 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/package.json @@ -0,0 +1,22 @@ +{ + "name": "angular-in-memory-web-api", + "version": "0.11.0", + "description": "An in-memory web api for Angular demos and tests", + "author": "angular", + "license": "MIT", + "peerDependencies": { + "@angular/core": "^8.0.0", + "@angular/common": "^8.0.0", + "rxjs": "^6.5.3", + "tslib": "^1.10.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/angular/angular.git", + "directory": "packages/misc/angular-in-memory-web-api" + }, + "sideEffects": false, + "publishConfig": { + "registry":"https://wombat-dressing-room.appspot.com" + } +} diff --git a/packages/misc/angular-in-memory-web-api/public_api.ts b/packages/misc/angular-in-memory-web-api/public_api.ts new file mode 100644 index 0000000000..65eb405d02 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/public_api.ts @@ -0,0 +1,11 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +export * from './src/in-memory-web-api'; + +// This file only reexports content of the `src` folder. Keep it that way. diff --git a/packages/misc/angular-in-memory-web-api/src/backend-service.ts b/packages/misc/angular-in-memory-web-api/src/backend-service.ts new file mode 100644 index 0000000000..71a62384ea --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/src/backend-service.ts @@ -0,0 +1,663 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {HttpHeaders} from '@angular/common/http'; +import {BehaviorSubject, from, Observable, Observer, of} from 'rxjs'; +import {concatMap, first} from 'rxjs/operators'; + +import {delayResponse} from './delay-response'; +import {getStatusText, isSuccess, STATUS} from './http-status-codes'; +import {InMemoryBackendConfig, InMemoryBackendConfigArgs, InMemoryDbService, ParsedRequestUrl, parseUri, PassThruBackend, removeTrailingSlash, RequestCore, RequestInfo, RequestInfoUtilities, ResponseOptions, UriInfo} from './interfaces'; + +/** + * 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 + */ +export abstract class BackendService { + protected config: InMemoryBackendConfigArgs = new InMemoryBackendConfig(); + protected db: {[key: string]: any} = {}; + protected dbReadySubject: BehaviorSubject|undefined; + private passThruBackend: PassThruBackend|undefined; + protected requestInfoUtils = this.getRequestInfoUtils(); + + constructor(protected inMemDbService: InMemoryDbService, config: InMemoryBackendConfigArgs = {}) { + const loc = this.getLocation('/'); + this.config.host = loc.host; // default to app web server host + this.config.rootPath = loc.path; // default to path when app is served (e.g.'/') + Object.assign(this.config, config); + } + + protected get dbReady(): Observable { + if (!this.dbReadySubject) { + // first time the service is called. + this.dbReadySubject = new BehaviorSubject(false); + this.resetDb(); + } + return this.dbReadySubject.asObservable().pipe(first((r: boolean) => r)); + } + + /** + * 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"). + */ + protected handleRequest(req: RequestCore): Observable { + // handle the request when there is an in-memory database + return this.dbReady.pipe(concatMap(() => this.handleRequest_(req))); + } + + protected handleRequest_(req: RequestCore): Observable { + const url = req.urlWithParams ? req.urlWithParams : req.url; + + // Try override parser + // If no override parser or it returns nothing, use default parser + const parser = this.bind('parseRequestUrl'); + const parsed: ParsedRequestUrl = + (parser && parser(url, this.requestInfoUtils)) || this.parseRequestUrl(url); + + const collectionName = parsed.collectionName; + const collection = this.db[collectionName]; + + const reqInfo: RequestInfo = { + req: req, + apiBase: parsed.apiBase, + collection: collection, + collectionName: collectionName, + headers: this.createHeaders({'Content-Type': 'application/json'}), + id: this.parseId(collection, collectionName, parsed.id), + method: this.getRequestMethod(req), + query: parsed.query, + resourceUrl: parsed.resourceUrl, + url: url, + utils: this.requestInfoUtils + }; + + let resOptions: ResponseOptions; + + if (/commands\/?$/i.test(reqInfo.apiBase)) { + return this.commands(reqInfo); + } + + const methodInterceptor = this.bind(reqInfo.method); + if (methodInterceptor) { + // InMemoryDbService intercepts this HTTP method. + // if interceptor produced a response, return it. + // else InMemoryDbService chose not to intercept; continue processing. + const interceptorResponse = methodInterceptor(reqInfo); + if (interceptorResponse) { + return interceptorResponse; + } + } + + if (this.db[collectionName]) { + // request is for a known collection of the InMemoryDbService + return this.createResponse$(() => this.collectionHandler(reqInfo)); + } + + if (this.config.passThruUnknownUrl) { + // unknown collection; pass request thru to a "real" backend. + return this.getPassThruBackend().handle(req); + } + + // 404 - can't handle this request + resOptions = this.createErrorResponseOptions( + url, STATUS.NOT_FOUND, `Collection '${collectionName}' not found`); + return this.createResponse$(() => resOptions); + } + + /** + * Add configured delay to response observable unless delay === 0 + */ + protected addDelay(response: Observable): Observable { + const d = this.config.delay; + return d === 0 ? response : delayResponse(response, d || 500); + } + + /** + * 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 + */ + protected applyQuery(collection: any[], query: Map): any[] { + // extract filtering conditions - {propertyName, RegExps) - from query/search parameters + const conditions: {name: string, rx: RegExp}[] = []; + const caseSensitive = this.config.caseSensitiveSearch ? undefined : 'i'; + query.forEach((value: string[], name: string) => { + value.forEach(v => conditions.push({name, rx: new RegExp(decodeURI(v), caseSensitive)})); + }); + + const len = conditions.length; + if (!len) { + return collection; + } + + // AND the RegExp conditions + return collection.filter(row => { + let ok = true; + let i = len; + while (ok && i) { + i -= 1; + const cond = conditions[i]; + ok = cond.rx.test(row[cond.name]); + } + return ok; + }); + } + + /** + * Get a method from the `InMemoryDbService` (if it exists), bound to that service + */ + protected bind(methodName: string) { + const fn = (this.inMemDbService as any)[methodName]; + return fn ? fn.bind(this.inMemDbService) as T : undefined; + } + + protected bodify(data: any) { + return this.config.dataEncapsulation ? {data} : data; + } + + protected clone(data: any) { + return JSON.parse(JSON.stringify(data)); + } + + protected collectionHandler(reqInfo: RequestInfo): ResponseOptions { + // const req = reqInfo.req; + let resOptions: ResponseOptions; + switch (reqInfo.method) { + case 'get': + resOptions = this.get(reqInfo); + break; + case 'post': + resOptions = this.post(reqInfo); + break; + case 'put': + resOptions = this.put(reqInfo); + break; + case 'delete': + resOptions = this.delete(reqInfo); + break; + default: + resOptions = this.createErrorResponseOptions( + reqInfo.url, STATUS.METHOD_NOT_ALLOWED, 'Method not allowed'); + break; + } + + // If `inMemDbService.responseInterceptor` exists, let it morph the response options + const interceptor = this.bind('responseInterceptor'); + return interceptor ? interceptor(resOptions, reqInfo) : resOptions; + } + + /** + * 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", + * the `collectionName` 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}'); + */ + protected commands(reqInfo: RequestInfo): Observable { + const command = reqInfo.collectionName.toLowerCase(); + const method = reqInfo.method; + + let resOptions: ResponseOptions = {url: reqInfo.url}; + + switch (command) { + case 'resetdb': + resOptions.status = STATUS.NO_CONTENT; + return this.resetDb(reqInfo).pipe( + concatMap(() => this.createResponse$(() => resOptions, false /* no latency delay */))); + + case 'config': + if (method === 'get') { + resOptions.status = STATUS.OK; + resOptions.body = this.clone(this.config); + + // any other HTTP method is assumed to be a config update + } else { + const body = this.getJsonBody(reqInfo.req); + Object.assign(this.config, body); + this.passThruBackend = undefined; // re-create when needed + + resOptions.status = STATUS.NO_CONTENT; + } + break; + + default: + resOptions = this.createErrorResponseOptions( + reqInfo.url, STATUS.INTERNAL_SERVER_ERROR, `Unknown command "${command}"`); + } + + return this.createResponse$(() => resOptions, false /* no latency delay */); + } + + protected createErrorResponseOptions(url: string, status: number, message: string): + ResponseOptions { + return { + body: {error: `${message}`}, + url: url, + headers: this.createHeaders({'Content-Type': 'application/json'}), + status: status + }; + } + + /** + * Create standard HTTP headers object from hash map of header strings + * @param headers + */ + protected abstract createHeaders(headers: {[index: string]: string}): HttpHeaders; + + /** + * create the function that passes unhandled requests through to the "real" backend. + */ + protected abstract createPassThruBackend(): PassThruBackend; + + /** + * return a search map from a location query/search string + */ + protected abstract createQueryMap(search: string): Map; + + /** + * Create a cold response Observable from a factory for ResponseOptions + * @param resOptionsFactory - creates ResponseOptions when observable is subscribed + * @param withDelay - if true (default), add simulated latency delay from configuration + */ + protected createResponse$(resOptionsFactory: () => ResponseOptions, withDelay = true): + Observable { + const resOptions$ = this.createResponseOptions$(resOptionsFactory); + let resp$ = this.createResponse$fromResponseOptions$(resOptions$); + return withDelay ? this.addDelay(resp$) : resp$; + } + + /** + * Create a Response observable from ResponseOptions observable. + */ + protected abstract createResponse$fromResponseOptions$(resOptions$: Observable): + Observable; + + /** + * Create a cold Observable of ResponseOptions. + * @param resOptionsFactory - creates ResponseOptions when observable is subscribed + */ + protected createResponseOptions$(resOptionsFactory: () => ResponseOptions): + Observable { + return new Observable((responseObserver: Observer) => { + let resOptions: ResponseOptions; + try { + resOptions = resOptionsFactory(); + } catch (error) { + const err = error.message || error; + resOptions = this.createErrorResponseOptions('', STATUS.INTERNAL_SERVER_ERROR, `${err}`); + } + + const status = resOptions.status; + try { + resOptions.statusText = status != null ? getStatusText(status) : undefined; + } catch (e) { /* ignore failure */ + } + if (status != null && isSuccess(status)) { + responseObserver.next(resOptions); + responseObserver.complete(); + } else { + responseObserver.error(resOptions); + } + return () => {}; // unsubscribe function + }); + } + + protected delete({collection, collectionName, headers, id, url}: RequestInfo): ResponseOptions { + if (id == null) { + return this.createErrorResponseOptions( + url, STATUS.NOT_FOUND, `Missing "${collectionName}" id`); + } + const exists = this.removeById(collection, id); + return { + headers: headers, + status: (exists || !this.config.delete404) ? STATUS.NO_CONTENT : STATUS.NOT_FOUND + }; + } + + /** + * Find first instance of item in collection by `item.id` + * @param collection + * @param id + */ + protected findById(collection: T[], id: any): T|undefined { + return collection.find((item: T) => item.id === id); + } + + /** + * Generate the next available id for item in this collection + * Use method from `inMemDbService` if it exists and returns a value, + * else delegates to `genIdDefault`. + * @param collection - collection of items with `id` key property + */ + protected genId(collection: T[], collectionName: string): any { + const genId = this.bind('genId'); + if (genId) { + const id = genId(collection, collectionName); + if (id != null) { + return id; + } + } + return this.genIdDefault(collection, collectionName); + } + + /** + * Default generator of the next available id for item in this collection + * This default implementation works only for numeric ids. + * @param collection - collection of items with `id` key property + * @param collectionName - name of the collection + */ + protected genIdDefault(collection: T[], collectionName: string): any { + if (!this.isCollectionIdNumeric(collection, collectionName)) { + throw new Error(`Collection '${ + collectionName}' id type is non-numeric or unknown. Can only generate numeric ids.`); + } + + let maxId = 0; + collection.reduce((prev: any, item: any) => { + maxId = Math.max(maxId, typeof item.id === 'number' ? item.id : maxId); + }, undefined); + return maxId + 1; + } + + protected get({collection, collectionName, headers, id, query, url}: RequestInfo): + ResponseOptions { + let data = collection; + + if (id != null && id !== '') { + data = this.findById(collection, id); + } else if (query) { + data = this.applyQuery(collection, query); + } + + if (!data) { + return this.createErrorResponseOptions( + url, STATUS.NOT_FOUND, `'${collectionName}' with id='${id}' not found`); + } + return {body: this.bodify(this.clone(data)), headers: headers, status: STATUS.OK}; + } + + /** Get JSON body from the request object */ + protected abstract getJsonBody(req: any): any; + + /** + * Get location info from a url, even on server where `document` is not defined + */ + protected getLocation(url: string): UriInfo { + if (!url.startsWith('http')) { + // get the document iff running in browser + const doc = (typeof document === 'undefined') ? undefined : document; + // add host info to url before parsing. Use a fake host when not in browser. + const base = doc ? doc.location.protocol + '//' + doc.location.host : 'http://fake'; + url = url.startsWith('/') ? base + url : base + '/' + url; + } + return parseUri(url); + } + + /** + * get or create the function that passes unhandled requests + * through to the "real" backend. + */ + protected getPassThruBackend(): PassThruBackend { + return this.passThruBackend ? this.passThruBackend : + this.passThruBackend = this.createPassThruBackend(); + } + + /** + * Get utility methods from this service instance. + * Useful within an HTTP method override + */ + protected getRequestInfoUtils(): RequestInfoUtilities { + return { + createResponse$: this.createResponse$.bind(this), + findById: this.findById.bind(this), + isCollectionIdNumeric: this.isCollectionIdNumeric.bind(this), + getConfig: () => this.config, + getDb: () => this.db, + getJsonBody: this.getJsonBody.bind(this), + getLocation: this.getLocation.bind(this), + getPassThruBackend: this.getPassThruBackend.bind(this), + parseRequestUrl: this.parseRequestUrl.bind(this), + }; + } + + /** + * return canonical HTTP method name (lowercase) from the request object + * e.g. (req.method || 'get').toLowerCase(); + * @param req - request object from the http call + * + */ + protected abstract getRequestMethod(req: any): string; + + protected indexOf(collection: any[], id: number) { + return collection.findIndex((item: any) => item.id === id); + } + + /** Parse the id as a number. Return original value if not a number. */ + protected parseId(collection: any[], collectionName: string, id: string): any { + if (!this.isCollectionIdNumeric(collection, collectionName)) { + // Can't confirm that `id` is a numeric type; don't parse as a number + // or else `'42'` -> `42` and _get by id_ fails. + return id; + } + const idNum = parseFloat(id); + return isNaN(idNum) ? id : idNum; + } + + /** + * 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 + * */ + protected isCollectionIdNumeric(collection: T[], collectionName: string): + boolean { + // collectionName not used now but override might maintain collection type information + // so that it could know the type of the `id` even when the collection is empty. + return !!(collection && collection[0]) && typeof collection[0].id === 'number'; + } + + /** + * Parses the request URL into a `ParsedRequestUrl` object. + * Parsing depends upon certain values of `config`: `apiBase`, `host`, and `urlRoot`. + * + * Configuring the `apiBase` yields the most interesting changes to `parseRequestUrl` 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'] + */ + protected parseRequestUrl(url: string): ParsedRequestUrl { + try { + const loc = this.getLocation(url); + let drop = (this.config.rootPath || '').length; + let urlRoot = ''; + if (loc.host !== this.config.host) { + // url for a server on a different host! + // assume it's collection is actually here too. + drop = 1; // the leading slash + urlRoot = loc.protocol + '//' + loc.host + '/'; + } + const path = loc.path.substring(drop); + const pathSegments = path.split('/'); + let segmentIndex = 0; + + // apiBase: the front part of the path devoted to getting to the api route + // Assumes first path segment if no config.apiBase + // else ignores as many path segments as are in config.apiBase + // Does NOT care what the api base chars actually are. + let apiBase: string; + if (this.config.apiBase == null) { + apiBase = pathSegments[segmentIndex++]; + } else { + apiBase = removeTrailingSlash(this.config.apiBase.trim()); + if (apiBase) { + segmentIndex = apiBase.split('/').length; + } else { + segmentIndex = 0; // no api base at all; unwise but allowed. + } + } + apiBase += '/'; + + let collectionName = pathSegments[segmentIndex++]; + // ignore anything after a '.' (e.g.,the "json" in "customers.json") + collectionName = collectionName && collectionName.split('.')[0]; + + const id = pathSegments[segmentIndex++]; + const query = this.createQueryMap(loc.query); + const resourceUrl = urlRoot + apiBase + collectionName + '/'; + return {apiBase, collectionName, id, query, resourceUrl}; + } catch (err) { + const msg = `unable to parse url '${url}'; original error: ${err.message}`; + throw new Error(msg); + } + } + + // Create entity + // Can update an existing entity too if post409 is false. + protected post({collection, collectionName, headers, id, req, resourceUrl, url}: RequestInfo): + ResponseOptions { + const item = this.clone(this.getJsonBody(req)); + + if (item.id == null) { + try { + item.id = id || this.genId(collection, collectionName); + } catch (err) { + const emsg: string = err.message || ''; + if (/id type is non-numeric/.test(emsg)) { + return this.createErrorResponseOptions(url, STATUS.UNPROCESSABLE_ENTRY, emsg); + } else { + return this.createErrorResponseOptions( + url, STATUS.INTERNAL_SERVER_ERROR, + `Failed to generate new id for '${collectionName}'`); + } + } + } + + if (id && id !== item.id) { + return this.createErrorResponseOptions( + url, STATUS.BAD_REQUEST, `Request id does not match item.id`); + } else { + id = item.id; + } + const existingIx = this.indexOf(collection, id); + const body = this.bodify(item); + + if (existingIx === -1) { + collection.push(item); + headers.set('Location', resourceUrl + '/' + id); + return {headers, body, status: STATUS.CREATED}; + } else if (this.config.post409) { + return this.createErrorResponseOptions( + url, STATUS.CONFLICT, + `'${collectionName}' item with id='${ + id} exists and may not be updated with POST; use PUT instead.`); + } else { + collection[existingIx] = item; + return this.config.post204 ? {headers, status: STATUS.NO_CONTENT} : // successful; no content + {headers, body, status: STATUS.OK}; // successful; return entity + } + } + + // Update existing entity + // Can create an entity too if put404 is false. + protected put({collection, collectionName, headers, id, req, url}: RequestInfo): ResponseOptions { + const item = this.clone(this.getJsonBody(req)); + if (item.id == null) { + return this.createErrorResponseOptions( + url, STATUS.NOT_FOUND, `Missing '${collectionName}' id`); + } + if (id && id !== item.id) { + return this.createErrorResponseOptions( + url, STATUS.BAD_REQUEST, `Request for '${collectionName}' id does not match item.id`); + } else { + id = item.id; + } + const existingIx = this.indexOf(collection, id); + const body = this.bodify(item); + + if (existingIx > -1) { + collection[existingIx] = item; + return this.config.put204 ? {headers, status: STATUS.NO_CONTENT} : // successful; no content + {headers, body, status: STATUS.OK}; // successful; return entity + } else if (this.config.put404) { + // item to update not found; use POST to create new item for this id. + return this.createErrorResponseOptions( + url, STATUS.NOT_FOUND, + `'${collectionName}' item with id='${ + id} not found and may not be created with PUT; use POST instead.`); + } else { + // create new item for id not found + collection.push(item); + return {headers, body, status: STATUS.CREATED}; + } + } + + protected removeById(collection: any[], id: number) { + const ix = this.indexOf(collection, id); + if (ix > -1) { + collection.splice(ix, 1); + return true; + } + return false; + } + + /** + * Tell your in-mem "database" to reset. + * returns Observable of the database because resetting it could be async + */ + protected resetDb(reqInfo?: RequestInfo): Observable { + this.dbReadySubject && this.dbReadySubject.next(false); + const db = this.inMemDbService.createDb(reqInfo); + const db$ = db instanceof Observable ? + db : + typeof (db as any).then === 'function' ? from(db as Promise) : of(db); + db$.pipe(first()).subscribe((d: {}) => { + this.db = d; + this.dbReadySubject && this.dbReadySubject.next(true); + }); + return this.dbReady; + } +} diff --git a/packages/misc/angular-in-memory-web-api/src/delay-response.ts b/packages/misc/angular-in-memory-web-api/src/delay-response.ts new file mode 100644 index 0000000000..0af153bfe9 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/src/delay-response.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Observable} from 'rxjs'; + +// Replaces use of RxJS delay. See v0.5.4. +/** adds specified delay (in ms) to both next and error channels of the response observable */ +export function delayResponse(response$: Observable, delayMs: number): Observable { + return new Observable(observer => { + let completePending = false; + let nextPending = false; + const subscription = response$.subscribe( + value => { + nextPending = true; + setTimeout(() => { + observer.next(value); + if (completePending) { + observer.complete(); + } + }, delayMs); + }, + error => setTimeout(() => observer.error(error), delayMs), + () => { + completePending = true; + if (!nextPending) { + observer.complete(); + } + }); + return () => { + return subscription.unsubscribe(); + }; + }); +} diff --git a/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts b/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts new file mode 100644 index 0000000000..fb71f1e495 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {HttpBackend, HttpEvent, HttpHeaders, HttpParams, HttpRequest, HttpResponse, HttpXhrBackend, XhrFactory} from '@angular/common/http'; +import {Inject, Injectable, Optional} from '@angular/core'; +import {Observable} from 'rxjs'; +import {map} from 'rxjs/operators'; + +import {BackendService} from './backend-service'; +import {STATUS} from './http-status-codes'; +import {InMemoryBackendConfig, InMemoryBackendConfigArgs, InMemoryDbService, ResponseOptions} from './interfaces'; + +/** + * For Angular `HttpClient` simulate the behavior of a RESTy web api + * backed by the simple in-memory data store provided by the injected `InMemoryDbService`. + * Conforms mostly to behavior described here: + * http://www.restapitutorial.com/lessons/httpmethods.html + * + * ### Usage + * + * Create an in-memory data store class that implements `InMemoryDbService`. + * Call `config` static method with this service class and optional configuration object: + * ``` + * // other imports + * import { 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 { ... } + * ``` + */ +@Injectable() +export class HttpClientBackendService extends BackendService implements HttpBackend { + constructor( + inMemDbService: InMemoryDbService, + @Inject(InMemoryBackendConfig) @Optional() config: InMemoryBackendConfigArgs, + private xhrFactory: XhrFactory) { + super(inMemDbService, config); + } + + handle(req: HttpRequest): Observable> { + try { + return this.handleRequest(req); + + } catch (error) { + const err = error.message || error; + const resOptions = + this.createErrorResponseOptions(req.url, STATUS.INTERNAL_SERVER_ERROR, `${err}`); + return this.createResponse$(() => resOptions); + } + } + + protected getJsonBody(req: HttpRequest): any { + return req.body; + } + + protected getRequestMethod(req: HttpRequest): string { + return (req.method || 'get').toLowerCase(); + } + + protected createHeaders(headers: {[index: string]: string;}): HttpHeaders { + return new HttpHeaders(headers); + } + + protected createQueryMap(search: string): Map { + const map = new Map(); + if (search) { + const params = new HttpParams({fromString: search}); + params.keys().forEach(p => map.set(p, params.getAll(p) || [])); + } + return map; + } + + protected createResponse$fromResponseOptions$(resOptions$: Observable): + Observable> { + return resOptions$.pipe(map(opts => new HttpResponse(opts))); + } + + protected createPassThruBackend() { + try { + return new HttpXhrBackend(this.xhrFactory); + } catch (ex) { + ex.message = 'Cannot create passThru404 backend; ' + (ex.message || ''); + throw ex; + } + } +} diff --git a/packages/misc/angular-in-memory-web-api/src/http-client-in-memory-web-api-module.ts b/packages/misc/angular-in-memory-web-api/src/http-client-in-memory-web-api-module.ts new file mode 100644 index 0000000000..ccf1a7ca7f --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/src/http-client-in-memory-web-api-module.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {HttpBackend, XhrFactory} from '@angular/common/http'; +import {ModuleWithProviders, NgModule, Type} from '@angular/core'; + +import {HttpClientBackendService} from './http-client-backend-service'; +import {InMemoryBackendConfig, InMemoryBackendConfigArgs, InMemoryDbService} from './interfaces'; + +// Internal - Creates the in-mem backend for the HttpClient module +// AoT requires factory to be exported +export function httpClientInMemBackendServiceFactory( + dbService: InMemoryDbService, options: InMemoryBackendConfig, + xhrFactory: XhrFactory): HttpBackend { + return new HttpClientBackendService(dbService, options, xhrFactory) as HttpBackend; +} + +@NgModule() +export class HttpClientInMemoryWebApiModule { + /** + * Redirect the Angular `HttpClient` XHR calls + * to in-memory data store that implements `InMemoryDbService`. + * 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 + * + * @param dbCreator - Class that creates seed data for in-memory database. Must implement + * InMemoryDbService. + * @param [options] + * + * @example + * HttpInMemoryWebApiModule.forRoot(dbCreator); + * HttpInMemoryWebApiModule.forRoot(dbCreator, {useValue: {delay:600}}); + */ + static forRoot(dbCreator: Type, options?: InMemoryBackendConfigArgs): + ModuleWithProviders { + return { + ngModule: HttpClientInMemoryWebApiModule, + providers: [ + {provide: InMemoryDbService, useClass: dbCreator}, + {provide: InMemoryBackendConfig, useValue: options}, { + provide: HttpBackend, + useFactory: httpClientInMemBackendServiceFactory, + deps: [InMemoryDbService, InMemoryBackendConfig, XhrFactory] + } + ] + }; + } + /** + * + * 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. + */ + static forFeature(dbCreator: Type, options?: InMemoryBackendConfigArgs): + ModuleWithProviders { + return HttpClientInMemoryWebApiModule.forRoot(dbCreator, options); + } +} diff --git a/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts b/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts new file mode 100644 index 0000000000..eb63d24e23 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts @@ -0,0 +1,523 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +export const STATUS = { + CONTINUE: 100, + SWITCHING_PROTOCOLS: 101, + OK: 200, + CREATED: 201, + ACCEPTED: 202, + NON_AUTHORITATIVE_INFORMATION: 203, + NO_CONTENT: 204, + RESET_CONTENT: 205, + PARTIAL_CONTENT: 206, + MULTIPLE_CHOICES: 300, + MOVED_PERMANTENTLY: 301, + FOUND: 302, + SEE_OTHER: 303, + NOT_MODIFIED: 304, + USE_PROXY: 305, + TEMPORARY_REDIRECT: 307, + BAD_REQUEST: 400, + UNAUTHORIZED: 401, + PAYMENT_REQUIRED: 402, + FORBIDDEN: 403, + NOT_FOUND: 404, + METHOD_NOT_ALLOWED: 405, + NOT_ACCEPTABLE: 406, + PROXY_AUTHENTICATION_REQUIRED: 407, + REQUEST_TIMEOUT: 408, + CONFLICT: 409, + GONE: 410, + LENGTH_REQUIRED: 411, + PRECONDITION_FAILED: 412, + PAYLOAD_TO_LARGE: 413, + URI_TOO_LONG: 414, + UNSUPPORTED_MEDIA_TYPE: 415, + RANGE_NOT_SATISFIABLE: 416, + EXPECTATION_FAILED: 417, + IM_A_TEAPOT: 418, + UPGRADE_REQUIRED: 426, + INTERNAL_SERVER_ERROR: 500, + NOT_IMPLEMENTED: 501, + BAD_GATEWAY: 502, + SERVICE_UNAVAILABLE: 503, + GATEWAY_TIMEOUT: 504, + HTTP_VERSION_NOT_SUPPORTED: 505, + PROCESSING: 102, + MULTI_STATUS: 207, + IM_USED: 226, + PERMANENT_REDIRECT: 308, + UNPROCESSABLE_ENTRY: 422, + LOCKED: 423, + FAILED_DEPENDENCY: 424, + PRECONDITION_REQUIRED: 428, + TOO_MANY_REQUESTS: 429, + REQUEST_HEADER_FIELDS_TOO_LARGE: 431, + UNAVAILABLE_FOR_LEGAL_REASONS: 451, + VARIANT_ALSO_NEGOTIATES: 506, + INSUFFICIENT_STORAGE: 507, + NETWORK_AUTHENTICATION_REQUIRED: 511 +}; + +export const STATUS_CODE_INFO: { + [key: string]: + {code: number; text: string; description: string; spec_title: string; spec_href: string;} +} = { + '100': { + 'code': 100, + 'text': 'Continue', + 'description': + '\"The initial part of a request has been received and has not yet been rejected by the server.\"', + 'spec_title': 'RFC7231#6.2.1', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.2.1' + }, + '101': { + 'code': 101, + 'text': 'Switching Protocols', + 'description': + '\"The server understands and is willing to comply with the client\'s request, via the Upgrade header field, for a change in the application protocol being used on this connection.\"', + 'spec_title': 'RFC7231#6.2.2', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.2.2' + }, + '200': { + 'code': 200, + 'text': 'OK', + 'description': '\"The request has succeeded.\"', + 'spec_title': 'RFC7231#6.3.1', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.3.1' + }, + '201': { + 'code': 201, + 'text': 'Created', + 'description': + '\"The request has been fulfilled and has resulted in one or more new resources being created.\"', + 'spec_title': 'RFC7231#6.3.2', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.3.2' + }, + '202': { + 'code': 202, + 'text': 'Accepted', + 'description': + '\"The request has been accepted for processing, but the processing has not been completed.\"', + 'spec_title': 'RFC7231#6.3.3', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.3.3' + }, + '203': { + 'code': 203, + 'text': 'Non-Authoritative Information', + 'description': + '\"The request was successful but the enclosed payload has been modified from that of the origin server\'s 200 (OK) response by a transforming proxy.\"', + 'spec_title': 'RFC7231#6.3.4', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.3.4' + }, + '204': { + 'code': 204, + 'text': 'No Content', + 'description': + '\"The server has successfully fulfilled the request and that there is no additional content to send in the response payload body.\"', + 'spec_title': 'RFC7231#6.3.5', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.3.5' + }, + '205': { + 'code': 205, + 'text': 'Reset Content', + 'description': + '\"The server has fulfilled the request and desires that the user agent reset the \"document view\", which caused the request to be sent, to its original state as received from the origin server.\"', + 'spec_title': 'RFC7231#6.3.6', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.3.6' + }, + '206': { + 'code': 206, + 'text': 'Partial Content', + 'description': + '\"The server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests\'s Range header field.\"', + 'spec_title': 'RFC7233#4.1', + 'spec_href': 'http://tools.ietf.org/html/rfc7233#section-4.1' + }, + '300': { + 'code': 300, + 'text': 'Multiple Choices', + 'description': + '\"The target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers.\"', + 'spec_title': 'RFC7231#6.4.1', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.4.1' + }, + '301': { + 'code': 301, + 'text': 'Moved Permanently', + 'description': + '\"The target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.\"', + 'spec_title': 'RFC7231#6.4.2', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.4.2' + }, + '302': { + 'code': 302, + 'text': 'Found', + 'description': '\"The target resource resides temporarily under a different URI.\"', + 'spec_title': 'RFC7231#6.4.3', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.4.3' + }, + '303': { + 'code': 303, + 'text': 'See Other', + 'description': + '\"The server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request.\"', + 'spec_title': 'RFC7231#6.4.4', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.4.4' + }, + '304': { + 'code': 304, + 'text': 'Not Modified', + 'description': + '\"A conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false.\"', + 'spec_title': 'RFC7232#4.1', + 'spec_href': 'http://tools.ietf.org/html/rfc7232#section-4.1' + }, + '305': { + 'code': 305, + 'text': 'Use Proxy', + 'description': '*deprecated*', + 'spec_title': 'RFC7231#6.4.5', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.4.5' + }, + '307': { + 'code': 307, + 'text': 'Temporary Redirect', + 'description': + '\"The target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI.\"', + 'spec_title': 'RFC7231#6.4.7', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.4.7' + }, + '400': { + 'code': 400, + 'text': 'Bad Request', + 'description': + '\"The server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.\"', + 'spec_title': 'RFC7231#6.5.1', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.1' + }, + '401': { + 'code': 401, + 'text': 'Unauthorized', + 'description': + '\"The request has not been applied because it lacks valid authentication credentials for the target resource.\"', + 'spec_title': 'RFC7235#6.3.1', + 'spec_href': 'http://tools.ietf.org/html/rfc7235#section-3.1' + }, + '402': { + 'code': 402, + 'text': 'Payment Required', + 'description': '*reserved*', + 'spec_title': 'RFC7231#6.5.2', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.2' + }, + '403': { + 'code': 403, + 'text': 'Forbidden', + 'description': '\"The server understood the request but refuses to authorize it.\"', + 'spec_title': 'RFC7231#6.5.3', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.3' + }, + '404': { + 'code': 404, + 'text': 'Not Found', + 'description': + '\"The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.\"', + 'spec_title': 'RFC7231#6.5.4', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.4' + }, + '405': { + 'code': 405, + 'text': 'Method Not Allowed', + 'description': + '\"The method specified in the request-line is known by the origin server but not supported by the target resource.\"', + 'spec_title': 'RFC7231#6.5.5', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.5' + }, + '406': { + 'code': 406, + 'text': 'Not Acceptable', + 'description': + '\"The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.\"', + 'spec_title': 'RFC7231#6.5.6', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.6' + }, + '407': { + 'code': 407, + 'text': 'Proxy Authentication Required', + 'description': '\"The client needs to authenticate itself in order to use a proxy.\"', + 'spec_title': 'RFC7231#6.3.2', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.3.2' + }, + '408': { + 'code': 408, + 'text': 'Request Timeout', + 'description': + '\"The server did not receive a complete request message within the time that it was prepared to wait.\"', + 'spec_title': 'RFC7231#6.5.7', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.7' + }, + '409': { + 'code': 409, + 'text': 'Conflict', + 'description': + '\"The request could not be completed due to a conflict with the current state of the resource.\"', + 'spec_title': 'RFC7231#6.5.8', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.8' + }, + '410': { + 'code': 410, + 'text': 'Gone', + 'description': + '\"Access to the target resource is no longer available at the origin server and that this condition is likely to be permanent.\"', + 'spec_title': 'RFC7231#6.5.9', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.9' + }, + '411': { + 'code': 411, + 'text': 'Length Required', + 'description': '\"The server refuses to accept the request without a defined Content-Length.\"', + 'spec_title': 'RFC7231#6.5.10', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.10' + }, + '412': { + 'code': 412, + 'text': 'Precondition Failed', + 'description': + '\"One or more preconditions given in the request header fields evaluated to false when tested on the server.\"', + 'spec_title': 'RFC7232#4.2', + 'spec_href': 'http://tools.ietf.org/html/rfc7232#section-4.2' + }, + '413': { + 'code': 413, + 'text': 'Payload Too Large', + 'description': + '\"The server is refusing to process a request because the request payload is larger than the server is willing or able to process.\"', + 'spec_title': 'RFC7231#6.5.11', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.11' + }, + '414': { + 'code': 414, + 'text': 'URI Too Long', + 'description': + '\"The server is refusing to service the request because the request-target is longer than the server is willing to interpret.\"', + 'spec_title': 'RFC7231#6.5.12', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.12' + }, + '415': { + 'code': 415, + 'text': 'Unsupported Media Type', + 'description': + '\"The origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method.\"', + 'spec_title': 'RFC7231#6.5.13', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.13' + }, + '416': { + 'code': 416, + 'text': 'Range Not Satisfiable', + 'description': + '\"None of the ranges in the request\'s Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges.\"', + 'spec_title': 'RFC7233#4.4', + 'spec_href': 'http://tools.ietf.org/html/rfc7233#section-4.4' + }, + '417': { + 'code': 417, + 'text': 'Expectation Failed', + 'description': + '\"The expectation given in the request\'s Expect header field could not be met by at least one of the inbound servers.\"', + 'spec_title': 'RFC7231#6.5.14', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.14' + }, + '418': { + 'code': 418, + 'text': 'I\'m a teapot', + 'description': '\"1988 April Fools Joke. Returned by tea pots requested to brew coffee.\"', + 'spec_title': 'RFC 2324', + 'spec_href': 'https://tools.ietf.org/html/rfc2324' + }, + '426': { + 'code': 426, + 'text': 'Upgrade Required', + 'description': + '\"The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.\"', + 'spec_title': 'RFC7231#6.5.15', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.5.15' + }, + '500': { + 'code': 500, + 'text': 'Internal Server Error', + 'description': + '\"The server encountered an unexpected condition that prevented it from fulfilling the request.\"', + 'spec_title': 'RFC7231#6.6.1', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.6.1' + }, + '501': { + 'code': 501, + 'text': 'Not Implemented', + 'description': + '\"The server does not support the functionality required to fulfill the request.\"', + 'spec_title': 'RFC7231#6.6.2', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.6.2' + }, + '502': { + 'code': 502, + 'text': 'Bad Gateway', + 'description': + '\"The server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.\"', + 'spec_title': 'RFC7231#6.6.3', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.6.3' + }, + '503': { + 'code': 503, + 'text': 'Service Unavailable', + 'description': + '\"The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.\"', + 'spec_title': 'RFC7231#6.6.4', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.6.4' + }, + '504': { + 'code': 504, + 'text': 'Gateway Time-out', + 'description': + '\"The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.\"', + 'spec_title': 'RFC7231#6.6.5', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.6.5' + }, + '505': { + 'code': 505, + 'text': 'HTTP Version Not Supported', + 'description': + '\"The server does not support, or refuses to support, the protocol version that was used in the request message.\"', + 'spec_title': 'RFC7231#6.6.6', + 'spec_href': 'http://tools.ietf.org/html/rfc7231#section-6.6.6' + }, + '102': { + 'code': 102, + 'text': 'Processing', + 'description': + '\"An interim response to inform the client that the server has accepted the complete request, but has not yet completed it.\"', + 'spec_title': 'RFC5218#10.1', + 'spec_href': 'http://tools.ietf.org/html/rfc2518#section-10.1' + }, + '207': { + 'code': 207, + 'text': 'Multi-Status', + 'description': '\"Status for multiple independent operations.\"', + 'spec_title': 'RFC5218#10.2', + 'spec_href': 'http://tools.ietf.org/html/rfc2518#section-10.2' + }, + '226': + { + 'code': 226, + 'text': 'IM Used', + 'description': + '\"The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.\"', + 'spec_title': 'RFC3229#10.4.1', + 'spec_href': 'http://tools.ietf.org/html/rfc3229#section-10.4.1' + }, + '308': { + 'code': 308, + 'text': 'Permanent Redirect', + 'description': + '\"The target resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET.\"', + 'spec_title': 'RFC7238', + 'spec_href': 'http://tools.ietf.org/html/rfc7238' + }, + '422': { + 'code': 422, + 'text': 'Unprocessable Entity', + 'description': + '\"The server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.\"', + 'spec_title': 'RFC5218#10.3', + 'spec_href': 'http://tools.ietf.org/html/rfc2518#section-10.3' + }, + '423': { + 'code': 423, + 'text': 'Locked', + 'description': '\"The source or destination resource of a method is locked.\"', + 'spec_title': 'RFC5218#10.4', + 'spec_href': 'http://tools.ietf.org/html/rfc2518#section-10.4' + }, + '424': { + 'code': 424, + 'text': 'Failed Dependency', + 'description': + '\"The method could not be performed on the resource because the requested action depended on another action and that action failed.\"', + 'spec_title': 'RFC5218#10.5', + 'spec_href': 'http://tools.ietf.org/html/rfc2518#section-10.5' + }, + '428': { + 'code': 428, + 'text': 'Precondition Required', + 'description': '\"The origin server requires the request to be conditional.\"', + 'spec_title': 'RFC6585#3', + 'spec_href': 'http://tools.ietf.org/html/rfc6585#section-3' + }, + '429': { + 'code': 429, + 'text': 'Too Many Requests', + 'description': + '\"The user has sent too many requests in a given amount of time (\"rate limiting\").\"', + 'spec_title': 'RFC6585#4', + 'spec_href': 'http://tools.ietf.org/html/rfc6585#section-4' + }, + '431': { + 'code': 431, + 'text': 'Request Header Fields Too Large', + 'description': + '\"The server is unwilling to process the request because its header fields are too large.\"', + 'spec_title': 'RFC6585#5', + 'spec_href': 'http://tools.ietf.org/html/rfc6585#section-5' + }, + '451': { + 'code': 451, + 'text': 'Unavailable For Legal Reasons', + 'description': + '\"The server is denying access to the resource in response to a legal demand.\"', + 'spec_title': 'draft-ietf-httpbis-legally-restricted-status', + 'spec_href': 'http://tools.ietf.org/html/draft-ietf-httpbis-legally-restricted-status' + }, + '506': { + 'code': 506, + 'text': 'Variant Also Negotiates', + 'description': + '\"The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.\"', + 'spec_title': 'RFC2295#8.1', + 'spec_href': 'http://tools.ietf.org/html/rfc2295#section-8.1' + }, + '507': { + 'code': 507, + 'text': 'Insufficient Storage', + 'description': + '\The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.\"', + 'spec_title': 'RFC5218#10.6', + 'spec_href': 'http://tools.ietf.org/html/rfc2518#section-10.6' + }, + '511': { + 'code': 511, + 'text': 'Network Authentication Required', + 'description': '\"The client needs to authenticate to gain network access.\"', + 'spec_title': 'RFC6585#6', + 'spec_href': 'http://tools.ietf.org/html/rfc6585#section-6' + } +}; + +/** + * get the status text from StatusCode + */ +export function getStatusText(code: number) { + return STATUS_CODE_INFO[code + ''].text || 'Unknown Status'; +} + +/** + * Returns true if the the Http Status Code is 200-299 (success) + */ +export function isSuccess(status: number): boolean { + return status >= 200 && status < 300; +} diff --git a/packages/misc/angular-in-memory-web-api/src/in-memory-web-api-module.ts b/packages/misc/angular-in-memory-web-api/src/in-memory-web-api-module.ts new file mode 100644 index 0000000000..f6d7622aba --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/src/in-memory-web-api-module.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {HttpBackend, XhrFactory} from '@angular/common/http'; +import {ModuleWithProviders, NgModule, Type} from '@angular/core'; + +import {httpClientInMemBackendServiceFactory} from './http-client-in-memory-web-api-module'; +import {InMemoryBackendConfig, InMemoryBackendConfigArgs, InMemoryDbService} from './interfaces'; + +@NgModule() +export class InMemoryWebApiModule { + /** + * Redirect BOTH Angular `Http` and `HttpClient` XHR calls + * to in-memory data store that implements `InMemoryDbService`. + * 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 + * + * @param dbCreator - Class that creates seed data for in-memory database. Must implement + * InMemoryDbService. + * @param [options] + * + * @example + * InMemoryWebApiModule.forRoot(dbCreator); + * InMemoryWebApiModule.forRoot(dbCreator, {useValue: {delay:600}}); + */ + static forRoot(dbCreator: Type, options?: InMemoryBackendConfigArgs): + ModuleWithProviders { + return { + ngModule: InMemoryWebApiModule, + providers: [ + {provide: InMemoryDbService, useClass: dbCreator}, + {provide: InMemoryBackendConfig, useValue: options}, { + provide: HttpBackend, + useFactory: httpClientInMemBackendServiceFactory, + deps: [InMemoryDbService, InMemoryBackendConfig, XhrFactory] + } + ] + }; + } + + /** + * + * 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. + */ + static forFeature(dbCreator: Type, options?: InMemoryBackendConfigArgs): + ModuleWithProviders { + return InMemoryWebApiModule.forRoot(dbCreator, options); + } +} diff --git a/packages/misc/angular-in-memory-web-api/src/in-memory-web-api.ts b/packages/misc/angular-in-memory-web-api/src/in-memory-web-api.ts new file mode 100644 index 0000000000..ec0ae38883 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/src/in-memory-web-api.ts @@ -0,0 +1,14 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +export * from './backend-service'; +export * from './http-status-codes'; +export * from './http-client-backend-service'; +export * from './in-memory-web-api-module'; +export * from './http-client-in-memory-web-api-module'; +export * from './interfaces'; diff --git a/packages/misc/angular-in-memory-web-api/src/interfaces.ts b/packages/misc/angular-in-memory-web-api/src/interfaces.ts new file mode 100644 index 0000000000..56bf9c1705 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/src/interfaces.ts @@ -0,0 +1,316 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {HttpHeaders} from '@angular/common/http'; +import {Injectable} from '@angular/core'; +import {Observable} from 'rxjs'; + +/** + * Interface for a class that creates an in-memory database + * + * Its `createDb` method creates a hash of named collections that represents the database + * + * For 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: {})` where `db` is the database object described above. + */ +export abstract class InMemoryDbService { + /** + * 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 POST `commands/resetDb` request. + * Your InMemoryDbService can adjust its behavior accordingly. + */ + abstract createDb(reqInfo?: RequestInfo): {}|Observable<{}>|Promise<{}>; +} + +/** + * Interface for InMemoryBackend configuration options + */ +export abstract class InMemoryBackendConfigArgs { + /** + * The base path to the api, e.g, 'api/'. + * If not specified than `parseRequestUrl` assumes it is the first path segment in the request. + */ + apiBase?: string; + /** + * false (default) if search match should be case insensitive + */ + caseSensitiveSearch?: boolean; + /** + * false (default) put content directly inside the response body. + * true: encapsulate content in a `data` property inside the response body, `{ data: ... }`. + */ + dataEncapsulation?: boolean; + /** + * delay (in ms) to simulate latency + */ + delay?: number; + /** + * false (default) should 204 when object-to-delete not found; true: 404 + */ + delete404?: boolean; + /** + * host for this service, e.g., 'localhost' + */ + host?: string; + /** + * false (default) should pass unrecognized request URL through to original backend; true: 404 + */ + passThruUnknownUrl?: boolean; + /** + * true (default) should NOT return the item (204) after a POST. false: return the item (200). + */ + post204?: boolean; + /** + * false (default) should NOT update existing item with POST. false: OK to update. + */ + post409?: boolean; + /** + * true (default) should NOT return the item (204) after a POST. false: return the item (200). + */ + put204?: boolean; + /** + * false (default) if item not found, create as new item; false: should 404. + */ + put404?: boolean; + /** + * root path _before_ any API call, e.g., '' + */ + rootPath?: string; +} + +///////////////////////////////// +/** + * InMemoryBackendService configuration options + * Usage: + * InMemoryWebApiModule.forRoot(InMemHeroService, {delay: 600}) + * + * or if providing separately: + * provide(InMemoryBackendConfig, {useValue: {delay: 600}}), + */ +@Injectable() +export class InMemoryBackendConfig implements InMemoryBackendConfigArgs { + constructor(config: InMemoryBackendConfigArgs = {}) { + Object.assign( + this, { + // default config: + caseSensitiveSearch: false, + dataEncapsulation: false, // do NOT wrap content within an object with a `data` property + delay: 500, // simulate latency by delaying response + delete404: false, // don't complain if can't find entity to delete + passThruUnknownUrl: false, // 404 if can't process URL + post204: true, // don't return the item after a POST + post409: false, // don't update existing item with that ID + put204: true, // don't return the item after a PUT + put404: false, // create new item if PUT item with that ID not found + apiBase: undefined, // assumed to be the first path segment + host: undefined, // default value is actually set in InMemoryBackendService ctor + rootPath: undefined // default value is actually set in InMemoryBackendService ctor + }, + config); + } +} + +/** Return information (UriInfo) about a URI */ +export function parseUri(str: string): UriInfo { + // Adapted from parseuri package - http://blog.stevenlevithan.com/archives/parseuri + // tslint:disable-next-line:max-line-length + const URL_REGEX = + /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; + const m = URL_REGEX.exec(str); + const uri: UriInfo&{[key: string]: string} = { + source: '', + protocol: '', + authority: '', + userInfo: '', + user: '', + password: '', + host: '', + port: '', + relative: '', + path: '', + directory: '', + file: '', + query: '', + anchor: '' + }; + const keys = Object.keys(uri); + let i = keys.length; + + while (i--) { + uri[keys[i]] = m && m[i] || ''; + } + return uri; +} + +/** + * + * 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/' + */ +export interface ParsedRequestUrl { + apiBase: string; // the slash-terminated "base" for api requests (e.g. `api/`) + collectionName: string; // the name of the collection of data items (e.g.,`customers`) + id: string; // the (optional) id of the item in the collection (e.g., `42`) + query: Map; // the query parameters; + resourceUrl: + string; // the effective URL for the resource (e.g., 'http://localhost/api/customers/') +} + +export interface PassThruBackend { + /** + * 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. + */ + handle(req: any): Observable; +} + +export function removeTrailingSlash(path: string) { + return path.replace(/\/$/, ''); +} + +/** + * Minimum definition needed by base class + */ +export interface RequestCore { + url: string; // request URL + urlWithParams?: string; // request URL with query parameters added by `HttpParams` +} + +/** + * 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 + */ +export interface RequestInfo { + req: RequestCore; // concrete type depends upon the Http library + apiBase: string; + collectionName: string; + collection: any; + headers: HttpHeaders; + method: string; + id: any; + query: Map; + resourceUrl: string; + url: string; // request URL + utils: RequestInfoUtilities; +} + +/** + * Interface for utility methods from this service instance. + * Useful within an HTTP method override + */ +export interface RequestInfoUtilities { + /** + * Create a cold response Observable from a factory for ResponseOptions + * the same way that the in-mem backend service does. + * @param resOptionsFactory - creates ResponseOptions when observable is subscribed + * @param withDelay - if true (default), add simulated latency delay from configuration + */ + createResponse$: (resOptionsFactory: () => ResponseOptions) => Observable; + + /** + * Find first instance of item in collection by `item.id` + * @param collection + * @param id + */ + findById(collection: T[], id: any): T|undefined; + + /** return the current, active configuration which is a blend of defaults and overrides */ + getConfig(): InMemoryBackendConfigArgs; + + /** Get the in-mem service's copy of the "database" */ + getDb(): {}; + + /** Get JSON body from the request object */ + getJsonBody(req: any): any; + + /** Get location info from a url, even on server where `document` is not defined */ + getLocation(url: string): UriInfo; + + /** Get (or create) the "real" backend */ + getPassThruBackend(): PassThruBackend; + + /** + * return true if can determine that the collection's `item.id` is a number + * */ + isCollectionIdNumeric(collection: T[], collectionName: string): boolean; + + /** + * Parses the request URL into a `ParsedRequestUrl` object. + * Parsing depends upon certain values of `config`: `apiBase`, `host`, and `urlRoot`. + */ + parseRequestUrl(url: string): ParsedRequestUrl; +} + +/** + * Provide a `responseInterceptor` method of this type in your `inMemDbService` to + * morph the response options created in the `collectionHandler`. + */ +export type ResponseInterceptor = (res: ResponseOptions, ri: RequestInfo) => ResponseOptions; + +export interface ResponseOptions { + /** + * String, Object, ArrayBuffer or Blob representing the body of the {@link Response}. + */ + body?: string|Object|ArrayBuffer|Blob; + + /** + * Response headers + */ + headers?: HttpHeaders; + + /** + * Http {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html status code} + * associated with the response. + */ + status?: number; + + /** + * Status text for the status code + */ + statusText?: string; + /** + * request url + */ + url?: string; +} + +/** Interface of information about a Uri */ +export interface UriInfo { + source: string; + protocol: string; + authority: string; + userInfo: string; + user: string; + password: string; + host: string; + port: string; + relative: string; + path: string; + directory: string; + file: string; + query: string; + anchor: string; +} diff --git a/packages/misc/angular-in-memory-web-api/test/BUILD.bazel b/packages/misc/angular-in-memory-web-api/test/BUILD.bazel new file mode 100644 index 0000000000..933b195df5 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/test/BUILD.bazel @@ -0,0 +1,34 @@ +load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library") + +ts_library( + name = "test_lib", + testonly = True, + srcs = glob(["**/*.ts"]), + # Visible to //:saucelabs_unit_tests_poc target + visibility = ["//:__pkg__"], + deps = [ + "//packages/common", + "//packages/common/http", + "//packages/core", + "//packages/core/testing", + "//packages/misc/angular-in-memory-web-api", + "@npm//@types/jasmine-ajax", + "@npm//jasmine-ajax", + "@npm//rxjs", + ], +) + +karma_web_test_suite( + name = "test_web", + # do not sort + bootstrap = [ + "@npm//:node_modules/core-js/client/core.js", + "@npm//:node_modules/reflect-metadata/Reflect.js", + "@npm//:node_modules/jasmine-ajax/lib/mock-ajax.js", + "//packages/zone.js/bundles:zone.umd.js", + "//packages/zone.js/bundles:zone-testing.umd.js", + ], + deps = [ + ":test_lib", + ], +) diff --git a/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-override-service.ts b/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-override-service.ts new file mode 100644 index 0000000000..b1923f03c1 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-override-service.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +/** + * This is an example of a Hero-oriented InMemoryDbService with method overrides. + */ +import {Injectable} from '@angular/core'; +import {getStatusText, ParsedRequestUrl, RequestInfo, RequestInfoUtilities, ResponseOptions, STATUS} from 'angular-in-memory-web-api'; +import {Observable} from 'rxjs'; + +import {HeroInMemDataService} from './hero-in-mem-data-service'; + +const villains = [ + // deliberately using string ids that look numeric + {id: 100, name: 'Snidley Wipsnatch'}, {id: 101, name: 'Boris Badenov'}, + {id: 103, name: 'Natasha Fatale'} +]; + +// Pseudo guid generator +function guid() { + const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); +} + +@Injectable() +export class HeroInMemDataOverrideService extends HeroInMemDataService { + // Overrides id generator and delivers next available `id`, starting with 1001. + genId(collection: T[], collectionName: string): any { + if (collectionName === 'nobodies') { + return guid(); + } else if (collection) { + return 1 + collection.reduce((prev, curr) => Math.max(prev, curr.id || 0), 1000); + } + } + + // HTTP GET interceptor + get(reqInfo: RequestInfo): Observable|undefined { + const collectionName = reqInfo.collectionName; + if (collectionName === 'villains') { + return this.getVillains(reqInfo); + } + return undefined; // let the default GET handle all others + } + + // HTTP GET interceptor handles requests for villains + private getVillains(reqInfo: RequestInfo) { + return reqInfo.utils.createResponse$(() => { + const collection = villains.slice(); + const dataEncapsulation = reqInfo.utils.getConfig().dataEncapsulation; + const id = reqInfo.id; + const data = id == null ? collection : reqInfo.utils.findById(collection, id); + + const options: ResponseOptions = data ? + {body: dataEncapsulation ? {data} : data, status: STATUS.OK} : + {body: {error: `'Villains' with id='${id}' not found`}, status: STATUS.NOT_FOUND}; + return this.finishOptions(options, reqInfo); + }); + } + + // parseRequestUrl override + // Do this to manipulate the request URL or the parsed result + // into something your data store can handle. + // This example turns a request for `/foo/heroes` into just `/heroes`. + // It leaves other URLs untouched and forwards to the default parser. + // It also logs the result of the default parser. + parseRequestUrl(url: string, utils: RequestInfoUtilities): ParsedRequestUrl { + const newUrl = url.replace(/\/foo\/heroes/, '/heroes'); + return utils.parseRequestUrl(newUrl); + } + + responseInterceptor(resOptions: ResponseOptions, reqInfo: RequestInfo) { + if (resOptions.headers) { + resOptions.headers = resOptions.headers.set('x-test', 'test-header'); + } + return resOptions; + } + + private finishOptions(options: ResponseOptions, {headers, url}: RequestInfo) { + options.statusText = options.status == null ? undefined : getStatusText(options.status); + options.headers = headers; + options.url = url; + return options; + } +} diff --git a/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-service.ts b/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-service.ts new file mode 100644 index 0000000000..cb38b0179b --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/test/fixtures/hero-in-mem-data-service.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + + +/** + * This is an example of a Hero-oriented InMemoryDbService. + * + * For demonstration purposes, it can return the database + * synchronously as an object (default), + * as an observable, or as a promise. + * + * Add the following line to `AppModule.imports` + * InMemoryWebApiModule.forRoot(HeroInMemDataService) // or HeroInMemDataOverrideService + */ +import {Injectable} from '@angular/core'; +import {InMemoryDbService, RequestInfo} from 'angular-in-memory-web-api'; +import {Observable, of} from 'rxjs'; +import {delay} from 'rxjs/operators'; + +interface Person { + id: string|number; + name: string; +} + +interface PersonResponse { + heroes: Person[]; + stringers: Person[]; + nobodies: Person[]; +} + +@Injectable() +export class HeroInMemDataService implements InMemoryDbService { + createDb(reqInfo?: RequestInfo): + Observable|Promise|PersonResponse { + const heroes = [ + {id: 1, name: 'Windstorm'}, {id: 2, name: 'Bombasto'}, {id: 3, name: 'Magneta'}, + {id: 4, name: 'Tornado'} + ]; + + const nobodies: any[] = []; + + // entities with string ids that look like numbers + const stringers = [{id: '10', name: 'Bob String'}, {id: '20', name: 'Jill String'}]; + + // default returnType + let returnType = 'object'; + // let returnType = 'observable'; + // let returnType = 'promise'; + + // demonstrate POST commands/resetDb + // this example clears the collections if the request body tells it to do so + if (reqInfo) { + const body = reqInfo.utils.getJsonBody(reqInfo.req) || {}; + if (body.clear === true) { + heroes.length = 0; + nobodies.length = 0; + stringers.length = 0; + } + + // 'returnType` can be 'object' | 'observable' | 'promise' + returnType = body.returnType || 'object'; + } + const db = {heroes, nobodies, stringers}; + + switch (returnType) { + case 'observable': + return of(db).pipe(delay(10)); + case 'promise': + return new Promise(resolve => setTimeout(() => resolve(db), 10)); + default: + return db; + } + } +} diff --git a/packages/misc/angular-in-memory-web-api/test/fixtures/hero-service.ts b/packages/misc/angular-in-memory-web-api/test/fixtures/hero-service.ts new file mode 100644 index 0000000000..9dde8222d2 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/test/fixtures/hero-service.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Observable} from 'rxjs'; +import {Hero} from './hero'; + +export abstract class HeroService { + heroesUrl = 'api/heroes'; // URL to web api + + abstract getHeroes(): Observable; + abstract getHero(id: number): Observable; + abstract addHero(name: string): Observable; + abstract deleteHero(hero: Hero|number): Observable; + abstract searchHeroes(term: string): Observable; + abstract updateHero(hero: Hero): Observable; +} diff --git a/packages/misc/angular-in-memory-web-api/test/fixtures/hero.ts b/packages/misc/angular-in-memory-web-api/test/fixtures/hero.ts new file mode 100644 index 0000000000..f1c4250a78 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/test/fixtures/hero.ts @@ -0,0 +1,14 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +export class Hero { + constructor(public id = 0, public name = '') {} + clone() { + return new Hero(this.id, this.name); + } +} diff --git a/packages/misc/angular-in-memory-web-api/test/fixtures/http-client-hero-service.ts b/packages/misc/angular-in-memory-web-api/test/fixtures/http-client-hero-service.ts new file mode 100644 index 0000000000..658bdf439f --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/test/fixtures/http-client-hero-service.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; +import {Injectable} from '@angular/core'; +import {Observable, throwError} from 'rxjs'; +import {catchError} from 'rxjs/operators'; + +import {Hero} from './hero'; +import {HeroService} from './hero-service'; + +const cudOptions = { + headers: new HttpHeaders({'Content-Type': 'application/json'}) +}; + +@Injectable() +export class HttpClientHeroService extends HeroService { + constructor(private http: HttpClient) { + super(); + } + + getHeroes(): Observable { + return this.http.get(this.heroesUrl).pipe(catchError(this.handleError)); + } + + // This get-by-id will 404 when id not found + getHero(id: number): Observable { + const url = `${this.heroesUrl}/${id}`; + return this.http.get(url).pipe(catchError(this.handleError)); + } + + // This get-by-id does not 404; returns undefined when id not found + // getHero(id: number): Observable { + // const url = `${this._heroesUrl}/?id=${id}`; + // return this.http.get(url) + // .map(heroes => heroes[0] as Hero) + // .catch(this.handleError); + // } + + addHero(name: string): Observable { + const hero = {name}; + + return this.http.post(this.heroesUrl, hero, cudOptions) + .pipe(catchError(this.handleError)); + } + + deleteHero(hero: Hero|number): Observable { + const id = typeof hero === 'number' ? hero : hero.id; + const url = `${this.heroesUrl}/${id}`; + + return this.http.delete(url, cudOptions).pipe(catchError(this.handleError)); + } + + searchHeroes(term: string): Observable { + term = term.trim(); + // add safe, encoded search parameter if term is present + const options = term ? {params: new HttpParams().set('name', term)} : {}; + + return this.http.get(this.heroesUrl, options).pipe(catchError(this.handleError)); + } + + updateHero(hero: Hero): Observable { + return this.http.put(this.heroesUrl, hero, cudOptions).pipe(catchError(this.handleError)); + } + + private handleError(error: any) { + // In a real world app, we might send the error to remote logging infrastructure + // and reformat for user consumption + return throwError(error); + } +} diff --git a/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts b/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts new file mode 100644 index 0000000000..8b45bffdb5 --- /dev/null +++ b/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts @@ -0,0 +1,574 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +/// + +import {HTTP_INTERCEPTORS, HttpBackend, HttpClient, HttpClientModule, HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http'; +import {Injectable} from '@angular/core'; +import {async, TestBed} from '@angular/core/testing'; +import {HttpClientBackendService, HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api'; +import {Observable, zip} from 'rxjs'; +import {concatMap, map, tap} from 'rxjs/operators'; + +import {Hero} from './fixtures/hero'; +import {HeroInMemDataOverrideService} from './fixtures/hero-in-mem-data-override-service'; +import {HeroInMemDataService} from './fixtures/hero-in-mem-data-service'; +import {HeroService} from './fixtures/hero-service'; +import {HttpClientHeroService} from './fixtures/http-client-hero-service'; + +describe('HttpClient Backend Service', () => { + const delay = 1; // some minimal simulated latency delay + + describe('raw Angular HttpClient', () => { + let http: HttpClient; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientModule, HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}) + ] + }); + + http = TestBed.get(HttpClient); + }); + + it('can get heroes', async(() => { + http.get('api/heroes') + .subscribe( + heroes => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'), + failRequest); + })); + + it('GET should be a "cold" observable', async(() => { + const httpBackend = TestBed.get(HttpBackend); + const spy = spyOn(httpBackend, 'collectionHandler').and.callThrough(); + const get$ = http.get('api/heroes'); + + // spy on `collectionHandler` should not be called before subscribe + expect(spy).not.toHaveBeenCalled(); + + get$.subscribe(heroes => { + expect(spy).toHaveBeenCalled(); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }, failRequest); + })); + + it('GET should wait until after delay to respond', async(() => { + // to make test fail, set `delay=0` above + let gotResponse = false; + + http.get('api/heroes').subscribe(heroes => { + gotResponse = true; + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }, failRequest); + + expect(gotResponse).toBe(false, 'should delay before response'); + })); + + it('Should only initialize the db once', async(() => { + const httpBackend = TestBed.get(HttpBackend); + const spy = spyOn(httpBackend, 'resetDb').and.callThrough(); + + // Simultaneous backend.handler calls + // Only the first should initialize by calling `resetDb` + // All should wait until the db is "ready" + // then they share the same db instance. + http.get('api/heroes').subscribe(); + http.get('api/heroes').subscribe(); + http.get('api/heroes').subscribe(); + http.get('api/heroes').subscribe(); + + expect(spy.calls.count()).toBe(1); + })); + + it('can get heroes (w/ a different base path)', async(() => { + http.get('some-base-path/heroes').subscribe(heroes => { + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }, failRequest); + })); + + it('should 404 when GET unknown collection (after delay)', async(() => { + let gotError = false; + const url = 'api/unknown-collection'; + http.get(url).subscribe( + () => fail(`should not have found data for '${url}'`), err => { + gotError = true; + expect(err.status).toBe(404, 'should have 404 status'); + }); + + expect(gotError).toBe(false, 'should not get error until after delay'); + })); + + it('should return the hero w/id=1 for GET app/heroes/1', async(() => { + http.get('api/heroes/1') + .subscribe( + hero => expect(hero).toBeDefined('should find hero with id=1'), failRequest); + })); + + // test where id is string that looks like a number + it('should return the stringer w/id="10" for GET app/stringers/10', async(() => { + http.get('api/stringers/10') + .subscribe( + hero => expect(hero).toBeDefined('should find string with id="10"'), failRequest); + })); + + it('should return 1-item array for GET app/heroes/?id=1', async(() => { + http.get('api/heroes/?id=1') + .subscribe( + heroes => expect(heroes.length).toBe(1, 'should find one hero w/id=1'), + failRequest); + })); + + it('should return 1-item array for GET app/heroes?id=1', async(() => { + http.get('api/heroes?id=1') + .subscribe( + heroes => expect(heroes.length).toBe(1, 'should find one hero w/id=1'), + failRequest); + })); + + it('should return undefined for GET app/heroes?id=not-found-id', async(() => { + http.get('api/heroes?id=123456') + .subscribe(heroes => expect(heroes.length).toBe(0), failRequest); + })); + + it('should return 404 for GET app/heroes/not-found-id', async(() => { + const url = 'api/heroes/123456'; + http.get(url).subscribe( + () => fail(`should not have found data for '${url}'`), + err => expect(err.status).toBe(404, 'should have 404 status')); + })); + + it('can generate the id when add a hero with no id', async(() => { + const hero = new Hero(undefined, 'SuperDooper'); + http.post('api/heroes', hero).subscribe(replyHero => { + expect(replyHero.id).toBeDefined('added hero should have an id'); + expect(replyHero).not.toBe(hero, 'reply hero should not be the request hero'); + }, failRequest); + })); + + it('can get nobodies (empty collection)', async(() => { + http.get('api/nobodies').subscribe(nobodies => { + expect(nobodies.length).toBe(0, 'should have no nobodies'); + }, failRequest); + })); + + it('can add a nobody with an id to empty nobodies collection', async(() => { + const id = 'g-u-i-d'; + + http.post('api/nobodies', {id, name: 'Noman'}) + .pipe(concatMap(() => http.get<{id: string; name: string;}[]>('api/nobodies'))) + .subscribe(nobodies => { + expect(nobodies.length).toBe(1, 'should a nobody'); + expect(nobodies[0].name).toBe('Noman', 'should be "Noman"'); + expect(nobodies[0].id).toBe(id, 'should preserve the submitted, ' + id); + }, failRequest); + })); + + it('should fail when add a nobody without an id to empty nobodies collection', async(() => { + http.post('api/nobodies', {name: 'Noman'}) + .subscribe( + () => fail(`should not have been able to add 'Norman' to 'nobodies'`), err => { + expect(err.status).toBe(422, 'should have 422 status'); + expect(err.body.error).toContain('id type is non-numeric'); + }); + })); + + describe('can reset the database', () => { + it('to empty (object db)', async(() => resetDatabaseTest('object'))); + + it('to empty (observable db)', async(() => resetDatabaseTest('observable'))); + + it('to empty (promise db)', async(() => resetDatabaseTest('promise'))); + + function resetDatabaseTest(returnType: string) { + // Observable of the number of heroes and nobodies + const sizes$ = + zip(http.get('api/heroes'), http.get('api/nobodies'), + http.get('api/stringers')) + .pipe(map( + ([h, n, s]) => ({heroes: h.length, nobodies: n.length, stringers: s.length}))); + + // Add a nobody so that we have one + http.post('api/nobodies', {id: 42, name: 'Noman'}) + .pipe( + // Reset database with "clear" option + concatMap(() => http.post('commands/resetDb', {clear: true, returnType})), + // get the number of heroes and nobodies + concatMap(() => sizes$)) + .subscribe(sizes => { + expect(sizes.heroes).toBe(0, 'reset should have cleared the heroes'); + expect(sizes.nobodies).toBe(0, 'reset should have cleared the nobodies'); + expect(sizes.stringers).toBe(0, 'reset should have cleared the stringers'); + }, failRequest); + } + }); + }); + + describe('raw Angular HttpClient w/ override service', () => { + let http: HttpClient; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientModule, + HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataOverrideService, {delay}) + ] + }); + + http = TestBed.get(HttpClient); + }); + + it('can get heroes', async(() => { + http.get('api/heroes') + .subscribe( + heroes => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'), + failRequest); + })); + + it('can translate `foo/heroes` to `heroes` via `parsedRequestUrl` override', async(() => { + http.get('api/foo/heroes') + .subscribe( + heroes => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'), + failRequest); + })); + + it('can get villains', async(() => { + http.get('api/villains') + .subscribe( + villains => expect(villains.length).toBeGreaterThan(0, 'should have villains'), + failRequest); + })); + + it('should 404 when POST to villains', async(() => { + const url = 'api/villains'; + http.post(url, {id: 42, name: 'Dr. Evil'}) + .subscribe( + () => fail(`should not have POSTed data for '${url}'`), + err => expect(err.status).toBe(404, 'should have 404 status')); + })); + + it('should 404 when GET unknown collection', async(() => { + const url = 'api/unknown-collection'; + http.get(url).subscribe( + () => fail(`should not have found data for '${url}'`), + err => expect(err.status).toBe(404, 'should have 404 status')); + })); + + it('should use genId override to add new hero, "Maxinius"', async(() => { + http.post('api/heroes', {name: 'Maxinius'}) + .pipe(concatMap(() => http.get('api/heroes?name=Maxi'))) + .subscribe(heroes => { + expect(heroes.length).toBe(1, 'should have found "Maxinius"'); + expect(heroes[0].name).toBe('Maxinius'); + expect(heroes[0].id).toBeGreaterThan(1000); + }, failRequest); + })); + + it('should use genId override guid generator for a new nobody without an id', async(() => { + http.post('api/nobodies', {name: 'Noman'}) + .pipe(concatMap(() => http.get<{id: string; name: string}[]>('api/nobodies'))) + .subscribe(nobodies => { + expect(nobodies.length).toBe(1, 'should a nobody'); + expect(nobodies[0].name).toBe('Noman', 'should be "Noman"'); + expect(typeof nobodies[0].id).toBe('string', 'should create a string (guid) id'); + }, failRequest); + })); + + describe('can reset the database', () => { + it('to empty (object db)', async(() => resetDatabaseTest('object'))); + + it('to empty (observable db)', async(() => resetDatabaseTest('observable'))); + + it('to empty (promise db)', async(() => resetDatabaseTest('promise'))); + + function resetDatabaseTest(returnType: string) { + // Observable of the number of heroes, nobodies and villains + const sizes$ = zip(http.get('api/heroes'), http.get('api/nobodies'), + http.get('api/stringers'), http.get('api/villains')) + .pipe(map(([h, n, s, v]) => ({ + heroes: h.length, + nobodies: n.length, + stringers: s.length, + villains: v.length + }))); + + // Add a nobody so that we have one + http.post('api/nobodies', {id: 42, name: 'Noman'}) + .pipe( + // Reset database with "clear" option + concatMap(() => http.post('commands/resetDb', {clear: true, returnType})), + // count all the collections + concatMap(() => sizes$)) + .subscribe(sizes => { + expect(sizes.heroes).toBe(0, 'reset should have cleared the heroes'); + expect(sizes.nobodies).toBe(0, 'reset should have cleared the nobodies'); + expect(sizes.stringers).toBe(0, 'reset should have cleared the stringers'); + expect(sizes.villains).toBeGreaterThan(0, 'reset should NOT clear villains'); + }, failRequest); + } + }); + }); + + describe('HttpClient HeroService', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientModule, HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}) + ], + providers: [{provide: HeroService, useClass: HttpClientHeroService}] + }); + }); + + describe('HeroService core', () => { + let heroService: HeroService; + + beforeEach(() => { + heroService = TestBed.get(HeroService); + }); + + it('can get heroes', async(() => { + heroService.getHeroes().subscribe(heroes => { + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }, failRequest); + })); + + it('can get hero w/ id=1', async(() => { + heroService.getHero(1).subscribe(hero => { + expect(hero.name).toBe('Windstorm'); + }, () => fail('getHero failed')); + })); + + it('should 404 when hero id not found', async(() => { + const id = 123456; + heroService.getHero(id).subscribe( + () => fail(`should not have found hero for id='${id}'`), err => { + expect(err.status).toBe(404, 'should have 404 status'); + }); + })); + + it('can add a hero', async(() => { + heroService.addHero('FunkyBob') + .pipe( + tap(hero => expect(hero.name).toBe('FunkyBob')), + // Get the new hero by its generated id + concatMap(hero => heroService.getHero(hero.id))) + .subscribe(hero => { + expect(hero.name).toBe('FunkyBob'); + }, () => failRequest('re-fetch of new hero failed')); + }), + 10000); + + it('can delete a hero', async(() => { + const id = 1; + heroService.deleteHero(id).subscribe((_: {}) => expect(_).toBeDefined(), failRequest); + })); + + it('should allow delete of non-existent hero', async(() => { + const id = 123456; + heroService.deleteHero(id).subscribe((_: {}) => expect(_).toBeDefined(), failRequest); + })); + + it('can search for heroes by name containing "a"', async(() => { + heroService.searchHeroes('a').subscribe((heroes: Hero[]) => { + expect(heroes.length).toBe(3, 'should find 3 heroes with letter "a"'); + }, failRequest); + })); + + it('can update existing hero', async(() => { + const id = 1; + heroService.getHero(id) + .pipe( + concatMap(hero => { + hero.name = 'Thunderstorm'; + return heroService.updateHero(hero); + }), + concatMap(() => heroService.getHero(id))) + .subscribe( + hero => expect(hero.name).toBe('Thunderstorm'), + () => fail('re-fetch of updated hero failed')); + }), + 10000); + + it('should create new hero when try to update non-existent hero', async(() => { + const falseHero = new Hero(12321, 'DryMan'); + heroService.updateHero(falseHero).subscribe( + hero => expect(hero.name).toBe(falseHero.name), failRequest); + })); + }); + }); + + describe('HttpClient interceptor', () => { + let http: HttpClient; + let interceptors: HttpInterceptor[]; + let httpBackend: HttpClientBackendService; + + /** + * Test interceptor adds a request header and a response header + */ + @Injectable() + class TestHeaderInterceptor implements HttpInterceptor { + intercept(req: HttpRequest, next: HttpHandler): Observable> { + const reqClone = req.clone({setHeaders: {'x-test-req': 'req-test-header'}}); + + return next.handle(reqClone).pipe(map(event => { + if (event instanceof HttpResponse) { + event = event.clone({headers: event.headers.set('x-test-res', 'res-test-header')}); + } + return event; + })); + } + } + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientModule, HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}) + ], + providers: [ + // Add test interceptor just for this test suite + {provide: HTTP_INTERCEPTORS, useClass: TestHeaderInterceptor, multi: true} + ] + }); + + http = TestBed.get(HttpClient); + httpBackend = TestBed.get(HttpBackend); + interceptors = TestBed.get(HTTP_INTERCEPTORS); + }); + + // sanity test + it('TestingModule should provide the test interceptor', () => { + const ti = interceptors.find(i => i instanceof TestHeaderInterceptor); + expect(ti).toBeDefined(); + }); + + it('should have GET request header from test interceptor', async(() => { + const handle = spyOn(httpBackend, 'handle').and.callThrough(); + + http.get('api/heroes').subscribe(heroes => { + // HttpRequest is first arg of the first call to in-mem backend `handle` + const req: HttpRequest = handle.calls.argsFor(0)[0]; + const reqHeader = req.headers.get('x-test-req'); + expect(reqHeader).toBe('req-test-header'); + + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }, failRequest); + })); + + it('should have GET response header from test interceptor', async(() => { + let gotResponse = false; + const req = new HttpRequest('GET', 'api/heroes'); + http.request(req).subscribe(event => { + if (event.type === HttpEventType.Response) { + gotResponse = true; + + const resHeader = event.headers.get('x-test-res'); + expect(resHeader).toBe('res-test-header'); + + const heroes = event.body as Hero[]; + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + } + }, failRequest, () => expect(gotResponse).toBe(true, 'should have seen Response event')); + })); + }); + + describe('HttpClient passThru', () => { + let http: HttpClient; + let httpBackend: HttpClientBackendService; + let createPassThruBackend: jasmine.Spy; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientModule, + HttpClientInMemoryWebApiModule.forRoot( + HeroInMemDataService, {delay, passThruUnknownUrl: true}) + ] + }); + + http = TestBed.get(HttpClient); + httpBackend = TestBed.get(HttpBackend); + createPassThruBackend = spyOn(httpBackend, 'createPassThruBackend').and.callThrough(); + }); + + beforeEach(() => { + jasmine.Ajax.install(); + }); + + afterEach(() => { + jasmine.Ajax.uninstall(); + }); + + it('can get heroes (no passthru)', async(() => { + http.get('api/heroes').subscribe(heroes => { + expect(createPassThruBackend).not.toHaveBeenCalled(); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }, failRequest); + })); + + // `passthru` is NOT a collection in the data store + // so requests for it should pass thru to the "real" server + + it('can GET passthru', async(() => { + jasmine.Ajax.stubRequest('api/passthru').andReturn({ + 'status': 200, + 'contentType': 'application/json', + 'response': JSON.stringify([{id: 42, name: 'Dude'}]) + }); + + http.get('api/passthru').subscribe(passthru => { + expect(passthru.length).toBeGreaterThan(0, 'should have passthru data'); + }, failRequest); + })); + + it('can ADD to passthru', async(() => { + jasmine.Ajax.stubRequest('api/passthru').andReturn({ + 'status': 200, + 'contentType': 'application/json', + 'response': JSON.stringify({id: 42, name: 'Dude'}) + }); + + http.post('api/passthru', {name: 'Dude'}).subscribe(passthru => { + expect(passthru).toBeDefined('should have passthru data'); + expect(passthru.id).toBe(42, 'passthru object should have id 42'); + }, failRequest); + })); + }); + + describe('Http dataEncapsulation = true', () => { + let http: HttpClient; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientModule, + HttpClientInMemoryWebApiModule.forRoot( + HeroInMemDataService, {delay, dataEncapsulation: true}) + ] + }); + + http = TestBed.get(HttpClient); + }); + + it('can get heroes (encapsulated)', async(() => { + http.get<{data: any}>('api/heroes') + .pipe(map(data => data.data as Hero[])) + .subscribe( + heroes => expect(heroes.length).toBeGreaterThan(0, 'should have data.heroes'), + failRequest); + })); + }); +}); + + +/** + * Fail a Jasmine test such that it displays the error object, + * typically passed in the error path of an Observable.subscribe() + */ +function failRequest(err: any) { + fail(JSON.stringify(err)); +} diff --git a/packages/tsconfig.json b/packages/tsconfig.json index 8e9f5153b6..82b7c712a7 100644 --- a/packages/tsconfig.json +++ b/packages/tsconfig.json @@ -19,7 +19,8 @@ "selenium-webdriver": ["./node_modules/@types/selenium-webdriver/index.d.ts"], "rxjs/*": ["./node_modules/rxjs/*"], "@angular/*": ["./packages/*"], - "zone.js/*": ["./packages/zone.js/*"] + "zone.js/*": ["./packages/zone.js/*"], + "angular-in-memory-web-api": ["./packages/misc/angular-in-memory-web-api/index.ts"] }, "rootDir": ".", "inlineSourceMap": true, diff --git a/test-main.js b/test-main.js index 75d210d7f1..4321c86442 100644 --- a/test-main.js +++ b/test-main.js @@ -28,6 +28,7 @@ System.config({ 'url': 'dist/all/@angular/empty.js', 'xhr2': 'dist/all/@angular/empty.js', '@angular/platform-server/src/domino_adapter': 'dist/all/empty.js', + 'angular-in-memory-web-api': 'dist/all/@angular/misc/angular-in-memory-web-api', 'rxjs': 'node_modules/rxjs', }, packages: { @@ -45,6 +46,7 @@ System.config({ '@angular/common/http': {main: 'index.js', defaultExtension: 'js'}, '@angular/common': {main: 'index.js', defaultExtension: 'js'}, '@angular/forms': {main: 'index.js', defaultExtension: 'js'}, + '@angular/misc/angular-in-memory-web-api': {main: 'index.js', defaultExtension: 'js'}, // remove after all tests imports are fixed '@angular/facade': {main: 'index.js', defaultExtension: 'js'}, '@angular/router/testing': {main: 'index.js', defaultExtension: 'js'}, diff --git a/yarn.lock b/yarn.lock index 7de5b582a8..eb21acf28d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2204,6 +2204,11 @@ "@types/through" "*" rxjs "^6.4.0" +"@types/jasmine-ajax@^3.3.1": + version "3.3.1" + resolved "https://registry.yarnpkg.com/@types/jasmine-ajax/-/jasmine-ajax-3.3.1.tgz#69bc09babecc600cd80ba7e23f61937b0eea735c" + integrity sha512-pU+naJ9ULvwdWB1rAzAwoKFfjSvrpI1ScKjN5WkEJgJSoUNv1KqpO6rEuX/r4s3u+E9KgntfpoQsIdFq1tLfiw== + "@types/jasmine@*", "@types/jasmine@3.5.10": version "3.5.10" resolved "https://registry.yarnpkg.com/@types/jasmine/-/jasmine-3.5.10.tgz#a1a41012012b5da9d4b205ba9eba58f6cce2ab7b" @@ -8872,6 +8877,11 @@ istanbul-reports@^1.3.0: dependencies: handlebars "^4.0.3" +jasmine-ajax@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/jasmine-ajax/-/jasmine-ajax-4.0.0.tgz#7d8ba7e47e3f7e780e155fe9aa563faafa7e1a26" + integrity sha512-htTxNw38BSHxxmd8RRMejocdPqLalGHU6n3HWFbzp/S8AuTQd1MYjkSH3dYDsbZ7EV1Xqx/b94m3tKaVSVBV2A== + jasmine-core@^3.3, jasmine-core@^3.5.0, jasmine-core@~3.5.0: version "3.5.0" resolved "https://registry.yarnpkg.com/jasmine-core/-/jasmine-core-3.5.0.tgz#132c23e645af96d85c8bca13c8758b18429fc1e4"