ng2-rest 19.0.46 → 19.0.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,136 +1,136 @@
1
-
2
- ## ng2-rest ##
3
-
4
- Robust isomorphic REST framework for browser (Angular, React etc.) and backend (NodeJS) JavaScript/TypeScript apps.
5
-
6
- Features:
7
- - Compatible with Angular (2+) (newest 13,14 also...) , React, Vue , NodeJS (works everywhere)
8
- - Compatible with RxJS operators (exhaustMap, switchMap, request cancelation etc.)
9
- - Based on [axios](https://axios-http.com/) => excellent alternative to Angular's [HttpClient](https://angular.io/api/common/http/HttpClient)
10
- - JSONP api request handling
11
- - Transfer class instance from server to client and back
12
- - Elegant way of dealing with REST api ( *similar to ExpressJS routes definitions* )
13
-
14
- (more documentation soon... )
15
-
16
- To install this package run:
17
-
18
- npm install ng2-rest --save
19
-
20
- Import Resource class:
21
- ```ts
22
- import { Resource } from 'ng2-rest/browser';
23
- ```
24
-
25
- Resource
26
- ========
27
-
28
- Fit you existing API (not only REST) into new fluent objects with **Resource**
29
- class observables. Use power of **async** in new angular templates;
30
-
31
- **template.html**
32
- ```html
33
- Users:
34
- <ul *ngIf="model.allUsers() | async; else loader; let users" >
35
-
36
- <li *ngFor="let user of users">
37
- {{user.id}} {{user.fullName()}}
38
- <br>
39
- <input type="name" [(NgModel)]="user.name" >
40
- <button (click)="model.update(user)" > Update </button>
41
- </li>
42
-
43
- </ul>
44
-
45
- <ng-template #loader> loading users... </ng-template>
46
-
47
- ```
48
- **component.ts**
49
- ```ts
50
- class User {
51
- name: string;
52
- surname: string;
53
- id: number;
54
-
55
- fullName() {
56
- return `Surname: ${this.surname}, Name: ${this.name}`;
57
- }
58
- }
59
-
60
- // Express.js style url endpoint model
61
- // you can ommit "<User>" part is you don't wanna see response interface
62
- // also you can ommit third argument ",User" is you don't wanna
63
- // map response object to User class objects
64
- const rest = Resource.create<User>("http://yourbackend.com/api","users/:id",{'':User} )
65
-
66
- class UserComponent {
67
-
68
- // Prepare your beautiful interface
69
- model = {
70
- allUsers: () => rest.model()
71
- .array
72
- .get()
73
- .observable // Observable resposne (useful for Angular 2+ html templates)
74
- .pipe( map({ body } => body.json) ) // get all users, body.json => User[]
75
-
76
- userBy: (id) => rest.model({id})
77
- .get() // Promise response by default
78
- .then({ body } => console.log(body.json)) // get user by id, body.json => User
79
-
80
- update: async (user:User) =>{
81
- try {
82
- await rest.model({id:user.id}).put(user) // Promise response by default
83
-
84
- alert('Update sucess')
85
- } catch(e) {
86
- alert(e)
87
- }
88
- }
89
- }
90
-
91
- constructor() { }
92
-
93
- }
94
- ```
95
-
96
- Specification
97
- ============
98
- Example **UrlParams[]** :
99
- `[ { sort: true },{ filter: 'id,5' }, { filter: 'name,test' } ]`
100
-
101
-
102
- | Name | Parameters | Description |
103
- | :---: | --- | ---: |
104
- | **array** | changes response type to array |
105
- | **get** | `model, UrlParams[] ` | get data |
106
- | **post** | `model, UrlParams[] ` | create data |
107
- | **patch** | `model, UrlParams[] ` | change data <br>(effect of changing data may be diffrent with each request) |
108
- | **put** | `model, UrlParams[]` | change data <br>(can be done multiple times with same effect) |
109
- | **head** | `model, UrlParams[]` | check data |
110
- | **delete** | `model, UrlParams[] ` | remove data |
111
- | **jsonp** | `model, UrlParams[] ` | get jsonp data |
112
-
113
-
114
-
115
- # Production mode
116
- ===
117
- Nice things to do in production mode:
118
-
119
- **1. Disable warnings.**
120
-
121
- If you don't wanna see warning, disable it like this:
122
- ```ts
123
- if (environment.production) {
124
- Resource.enableWarnings = false;
125
- }
126
- ```
127
-
128
- # Angular 2+ ngZone
129
- If you are using Angular 2+ you need to do this in your root **app.component**:
130
- ```ts
131
- constructor(zone:NgZone) {
132
- Resource.initAngularNgZone(zone)
133
- }
134
- ```
135
-
136
-
1
+
2
+ ## ng2-rest ##
3
+
4
+ Robust isomorphic REST framework for browser (Angular, React etc.) and backend (NodeJS) JavaScript/TypeScript apps.
5
+
6
+ Features:
7
+ - Compatible with Angular (2+) (newest 13,14 also...) , React, Vue , NodeJS (works everywhere)
8
+ - Compatible with RxJS operators (exhaustMap, switchMap, request cancelation etc.)
9
+ - Based on [axios](https://axios-http.com/) => excellent alternative to Angular's [HttpClient](https://angular.io/api/common/http/HttpClient)
10
+ - JSONP api request handling
11
+ - Transfer class instance from server to client and back
12
+ - Elegant way of dealing with REST api ( *similar to ExpressJS routes definitions* )
13
+
14
+ (more documentation soon... )
15
+
16
+ To install this package run:
17
+
18
+ npm install ng2-rest --save
19
+
20
+ Import Resource class:
21
+ ```ts
22
+ import { Resource } from 'ng2-rest/browser';
23
+ ```
24
+
25
+ Resource
26
+ ========
27
+
28
+ Fit you existing API (not only REST) into new fluent objects with **Resource**
29
+ class observables. Use power of **async** in new angular templates;
30
+
31
+ **template.html**
32
+ ```html
33
+ Users:
34
+ <ul *ngIf="model.allUsers() | async; else loader; let users" >
35
+
36
+ <li *ngFor="let user of users">
37
+ {{user.id}} {{user.fullName()}}
38
+ <br>
39
+ <input type="name" [(NgModel)]="user.name" >
40
+ <button (click)="model.update(user)" > Update </button>
41
+ </li>
42
+
43
+ </ul>
44
+
45
+ <ng-template #loader> loading users... </ng-template>
46
+
47
+ ```
48
+ **component.ts**
49
+ ```ts
50
+ class User {
51
+ name: string;
52
+ surname: string;
53
+ id: number;
54
+
55
+ fullName() {
56
+ return `Surname: ${this.surname}, Name: ${this.name}`;
57
+ }
58
+ }
59
+
60
+ // Express.js style url endpoint model
61
+ // you can ommit "<User>" part is you don't wanna see response interface
62
+ // also you can ommit third argument ",User" is you don't wanna
63
+ // map response object to User class objects
64
+ const rest = Resource.create<User>("http://yourbackend.com/api","users/:id",{'':User} )
65
+
66
+ class UserComponent {
67
+
68
+ // Prepare your beautiful interface
69
+ model = {
70
+ allUsers: () => rest.model()
71
+ .array
72
+ .get()
73
+ .observable // Observable resposne (useful for Angular 2+ html templates)
74
+ .pipe( map({ body } => body.json) ) // get all users, body.json => User[]
75
+
76
+ userBy: (id) => rest.model({id})
77
+ .get() // Promise response by default
78
+ .then({ body } => console.log(body.json)) // get user by id, body.json => User
79
+
80
+ update: async (user:User) =>{
81
+ try {
82
+ await rest.model({id:user.id}).put(user) // Promise response by default
83
+
84
+ alert('Update sucess')
85
+ } catch(e) {
86
+ alert(e)
87
+ }
88
+ }
89
+ }
90
+
91
+ constructor() { }
92
+
93
+ }
94
+ ```
95
+
96
+ Specification
97
+ ============
98
+ Example **UrlParams[]** :
99
+ `[ { sort: true },{ filter: 'id,5' }, { filter: 'name,test' } ]`
100
+
101
+
102
+ | Name | Parameters | Description |
103
+ | :---: | --- | ---: |
104
+ | **array** | changes response type to array |
105
+ | **get** | `model, UrlParams[] ` | get data |
106
+ | **post** | `model, UrlParams[] ` | create data |
107
+ | **patch** | `model, UrlParams[] ` | change data <br>(effect of changing data may be diffrent with each request) |
108
+ | **put** | `model, UrlParams[]` | change data <br>(can be done multiple times with same effect) |
109
+ | **head** | `model, UrlParams[]` | check data |
110
+ | **delete** | `model, UrlParams[] ` | remove data |
111
+ | **jsonp** | `model, UrlParams[] ` | get jsonp data |
112
+
113
+
114
+
115
+ # Production mode
116
+ ===
117
+ Nice things to do in production mode:
118
+
119
+ **1. Disable warnings.**
120
+
121
+ If you don't wanna see warning, disable it like this:
122
+ ```ts
123
+ if (environment.production) {
124
+ Resource.enableWarnings = false;
125
+ }
126
+ ```
127
+
128
+ # Angular 2+ ngZone
129
+ If you are using Angular 2+ you need to do this in your root **app.component**:
130
+ ```ts
131
+ constructor(zone:NgZone) {
132
+ Resource.initAngularNgZone(zone)
133
+ }
134
+ ```
135
+
136
+
package/browser/README.md CHANGED
@@ -1,24 +1,24 @@
1
- # MyLib
2
-
3
- This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 13.2.0.
4
-
5
- ## Code scaffolding
6
-
7
- Run `ng generate component component-name --project my-lib` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project my-lib`.
8
- > Note: Don't forget to add `--project my-lib` or else it will be added to the default project in your `angular.json` file.
9
-
10
- ## Build
11
-
12
- Run `ng build my-lib` to build the project. The build artifacts will be stored in the `dist/` directory.
13
-
14
- ## Publishing
15
-
16
- After building your library with `ng build my-lib`, go to the dist folder `cd dist/my-lib` and run `npm publish`.
17
-
18
- ## Running unit tests
19
-
20
- Run `ng test my-lib` to execute the unit tests via [Karma](https://karma-runner.github.io).
21
-
22
- ## Further help
23
-
24
- To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.
1
+ # MyLib
2
+
3
+ This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 13.2.0.
4
+
5
+ ## Code scaffolding
6
+
7
+ Run `ng generate component component-name --project my-lib` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project my-lib`.
8
+ > Note: Don't forget to add `--project my-lib` or else it will be added to the default project in your `angular.json` file.
9
+
10
+ ## Build
11
+
12
+ Run `ng build my-lib` to build the project. The build artifacts will be stored in the `dist/` directory.
13
+
14
+ ## Publishing
15
+
16
+ After building your library with `ng build my-lib`, go to the dist folder `cd dist/my-lib` and run `npm publish`.
17
+
18
+ ## Running unit tests
19
+
20
+ Run `ng test my-lib` to execute the unit tests via [Karma](https://karma-runner.github.io).
21
+
22
+ ## Further help
23
+
24
+ To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.
@@ -1,5 +1,5 @@
1
1
  import { from, firstValueFrom, Subject, Observable } from 'rxjs';
2
- import { _, UtilsOs, CoreHelpers, Helpers as Helpers$1 } from 'tnp-core/browser';
2
+ import { _, UtilsOs, CoreHelpers, CoreModels, Helpers as Helpers$1 } from 'tnp-core/browser';
3
3
  import { diffChars } from 'diff';
4
4
  import { Log, Level } from 'ng2-logger/browser';
5
5
  import { walk } from 'lodash-walk-object/browser';
@@ -643,6 +643,12 @@ const buildInterceptorChain = (interceptors, backend) => {
643
643
  };
644
644
 
645
645
  /* */
646
+ class RestCommonHttpResponseWrapper {
647
+ }
648
+ class RestResponseWrapper extends RestCommonHttpResponseWrapper {
649
+ }
650
+ class RestErrorResponseWrapper extends RestCommonHttpResponseWrapper {
651
+ }
646
652
  // const log = Log.create('rest namespace', Level.__NOTHING)
647
653
  var Models;
648
654
  (function (Models) {
@@ -651,11 +657,19 @@ var Models;
651
657
  Models.ParamConfig = Models$1.ParamConfig;
652
658
  [];
653
659
  class BaseBody {
654
- toJSON(data, isJSONArray = false) {
655
- let r = isJSONArray ? [] : {};
660
+ toJSON(data, opt) {
661
+ opt = opt || { isJSONArray: false };
662
+ let r = opt.isJSONArray ? [] : {};
656
663
  if (typeof data === 'string') {
657
664
  try {
658
- r = JSON.parse(data);
665
+ let parsed = JSON.parse(data);
666
+ if (typeof parsed === 'string' && parsed.trim().startsWith('{')) {
667
+ parsed = JSON.parse(parsed);
668
+ }
669
+ if (opt.parsingError && parsed[CoreModels.TaonHttpErrorCustomProp]) {
670
+ return _.merge(new RestErrorResponseWrapper(), parsed);
671
+ }
672
+ return parsed;
659
673
  }
660
674
  catch (e) { }
661
675
  }
@@ -689,7 +703,7 @@ var Models;
689
703
  }
690
704
  get rawJson() {
691
705
  if (!Helpers$1.isBlob(this.responseText)) {
692
- let res = this.toJSON(this.responseText, this.isArray);
706
+ let res = this.toJSON(this.responseText, { isJSONArray: this.isArray });
693
707
  if (this.circular && Array.isArray(this.circular)) {
694
708
  res = JSON10.parse(JSON.stringify(res), this.circular);
695
709
  }
@@ -705,10 +719,12 @@ var Models;
705
719
  return this.entity(); // @LAST
706
720
  }
707
721
  if (this.entity && typeof this.entity === 'object') {
708
- const json = this.toJSON(this.responseText, this.isArray);
722
+ const json = this.toJSON(this.responseText, {
723
+ isJSONArray: this.isArray,
724
+ });
709
725
  return Mapping.encode(json, this.entity, this.circular);
710
726
  }
711
- let res = this.toJSON(this.responseText, this.isArray);
727
+ let res = this.toJSON(this.responseText, { isJSONArray: this.isArray });
712
728
  if (this.circular && Array.isArray(this.circular)) {
713
729
  res = JSON10.parse(JSON.stringify(res), this.circular);
714
730
  }
@@ -732,7 +748,7 @@ var Models;
732
748
  this.data = data;
733
749
  }
734
750
  get json() {
735
- return this.toJSON(this.data);
751
+ return this.toJSON(this.data, { parsingError: true });
736
752
  }
737
753
  get text() {
738
754
  return this.data;
@@ -791,17 +807,6 @@ var Models;
791
807
  }
792
808
  }
793
809
  Models.HttpResponse = HttpResponse;
794
- class HttpResponseError extends BaseResponse {
795
- // public tryRecconect() {
796
- // }
797
- constructor(message, responseText, headers, statusCode, jobid) {
798
- super(responseText, headers, statusCode);
799
- this.message = message;
800
- this.jobid = jobid;
801
- this.body = new ErrorBody(responseText);
802
- }
803
- }
804
- Models.HttpResponseError = HttpResponseError;
805
810
  /* */
806
811
  /* */
807
812
  /* */
@@ -809,6 +814,17 @@ var Models;
809
814
  /* */
810
815
  /* */
811
816
  })(Models || (Models = {}));
817
+ class HttpResponseError extends Models.BaseResponse {
818
+ // public tryRecconect() {
819
+ // }
820
+ constructor(message, responseText, headers, statusCode, jobid, sourceRequest) {
821
+ super(responseText, headers, statusCode);
822
+ this.message = message;
823
+ this.jobid = jobid;
824
+ this.sourceRequest = sourceRequest;
825
+ this.body = new Models.ErrorBody(responseText);
826
+ }
827
+ }
812
828
 
813
829
  class RestHeaders {
814
830
  static from(headers) {
@@ -991,7 +1007,7 @@ class RestRequest {
991
1007
  }
992
1008
  // error no internet
993
1009
  if (res.error) {
994
- this.subjectInuUse[jobid].error(new Models.HttpResponseError(res.error, res.data, res.headers, res.code, jobid));
1010
+ this.subjectInuUse[jobid].error(new HttpResponseError(res.error, res.data, res.headers, res.code, jobid, sourceRequest));
995
1011
  return;
996
1012
  }
997
1013
  const entity = this.meta[jobid].entity;
@@ -1086,6 +1102,7 @@ class RestRequest {
1086
1102
  if (this.subjectInuUse[jobid][isCanceled]) {
1087
1103
  return;
1088
1104
  }
1105
+ // handle normal request
1089
1106
  this.handlerResult({
1090
1107
  res: {
1091
1108
  code: response.status,
@@ -1129,6 +1146,7 @@ class RestRequest {
1129
1146
  const error = catchedError && catchedError.response
1130
1147
  ? `[${catchedError.response.statusText}]: `
1131
1148
  : '';
1149
+ // handle error request
1132
1150
  this.handlerResult({
1133
1151
  res: {
1134
1152
  code: catchedError && catchedError.response
@@ -1279,6 +1297,7 @@ class RestRequest {
1279
1297
  let callbackMethodName = 'cb_' + num;
1280
1298
  let win = globalThis; // TODO not a good idea! @LAST
1281
1299
  win[callbackMethodName] = data => {
1300
+ // handle jsonp result data
1282
1301
  this.handlerResult({
1283
1302
  res: {
1284
1303
  data,
@@ -1779,5 +1798,5 @@ class SimpleResource {
1779
1798
  * Generated bundle index. Do not edit.
1780
1799
  */
1781
1800
 
1782
- export { AxiosBackendHandler, CONTENT_TYPE, Helpers, Mapping, Models, Resource, Rest, RestHeaders, SimpleResource, buildInterceptorChain, interpolateParamsToUrl };
1801
+ export { AxiosBackendHandler, CONTENT_TYPE, Helpers, HttpResponseError, Mapping, Models, Resource, Rest, RestErrorResponseWrapper, RestHeaders, RestResponseWrapper, SimpleResource, buildInterceptorChain, interpolateParamsToUrl };
1783
1802
  //# sourceMappingURL=ng2-rest.mjs.map