ng2-rest 13.2.4 → 13.2.6

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.
Files changed (125) hide show
  1. package/README.md +135 -135
  2. package/assets/shared/shared_folder_info.txt +1 -1
  3. package/browser/README.md +24 -24
  4. package/browser/esm2020/lib/content-type.mjs +12 -12
  5. package/browser/esm2020/lib/cookie.mjs +28 -28
  6. package/browser/esm2020/lib/helpers.mjs +23 -23
  7. package/browser/esm2020/lib/index.mjs +12 -12
  8. package/browser/esm2020/lib/mapping.mjs +238 -238
  9. package/browser/esm2020/lib/models.mjs +160 -165
  10. package/browser/esm2020/lib/other/simple-resource.mjs +116 -116
  11. package/browser/esm2020/lib/params.mjs +278 -278
  12. package/browser/esm2020/lib/request-cache.mjs +100 -100
  13. package/browser/esm2020/lib/resource.service.mjs +213 -213
  14. package/browser/esm2020/lib/rest-headers.mjs +128 -128
  15. package/browser/esm2020/lib/rest-request.mjs +321 -321
  16. package/browser/esm2020/lib/rest.class.mjs +115 -115
  17. package/browser/esm2020/ng2-rest.mjs +4 -4
  18. package/browser/esm2020/public-api.mjs +1 -1
  19. package/browser/fesm2015/ng2-rest.mjs +1677 -1683
  20. package/browser/fesm2015/ng2-rest.mjs.map +1 -1
  21. package/browser/fesm2020/ng2-rest.mjs +1675 -1681
  22. package/browser/fesm2020/ng2-rest.mjs.map +1 -1
  23. package/browser/lib/content-type.d.ts +4 -4
  24. package/browser/lib/cookie.d.ts +7 -7
  25. package/browser/lib/helpers.d.ts +10 -10
  26. package/browser/lib/index.d.ts +9 -9
  27. package/browser/lib/mapping.d.ts +12 -12
  28. package/browser/lib/models.d.ts +157 -157
  29. package/browser/lib/other/simple-resource.d.ts +29 -29
  30. package/browser/lib/params.d.ts +23 -23
  31. package/browser/lib/request-cache.d.ts +17 -17
  32. package/browser/lib/resource.service.d.ts +43 -43
  33. package/browser/lib/rest-headers.d.ts +57 -57
  34. package/browser/lib/rest-request.d.ts +21 -21
  35. package/browser/lib/rest.class.d.ts +36 -36
  36. package/browser/ng2-rest.d.ts +4 -4
  37. package/client/README.md +24 -24
  38. package/client/esm2020/lib/content-type.mjs +12 -12
  39. package/client/esm2020/lib/cookie.mjs +28 -28
  40. package/client/esm2020/lib/helpers.mjs +23 -23
  41. package/client/esm2020/lib/index.mjs +12 -12
  42. package/client/esm2020/lib/mapping.mjs +238 -238
  43. package/client/esm2020/lib/models.mjs +160 -165
  44. package/client/esm2020/lib/other/simple-resource.mjs +116 -116
  45. package/client/esm2020/lib/params.mjs +278 -278
  46. package/client/esm2020/lib/request-cache.mjs +100 -100
  47. package/client/esm2020/lib/resource.service.mjs +213 -213
  48. package/client/esm2020/lib/rest-headers.mjs +128 -128
  49. package/client/esm2020/lib/rest-request.mjs +321 -321
  50. package/client/esm2020/lib/rest.class.mjs +115 -115
  51. package/client/esm2020/ng2-rest.mjs +4 -4
  52. package/client/esm2020/public-api.mjs +1 -1
  53. package/client/fesm2015/ng2-rest.mjs +1677 -1683
  54. package/client/fesm2015/ng2-rest.mjs.map +1 -1
  55. package/client/fesm2020/ng2-rest.mjs +1675 -1681
  56. package/client/fesm2020/ng2-rest.mjs.map +1 -1
  57. package/client/lib/content-type.d.ts +4 -4
  58. package/client/lib/cookie.d.ts +7 -7
  59. package/client/lib/helpers.d.ts +10 -10
  60. package/client/lib/index.d.ts +9 -9
  61. package/client/lib/mapping.d.ts +12 -12
  62. package/client/lib/models.d.ts +157 -157
  63. package/client/lib/other/simple-resource.d.ts +29 -29
  64. package/client/lib/params.d.ts +23 -23
  65. package/client/lib/request-cache.d.ts +17 -17
  66. package/client/lib/resource.service.d.ts +43 -43
  67. package/client/lib/rest-headers.d.ts +57 -57
  68. package/client/lib/rest-request.d.ts +21 -21
  69. package/client/lib/rest.class.d.ts +36 -36
  70. package/client/ng2-rest.d.ts +4 -4
  71. package/client/package.json +44 -44
  72. package/index.d.ts +1 -1
  73. package/lib/content-type.d.ts +5 -5
  74. package/lib/cookie.d.ts +8 -8
  75. package/lib/helpers.d.ts +11 -11
  76. package/lib/index.d.ts +10 -10
  77. package/lib/mapping.d.ts +13 -13
  78. package/lib/models.d.ts +158 -158
  79. package/lib/models.js +5 -12
  80. package/lib/models.js.map +1 -1
  81. package/lib/other/simple-resource.d.ts +30 -30
  82. package/lib/params.d.ts +24 -24
  83. package/lib/request-cache.d.ts +18 -18
  84. package/lib/resource.service.d.ts +44 -44
  85. package/lib/rest-headers.d.ts +58 -58
  86. package/lib/rest-request.d.ts +22 -22
  87. package/lib/rest.class.d.ts +37 -37
  88. package/package.json +5 -238
  89. package/package.json_devDependencies.json +217 -217
  90. package/package.json_tnp.json5 +50 -50
  91. package/tmp-environment.json +48 -48
  92. package/websql/README.md +24 -24
  93. package/websql/esm2020/lib/content-type.mjs +12 -12
  94. package/websql/esm2020/lib/cookie.mjs +28 -28
  95. package/websql/esm2020/lib/helpers.mjs +23 -23
  96. package/websql/esm2020/lib/index.mjs +12 -12
  97. package/websql/esm2020/lib/mapping.mjs +238 -238
  98. package/websql/esm2020/lib/models.mjs +160 -165
  99. package/websql/esm2020/lib/other/simple-resource.mjs +116 -116
  100. package/websql/esm2020/lib/params.mjs +278 -278
  101. package/websql/esm2020/lib/request-cache.mjs +100 -100
  102. package/websql/esm2020/lib/resource.service.mjs +213 -213
  103. package/websql/esm2020/lib/rest-headers.mjs +128 -128
  104. package/websql/esm2020/lib/rest-request.mjs +321 -321
  105. package/websql/esm2020/lib/rest.class.mjs +115 -115
  106. package/websql/esm2020/ng2-rest.mjs +4 -4
  107. package/websql/esm2020/public-api.mjs +1 -1
  108. package/websql/fesm2015/ng2-rest.mjs +1677 -1683
  109. package/websql/fesm2015/ng2-rest.mjs.map +1 -1
  110. package/websql/fesm2020/ng2-rest.mjs +1675 -1681
  111. package/websql/fesm2020/ng2-rest.mjs.map +1 -1
  112. package/websql/lib/content-type.d.ts +4 -4
  113. package/websql/lib/cookie.d.ts +7 -7
  114. package/websql/lib/helpers.d.ts +10 -10
  115. package/websql/lib/index.d.ts +9 -9
  116. package/websql/lib/mapping.d.ts +12 -12
  117. package/websql/lib/models.d.ts +157 -157
  118. package/websql/lib/other/simple-resource.d.ts +29 -29
  119. package/websql/lib/params.d.ts +23 -23
  120. package/websql/lib/request-cache.d.ts +17 -17
  121. package/websql/lib/resource.service.d.ts +43 -43
  122. package/websql/lib/rest-headers.d.ts +57 -57
  123. package/websql/lib/rest-request.d.ts +21 -21
  124. package/websql/lib/rest.class.d.ts +36 -36
  125. package/websql/ng2-rest.d.ts +4 -4
@@ -8,1737 +8,1731 @@ import { JSON10 } from 'json10/browser';
8
8
  import { __awaiter } from 'tslib';
9
9
  import axios from 'axios';
10
10
 
11
- var Mapping;
12
- (function (Mapping) {
13
- function decode(json, autodetect = false) {
14
- if (_.isUndefined(json)) {
15
- return void 0;
16
- }
17
- let mapping = decodeFromDecorator(_.isArray(json) ? _.first(json) : json, !autodetect);
18
- if (autodetect) {
19
- mapping = _.merge(getMappingNaive(json), mapping);
20
- }
21
- return mapping;
22
- }
23
- Mapping.decode = decode;
24
- function encode(json, mapping, circular = []) {
25
- if (_.isString(json) || _.isBoolean(json) || _.isNumber(json)) {
26
- return json;
27
- }
28
- if (mapping['']) {
29
- const decoratorMapping = getModelsMapping(CLASS.getBy(mapping['']));
30
- mapping = _.merge(mapping, decoratorMapping);
31
- }
32
- let res;
33
- if (_.isArray(circular) && circular.length > 0) {
34
- res = setMappingCirc(json, mapping, circular);
35
- }
36
- else {
37
- res = setMapping(json, mapping);
38
- }
39
- return res;
40
- }
41
- Mapping.encode = encode;
42
- function decodeFromDecorator(json, production = false) {
43
- const entityClass = CLASS.getFromObject(json);
44
- const mappings = getModelsMapping(entityClass);
45
- return mappings;
46
- }
47
- function getModelsMapping(entity) {
48
- if (!_.isFunction(entity) || entity === Object) {
49
- return {};
50
- }
51
- const className = CLASS.getName(entity);
52
- let enityOWnMapping = _.isArray(entity[SYMBOL.MODELS_MAPPING]) ?
53
- entity[SYMBOL.MODELS_MAPPING] : [{ '': className }];
54
- let res = {};
55
- let parents = enityOWnMapping
56
- .filter(m => !_.isUndefined(m['']) && m[''] !== className)
57
- .map(m => m['']);
58
- enityOWnMapping.reverse().forEach(m => {
59
- m = _.cloneDeep(m);
60
- Object.keys(m).forEach(key => {
61
- const v = m[key];
62
- const isArr = _.isArray(v);
63
- const model = isArr ? _.first(v) : v;
64
- if (parents.includes(model)) {
65
- m[key] = isArr ? [className] : className;
66
- }
67
- });
68
- res = _.merge(res, m);
69
- });
70
- res[''] = className;
71
- return res;
72
- }
73
- Mapping.getModelsMapping = getModelsMapping;
74
- function add(o, path, mapping = {}) {
75
- if (!o || Array.isArray(o) || typeof o !== 'object')
76
- return;
77
- const objectClassName = CLASS.getName(Object.getPrototypeOf(o).constructor);
78
- const resolveClass = CLASS.getBy(objectClassName);
79
- if (!resolveClass) {
80
- if (objectClassName !== 'Object') {
81
- if (Helpers$1.isBrowser) {
82
- console.error(`Cannot resolve class "${objectClassName}" while mapping.`);
83
- }
84
- }
85
- return;
86
- }
87
- if (!mapping[path])
88
- mapping[path] = CLASS.getName(resolveClass);
89
- ;
90
- }
91
- /**
92
- * USE ONLY IN DEVELOPMENT
93
- * @param c
94
- * @param path
95
- * @param mapping
96
- * @param level
97
- */
98
- function getMappingNaive(c, path = '', mapping = {}, level = 0) {
99
- if (Array.isArray(c)) {
100
- c.forEach(c => getMappingNaive(c, path, mapping, level));
101
- return mapping;
102
- }
103
- if (++level === 16)
104
- return;
105
- add(c, path, mapping);
106
- for (var p in c) {
107
- if (c.hasOwnProperty(p)) {
108
- const v = c[p];
109
- if (Array.isArray(v) && v.length > 0) { // reducer as impovement
110
- v.forEach((elem, i) => {
111
- const currentPaht = [path, p].filter(c => c.trim() != '').join('.');
112
- getMappingNaive(elem, currentPaht, mapping, level);
113
- });
114
- }
115
- else if (typeof v === 'object') {
116
- const currentPaht = [path, p].filter(c => c.trim() != '').join('.');
117
- add(v, currentPaht, mapping);
118
- getMappingNaive(v, currentPaht, mapping, level);
119
- }
120
- }
121
- }
122
- return mapping;
123
- }
124
- function getMappingPathFrom(pathLodhas) {
125
- if (!_.isString(pathLodhas)) {
126
- return void 0;
127
- }
128
- const regex = /\[([0-9a-zA-Z]|\'|\")*\]/g;
129
- pathLodhas = pathLodhas
130
- .replace(regex, '')
131
- .replace('..', '.');
132
- if (pathLodhas.startsWith('.')) {
133
- pathLodhas = pathLodhas.slice(1);
134
- }
135
- return pathLodhas;
136
- }
137
- function setMappingCirc(json, mapping = {}, circular = []) {
138
- const mainClassFn = !_.isArray(json) && CLASS.getBy(mapping['']);
139
- walk.Object(json, (v, lodashPath, changeValue) => {
140
- if (!_.isUndefined(v) && !_.isNull(v)) {
141
- const mappingPath = getMappingPathFrom(lodashPath);
142
- if (!_.isUndefined(mapping[mappingPath])) {
143
- const isArray = _.isArray(mapping[mappingPath]);
144
- if (!isArray) {
145
- const className = isArray ? _.first(mapping[mappingPath]) : mapping[mappingPath];
146
- const classFN = CLASS.getBy(className);
147
- if (_.isFunction(classFN)) {
148
- changeValue(_.merge(new classFN(), v));
149
- }
150
- }
151
- }
152
- }
153
- });
154
- circular.forEach(c => {
155
- const ref = _.get(json, c.circuralTargetPath);
156
- _.set(json, c.pathToObj, ref);
157
- });
158
- if (_.isFunction(mainClassFn)) {
159
- json = _.merge(new mainClassFn(), json);
160
- }
161
- return json;
162
- }
163
- function setMapping(json, mapping = {}) {
164
- if (Array.isArray(json)) {
165
- return json.map(j => {
166
- return setMapping(j, mapping);
167
- });
168
- }
169
- const mainClassFn = CLASS.getBy(mapping['']);
170
- for (const key in json) {
171
- if (json.hasOwnProperty(key)) {
172
- if (_.isArray(json[key])) {
173
- json[key] = json[key].map(arrObj => {
174
- const objMapping = getModelsMapping(CLASS.getBy(mapping[key]));
175
- return setMapping(arrObj, objMapping);
176
- });
177
- }
178
- else if (_.isObject(json[key])) {
179
- const objMapping = getModelsMapping(CLASS.getBy(mapping[key]));
180
- json[key] = setMapping(json[key], objMapping);
181
- }
182
- }
183
- }
184
- Object
185
- .keys(mapping)
186
- .filter(key => key !== '' && key.split('.').length >= 2)
187
- .forEach(lodasPath => {
188
- const objMapping = getModelsMapping(CLASS.getBy(mapping[lodasPath]));
189
- const input = _.get(json, lodasPath);
190
- if (!_.isUndefined(input)) {
191
- const res = setMapping(input, objMapping);
192
- _.set(json, lodasPath, res);
193
- }
194
- });
195
- if (!mainClassFn) {
196
- return json;
197
- }
198
- return _.merge(new mainClassFn(), json);
199
- }
200
- function DefaultModelWithMapping(defaultModelValues, mapping) {
201
- return function (target) {
202
- if (!_.isArray(target[SYMBOL.MODELS_MAPPING])) {
203
- target[SYMBOL.MODELS_MAPPING] = [];
204
- }
205
- target[SYMBOL.MODELS_MAPPING].push({ '': CLASS.getName(target) });
206
- if (_.isObject(mapping)) {
207
- target[SYMBOL.MODELS_MAPPING] = target[SYMBOL.MODELS_MAPPING].concat(mapping);
208
- Object.keys(mapping)
209
- .forEach(key => {
210
- const v = mapping;
211
- if (_.isUndefined(v) || _.isFunction(v)) {
11
+ var Mapping;
12
+ (function (Mapping) {
13
+ function decode(json, autodetect = false) {
14
+ if (_.isUndefined(json)) {
15
+ return void 0;
16
+ }
17
+ let mapping = decodeFromDecorator(_.isArray(json) ? _.first(json) : json, !autodetect);
18
+ if (autodetect) {
19
+ mapping = _.merge(getMappingNaive(json), mapping);
20
+ }
21
+ return mapping;
22
+ }
23
+ Mapping.decode = decode;
24
+ function encode(json, mapping, circular = []) {
25
+ if (_.isString(json) || _.isBoolean(json) || _.isNumber(json)) {
26
+ return json;
27
+ }
28
+ if (mapping['']) {
29
+ const decoratorMapping = getModelsMapping(CLASS.getBy(mapping['']));
30
+ mapping = _.merge(mapping, decoratorMapping);
31
+ }
32
+ let res;
33
+ if (_.isArray(circular) && circular.length > 0) {
34
+ res = setMappingCirc(json, mapping, circular);
35
+ }
36
+ else {
37
+ res = setMapping(json, mapping);
38
+ }
39
+ return res;
40
+ }
41
+ Mapping.encode = encode;
42
+ function decodeFromDecorator(json, production = false) {
43
+ const entityClass = CLASS.getFromObject(json);
44
+ const mappings = getModelsMapping(entityClass);
45
+ return mappings;
46
+ }
47
+ function getModelsMapping(entity) {
48
+ if (!_.isFunction(entity) || entity === Object) {
49
+ return {};
50
+ }
51
+ const className = CLASS.getName(entity);
52
+ let enityOWnMapping = _.isArray(entity[SYMBOL.MODELS_MAPPING]) ?
53
+ entity[SYMBOL.MODELS_MAPPING] : [{ '': className }];
54
+ let res = {};
55
+ let parents = enityOWnMapping
56
+ .filter(m => !_.isUndefined(m['']) && m[''] !== className)
57
+ .map(m => m['']);
58
+ enityOWnMapping.reverse().forEach(m => {
59
+ m = _.cloneDeep(m);
60
+ Object.keys(m).forEach(key => {
61
+ const v = m[key];
62
+ const isArr = _.isArray(v);
63
+ const model = isArr ? _.first(v) : v;
64
+ if (parents.includes(model)) {
65
+ m[key] = isArr ? [className] : className;
66
+ }
67
+ });
68
+ res = _.merge(res, m);
69
+ });
70
+ res[''] = className;
71
+ return res;
72
+ }
73
+ Mapping.getModelsMapping = getModelsMapping;
74
+ function add(o, path, mapping = {}) {
75
+ if (!o || Array.isArray(o) || typeof o !== 'object')
76
+ return;
77
+ const objectClassName = CLASS.getName(Object.getPrototypeOf(o).constructor);
78
+ const resolveClass = CLASS.getBy(objectClassName);
79
+ if (!resolveClass) {
80
+ if (objectClassName !== 'Object') {
81
+ if (Helpers$1.isBrowser) {
82
+ console.error(`Cannot resolve class "${objectClassName}" while mapping.`);
83
+ }
84
+ }
85
+ return;
86
+ }
87
+ if (!mapping[path])
88
+ mapping[path] = CLASS.getName(resolveClass);
89
+ ;
90
+ }
91
+ /**
92
+ * USE ONLY IN DEVELOPMENT
93
+ * @param c
94
+ * @param path
95
+ * @param mapping
96
+ * @param level
97
+ */
98
+ function getMappingNaive(c, path = '', mapping = {}, level = 0) {
99
+ if (Array.isArray(c)) {
100
+ c.forEach(c => getMappingNaive(c, path, mapping, level));
101
+ return mapping;
102
+ }
103
+ if (++level === 16)
104
+ return;
105
+ add(c, path, mapping);
106
+ for (var p in c) {
107
+ if (c.hasOwnProperty(p)) {
108
+ const v = c[p];
109
+ if (Array.isArray(v) && v.length > 0) { // reducer as impovement
110
+ v.forEach((elem, i) => {
111
+ const currentPaht = [path, p].filter(c => c.trim() != '').join('.');
112
+ getMappingNaive(elem, currentPaht, mapping, level);
113
+ });
114
+ }
115
+ else if (typeof v === 'object') {
116
+ const currentPaht = [path, p].filter(c => c.trim() != '').join('.');
117
+ add(v, currentPaht, mapping);
118
+ getMappingNaive(v, currentPaht, mapping, level);
119
+ }
120
+ }
121
+ }
122
+ return mapping;
123
+ }
124
+ function getMappingPathFrom(pathLodhas) {
125
+ if (!_.isString(pathLodhas)) {
126
+ return void 0;
127
+ }
128
+ const regex = /\[([0-9a-zA-Z]|\'|\")*\]/g;
129
+ pathLodhas = pathLodhas
130
+ .replace(regex, '')
131
+ .replace('..', '.');
132
+ if (pathLodhas.startsWith('.')) {
133
+ pathLodhas = pathLodhas.slice(1);
134
+ }
135
+ return pathLodhas;
136
+ }
137
+ function setMappingCirc(json, mapping = {}, circular = []) {
138
+ const mainClassFn = !_.isArray(json) && CLASS.getBy(mapping['']);
139
+ walk.Object(json, (v, lodashPath, changeValue) => {
140
+ if (!_.isUndefined(v) && !_.isNull(v)) {
141
+ const mappingPath = getMappingPathFrom(lodashPath);
142
+ if (!_.isUndefined(mapping[mappingPath])) {
143
+ const isArray = _.isArray(mapping[mappingPath]);
144
+ if (!isArray) {
145
+ const className = isArray ? _.first(mapping[mappingPath]) : mapping[mappingPath];
146
+ const classFN = CLASS.getBy(className);
147
+ if (_.isFunction(classFN)) {
148
+ changeValue(_.merge(new classFN(), v));
149
+ }
150
+ }
151
+ }
152
+ }
153
+ });
154
+ circular.forEach(c => {
155
+ const ref = _.get(json, c.circuralTargetPath);
156
+ _.set(json, c.pathToObj, ref);
157
+ });
158
+ if (_.isFunction(mainClassFn)) {
159
+ json = _.merge(new mainClassFn(), json);
160
+ }
161
+ return json;
162
+ }
163
+ function setMapping(json, mapping = {}) {
164
+ if (Array.isArray(json)) {
165
+ return json.map(j => {
166
+ return setMapping(j, mapping);
167
+ });
168
+ }
169
+ const mainClassFn = CLASS.getBy(mapping['']);
170
+ for (const key in json) {
171
+ if (json.hasOwnProperty(key)) {
172
+ if (_.isArray(json[key])) {
173
+ json[key] = json[key].map(arrObj => {
174
+ const objMapping = getModelsMapping(CLASS.getBy(mapping[key]));
175
+ return setMapping(arrObj, objMapping);
176
+ });
177
+ }
178
+ else if (_.isObject(json[key])) {
179
+ const objMapping = getModelsMapping(CLASS.getBy(mapping[key]));
180
+ json[key] = setMapping(json[key], objMapping);
181
+ }
182
+ }
183
+ }
184
+ Object
185
+ .keys(mapping)
186
+ .filter(key => key !== '' && key.split('.').length >= 2)
187
+ .forEach(lodasPath => {
188
+ const objMapping = getModelsMapping(CLASS.getBy(mapping[lodasPath]));
189
+ const input = _.get(json, lodasPath);
190
+ if (!_.isUndefined(input)) {
191
+ const res = setMapping(input, objMapping);
192
+ _.set(json, lodasPath, res);
193
+ }
194
+ });
195
+ if (!mainClassFn) {
196
+ return json;
197
+ }
198
+ return _.merge(new mainClassFn(), json);
199
+ }
200
+ function DefaultModelWithMapping(defaultModelValues, mapping) {
201
+ return function (target) {
202
+ if (!_.isArray(target[SYMBOL.MODELS_MAPPING])) {
203
+ target[SYMBOL.MODELS_MAPPING] = [];
204
+ }
205
+ target[SYMBOL.MODELS_MAPPING].push({ '': CLASS.getName(target) });
206
+ if (_.isObject(mapping)) {
207
+ target[SYMBOL.MODELS_MAPPING] = target[SYMBOL.MODELS_MAPPING].concat(mapping);
208
+ Object.keys(mapping)
209
+ .forEach(key => {
210
+ const v = mapping;
211
+ if (_.isUndefined(v) || _.isFunction(v)) {
212
212
  throw `
213
213
 
214
214
 
215
215
  Class: '${target.name}'
216
216
  [ng2rest] Bad mapping value for path: ${key} , please use type: <string> or [<string>]
217
- `;
218
- }
219
- });
220
- }
221
- if (_.isObject(defaultModelValues)) {
222
- const toMerge = {};
223
- const describedTarget = CLASS
224
- .describeProperites(target)
225
- .filter(prop => /^([a-zA-Z0-9]|\_|\#)+$/.test(prop));
226
- describedTarget.forEach(propDefInConstr => {
227
- if (defaultModelValues[propDefInConstr]) {
217
+ `;
218
+ }
219
+ });
220
+ }
221
+ if (_.isObject(defaultModelValues)) {
222
+ const toMerge = {};
223
+ const describedTarget = CLASS
224
+ .describeProperites(target)
225
+ .filter(prop => /^([a-zA-Z0-9]|\_|\#)+$/.test(prop));
226
+ describedTarget.forEach(propDefInConstr => {
227
+ if (defaultModelValues[propDefInConstr]) {
228
228
  console.warn(`
229
229
 
230
230
  CONFLICT: default value for property: "${propDefInConstr}"
231
231
  in class "${target.name}" already defined as typescript
232
232
  default class proprty value.
233
233
 
234
- `);
235
- }
236
- else {
237
- toMerge[propDefInConstr] = null; // TODO from toString I can't know that
238
- }
239
- });
240
- target[SYMBOL.DEFAULT_MODEL] = _.merge(toMerge, defaultModelValues);
241
- const propsToOmmit = Object
242
- .keys(target[SYMBOL.DEFAULT_MODEL])
243
- .filter(key => {
244
- const descriptor = Object
245
- .getOwnPropertyDescriptor(target.prototype, key);
246
- return !!descriptor;
247
- });
248
- _.merge(target.prototype, _.omit(target[SYMBOL.DEFAULT_MODEL], propsToOmmit));
249
- }
250
- };
251
- }
252
- Mapping.DefaultModelWithMapping = DefaultModelWithMapping;
253
- })(Mapping || (Mapping = {}));
254
- ;
234
+ `);
235
+ }
236
+ else {
237
+ toMerge[propDefInConstr] = null; // TODO from toString I can't know that
238
+ }
239
+ });
240
+ target[SYMBOL.DEFAULT_MODEL] = _.merge(toMerge, defaultModelValues);
241
+ const propsToOmmit = Object
242
+ .keys(target[SYMBOL.DEFAULT_MODEL])
243
+ .filter(key => {
244
+ const descriptor = Object
245
+ .getOwnPropertyDescriptor(target.prototype, key);
246
+ return !!descriptor;
247
+ });
248
+ _.merge(target.prototype, _.omit(target[SYMBOL.DEFAULT_MODEL], propsToOmmit));
249
+ }
250
+ };
251
+ }
252
+ Mapping.DefaultModelWithMapping = DefaultModelWithMapping;
253
+ })(Mapping || (Mapping = {}));
254
+ ;
255
255
  ({}); // @--end-of-file-for-module=ng2-rest lib/mapping.ts
256
256
 
257
- // @ts-ignore
258
- class Helpers extends CoreHelpers {
259
- static get Mapping() {
260
- return {
261
- encode(json, mapping) {
262
- return Mapping.encode(json, mapping);
263
- },
264
- decode(json, autodetect = false) {
265
- return Mapping.decode(json, autodetect);
266
- }
267
- };
268
- }
269
- static checkValidUrl(url) {
270
- let regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
271
- return regex.test(url);
272
- }
273
- }
274
- Helpers.JSON = JSON10;
275
- ;
257
+ // @ts-ignore
258
+ class Helpers extends CoreHelpers {
259
+ static get Mapping() {
260
+ return {
261
+ encode(json, mapping) {
262
+ return Mapping.encode(json, mapping);
263
+ },
264
+ decode(json, autodetect = false) {
265
+ return Mapping.decode(json, autodetect);
266
+ }
267
+ };
268
+ }
269
+ static checkValidUrl(url) {
270
+ let regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
271
+ return regex.test(url);
272
+ }
273
+ }
274
+ Helpers.JSON = JSON10;
275
+ ;
276
276
  ({}); // @--end-of-file-for-module=ng2-rest lib/helpers.ts
277
277
 
278
- const log$3 = Log.create('[ng2-rest] params', Level.__NOTHING);
279
- /** check if string is a valid pattern */
280
- function isValid(pattern) {
281
- return (new RegExp('\/:[a-zA-Z]*', 'g')).test(pattern.replace('://', ''));
282
- }
283
- function check(url, pattern) {
284
- if (!Helpers.checkValidUrl(url)) {
285
- log$3.error(`Incorrect url: ${url}`);
286
- return false;
287
- }
288
- if (url.charAt(url.length - 1) === '/')
289
- url = url.slice(0, url.length - 2);
290
- if (pattern.charAt(pattern.length - 1) === '/')
291
- pattern = pattern.slice(0, url.length - 2);
292
- pattern = pattern.replace(/\//g, '\/');
293
- pattern = pattern.replace(new RegExp('\/:[a-zA-Z]*', 'g'), '.+');
294
- let reg = new RegExp(pattern, 'g');
295
- return reg.test(url);
296
- }
297
- function getModels(pattern) {
298
- let m = pattern.match(new RegExp('[a-z-A-Z]*\/:', 'g'));
299
- return m.map(p => p.replace('/:', ''));
300
- }
301
- function getRestPramsNames(pattern) {
302
- if (pattern.charAt(pattern.length - 1) !== '/')
303
- pattern = `${pattern}/`;
304
- let m = pattern.match(new RegExp(':[a-zA-Z]*\/', 'g'));
305
- let res = m.map(p => p.replace(':', '').replace('/', ''));
306
- return res.filter(p => p.trim() !== '');
307
- }
308
- function containsModels(url, models) {
309
- if (url.charAt(0) !== '/')
310
- url = '/' + url;
311
- let res = models.filter(m => {
312
- let word = '/' + m;
313
- let iii = url.indexOf(word);
314
- if (iii + word.length < url.length && url.charAt(iii + word.length) !== '/') {
315
- return false;
316
- }
317
- if (iii !== -1) {
318
- url = url.replace(new RegExp('\/' + m, 'g'), '');
319
- return true;
320
- }
321
- return false;
322
- }).length;
323
- return res === models.length;
324
- }
325
- function stars(n) {
326
- let res = '';
327
- for (let i = 0; i < n; i++)
328
- res += '*';
329
- return res;
330
- }
331
- function getRestParams(url, pattern) {
332
- let res = {};
333
- let models = getRestPramsNames(pattern);
334
- models.forEach(m => {
335
- pattern = pattern.replace(`:${m}`, stars(m.length));
336
- });
337
- let currentModel = void 0;
338
- diffChars(pattern, url).forEach(d => {
339
- if (d.added) {
340
- if (!isNaN(Number(d.value)))
341
- res[currentModel] = Number(d.value);
342
- else if (d.value.trim() === 'true')
343
- res[currentModel] = true;
344
- else if (d.value.trim() === 'false')
345
- res[currentModel] = false;
346
- else
347
- res[currentModel] = decodeURIComponent(d.value);
348
- currentModel = void 0;
349
- }
350
- let m = d.value.replace(':', "");
351
- if (d.removed) {
352
- currentModel = models.shift();
353
- }
354
- });
355
- return res;
356
- }
357
- const regexisPath = /[^\..]+(\.[^\..]+)+/g;
358
- /**
359
- * Models like books/:id
360
- */
361
- function cutUrlModel(params, models, output) {
362
- if (models.length === 0)
363
- return output.join('\/');
364
- let m = models.pop();
365
- let param = m.match(/:[a-zA-Z0-9\.]+/)[0].replace(':', '');
366
- const paramIsPath = regexisPath.test(param);
367
- let model = m.match(/[a-zA-Z0-9]+\//)[0].replace('\/', '');
368
- if (params === void 0 ||
369
- (paramIsPath ? _.get(params, param) === void 0 : params[param] === void 0) ||
370
- param === 'undefined') {
371
- output.length = 0;
372
- output.unshift(model);
373
- return cutUrlModel(params, models, output);
374
- }
375
- else {
376
- if (paramIsPath) {
377
- let mrep = m.replace(new RegExp(`:${param}`, 'g'), `${_.get(params, param)}`);
378
- output.unshift(mrep);
379
- return cutUrlModel(params, models, output);
380
- }
381
- else {
382
- let mrep = m.replace(new RegExp(`:${param}`, 'g'), `${params[param]}`);
383
- output.unshift(mrep);
384
- return cutUrlModel(params, models, output);
385
- }
386
- }
387
- }
388
- function interpolateParamsToUrl(params, url) {
389
- const regexInt = /\[\[([^\..]+\.[^\..]+)+\]\]/g;
390
- url = url.split('/').map(p => {
391
- let isParam = p.startsWith(':');
392
- if (isParam) {
393
- let part = p.slice(1);
394
- if (regexInt.test(part)) {
395
- part = part.replace('[[', '');
396
- part = part.replace(']]', '');
397
- }
398
- return `:${part}`;
399
- }
400
- return p;
401
- }).join('/');
402
- let slash = {
403
- start: url.charAt(0) === '\/',
404
- end: url.charAt(url.length - 1) === '\/'
405
- };
406
- let morePramsOnEnd = url.match(/(\/:[a-zA-Z0-9\.]+){2,10}/g);
407
- if (morePramsOnEnd && (Array.isArray(morePramsOnEnd) && morePramsOnEnd.length === 1)) {
408
- let m = morePramsOnEnd[0];
409
- let match = m.match(/\/:[a-zA-Z0-9\.]+/g);
410
- match.forEach(e => {
411
- let c = e.replace('\/:', '');
412
- if (regexisPath.test(c)) {
413
- url = url.replace(e, `/${_.get(params, c)}`);
414
- }
415
- else {
416
- url = url.replace(e, `/${params[c]}`);
417
- }
418
- });
419
- return url;
420
- }
421
- let nestedParams = url.match(/[a-zA-Z0-9]+\/:[a-zA-Z0-9\.]+/g);
422
- if (!nestedParams || (Array.isArray(nestedParams) && nestedParams.length === 0))
423
- return url;
424
- if (!slash.end)
425
- url = `${url}/`;
426
- let addUndefinedForAlone = (!/:[a-zA-Z0-9\.]+\/$/g.test(url) && /[a-zA-Z0-9]+\/$/g.test(url));
427
- let replace = (nestedParams.length > 1 ? nestedParams.join('\/') : nestedParams[0]) +
428
- (addUndefinedForAlone ? '\/' + url.match(/[a-zA-Z0-9]+\/$/g)[0] : '\/');
429
- let beginHref = url.replace(replace, '');
430
- if (addUndefinedForAlone) {
431
- url = url.replace(/\/$/g, '/:undefined');
432
- nestedParams = url.match(/[a-zA-Z0-9]+\/:[a-zA-Z0-9\.]+/g);
433
- url = cutUrlModel(params, nestedParams, []);
434
- }
435
- else {
436
- url = cutUrlModel(params, nestedParams, []);
437
- }
438
- url = beginHref + url;
439
- if (url.charAt(url.length - 1) !== '/' && slash.end)
440
- url = `${url}/`;
441
- if (url.charAt(0) !== '\/' && slash.start)
442
- url = `/${url}`;
443
- return url;
444
- }
445
- /**
446
- * Get query params from url, like 'ex' in /api/books?ex=value
447
- */
448
- function decodeUrl(url) {
449
- let regex = /[?&]([^=#]+)=([^&#]*)/g, params = {}, match;
450
- while (match = regex.exec(url)) {
451
- params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
452
- }
453
- let paramsObject = params;
454
- for (let p in paramsObject) {
455
- if (paramsObject[p] === void 0) {
456
- delete paramsObject[p];
457
- continue;
458
- }
459
- if (paramsObject.hasOwnProperty(p)) {
460
- let n = Number(params[p]);
461
- if (!isNaN(n)) {
462
- params[p] = n;
463
- continue;
464
- }
465
- if (typeof params[p] === 'string') {
466
- let json;
467
- try {
468
- json = JSON.parse(params[p]);
469
- }
470
- catch (error) { }
471
- if (json !== void 0) {
472
- params[p] = json;
473
- continue;
474
- }
475
- }
476
- }
477
- }
478
- return params;
479
- }
480
- /**
481
- * Create query params string for url
482
- *
483
- * @export
484
- * @param {UrlParams[]} params
485
- * @returns {string}
486
- */
487
- function getParamsUrl(params, doNotSerialize = false) {
488
- let urlparts = [];
489
- if (!params)
490
- return '';
491
- if (!(params instanceof Array))
492
- return '';
493
- if (params.length === 0)
494
- return '';
495
- params.forEach(urlparam => {
496
- if (JSON.stringify(urlparam) !== '{}') {
497
- let parameters = [];
498
- let paramObject = urlparam;
499
- for (let p in paramObject) {
500
- if (paramObject[p] === void 0)
501
- delete paramObject[p];
502
- if (paramObject.hasOwnProperty(p) && typeof p === 'string' && p !== 'regex' && !(paramObject[p] instanceof RegExp)) {
503
- if (p.length > 0 && p[0] === '/') {
504
- let newName = p.slice(1, p.length - 1);
505
- urlparam[newName] = urlparam[p];
506
- urlparam[p] = void 0;
507
- p = newName;
508
- }
509
- if (p.length > 0 && p[p.length - 1] === '/') {
510
- let newName = p.slice(0, p.length - 2);
511
- urlparam[newName] = urlparam[p];
512
- urlparam[p] = void 0;
513
- p = newName;
514
- }
515
- let v = urlparam[p];
516
- if (v instanceof Object) {
517
- urlparam[p] = JSON.stringify(urlparam[p]);
518
- }
519
- urlparam[p] = doNotSerialize ? urlparam[p] : encodeURIComponent(urlparam[p]);
520
- if (urlparam.regex !== void 0 && urlparam.regex instanceof RegExp) {
521
- if (!urlparam.regex.test(urlparam[p])) {
522
- console.warn(`Data: ${urlparam[p]} incostistent with regex ${urlparam.regex.source}`);
523
- }
524
- }
525
- parameters.push(`${p}=${urlparam[p]}`);
526
- }
527
- }
528
- urlparts.push(parameters.join('&'));
529
- }
530
- });
531
- let join = urlparts.join().trim();
532
- if (join.trim() === '')
533
- return '';
534
- return `?${urlparts.join('&')}`;
535
- }
536
- function transform(o) {
537
- if (typeof o === 'object') {
538
- return encodeURIComponent(JSON.stringify(o));
539
- }
540
- return o;
541
- }
542
- function prepareUrlOldWay(params) {
543
- if (!params)
544
- return this.endpoint;
545
- if (typeof params === 'object') {
546
- params = transform(params);
547
- }
548
- return this.endpoint + '/' + params;
549
- }
550
- ;
278
+ const log$3 = Log.create('[ng2-rest] params', Level.__NOTHING);
279
+ /** check if string is a valid pattern */
280
+ function isValid(pattern) {
281
+ return (new RegExp('\/:[a-zA-Z]*', 'g')).test(pattern.replace('://', ''));
282
+ }
283
+ function check(url, pattern) {
284
+ if (!Helpers.checkValidUrl(url)) {
285
+ log$3.error(`Incorrect url: ${url}`);
286
+ return false;
287
+ }
288
+ if (url.charAt(url.length - 1) === '/')
289
+ url = url.slice(0, url.length - 2);
290
+ if (pattern.charAt(pattern.length - 1) === '/')
291
+ pattern = pattern.slice(0, url.length - 2);
292
+ pattern = pattern.replace(/\//g, '\/');
293
+ pattern = pattern.replace(new RegExp('\/:[a-zA-Z]*', 'g'), '.+');
294
+ let reg = new RegExp(pattern, 'g');
295
+ return reg.test(url);
296
+ }
297
+ function getModels(pattern) {
298
+ let m = pattern.match(new RegExp('[a-z-A-Z]*\/:', 'g'));
299
+ return m.map(p => p.replace('/:', ''));
300
+ }
301
+ function getRestPramsNames(pattern) {
302
+ if (pattern.charAt(pattern.length - 1) !== '/')
303
+ pattern = `${pattern}/`;
304
+ let m = pattern.match(new RegExp(':[a-zA-Z]*\/', 'g'));
305
+ let res = m.map(p => p.replace(':', '').replace('/', ''));
306
+ return res.filter(p => p.trim() !== '');
307
+ }
308
+ function containsModels(url, models) {
309
+ if (url.charAt(0) !== '/')
310
+ url = '/' + url;
311
+ let res = models.filter(m => {
312
+ let word = '/' + m;
313
+ let iii = url.indexOf(word);
314
+ if (iii + word.length < url.length && url.charAt(iii + word.length) !== '/') {
315
+ return false;
316
+ }
317
+ if (iii !== -1) {
318
+ url = url.replace(new RegExp('\/' + m, 'g'), '');
319
+ return true;
320
+ }
321
+ return false;
322
+ }).length;
323
+ return res === models.length;
324
+ }
325
+ function stars(n) {
326
+ let res = '';
327
+ for (let i = 0; i < n; i++)
328
+ res += '*';
329
+ return res;
330
+ }
331
+ function getRestParams(url, pattern) {
332
+ let res = {};
333
+ let models = getRestPramsNames(pattern);
334
+ models.forEach(m => {
335
+ pattern = pattern.replace(`:${m}`, stars(m.length));
336
+ });
337
+ let currentModel = void 0;
338
+ diffChars(pattern, url).forEach(d => {
339
+ if (d.added) {
340
+ if (!isNaN(Number(d.value)))
341
+ res[currentModel] = Number(d.value);
342
+ else if (d.value.trim() === 'true')
343
+ res[currentModel] = true;
344
+ else if (d.value.trim() === 'false')
345
+ res[currentModel] = false;
346
+ else
347
+ res[currentModel] = decodeURIComponent(d.value);
348
+ currentModel = void 0;
349
+ }
350
+ let m = d.value.replace(':', "");
351
+ if (d.removed) {
352
+ currentModel = models.shift();
353
+ }
354
+ });
355
+ return res;
356
+ }
357
+ const regexisPath = /[^\..]+(\.[^\..]+)+/g;
358
+ /**
359
+ * Models like books/:id
360
+ */
361
+ function cutUrlModel(params, models, output) {
362
+ if (models.length === 0)
363
+ return output.join('\/');
364
+ let m = models.pop();
365
+ let param = m.match(/:[a-zA-Z0-9\.]+/)[0].replace(':', '');
366
+ const paramIsPath = regexisPath.test(param);
367
+ let model = m.match(/[a-zA-Z0-9]+\//)[0].replace('\/', '');
368
+ if (params === void 0 ||
369
+ (paramIsPath ? _.get(params, param) === void 0 : params[param] === void 0) ||
370
+ param === 'undefined') {
371
+ output.length = 0;
372
+ output.unshift(model);
373
+ return cutUrlModel(params, models, output);
374
+ }
375
+ else {
376
+ if (paramIsPath) {
377
+ let mrep = m.replace(new RegExp(`:${param}`, 'g'), `${_.get(params, param)}`);
378
+ output.unshift(mrep);
379
+ return cutUrlModel(params, models, output);
380
+ }
381
+ else {
382
+ let mrep = m.replace(new RegExp(`:${param}`, 'g'), `${params[param]}`);
383
+ output.unshift(mrep);
384
+ return cutUrlModel(params, models, output);
385
+ }
386
+ }
387
+ }
388
+ function interpolateParamsToUrl(params, url) {
389
+ const regexInt = /\[\[([^\..]+\.[^\..]+)+\]\]/g;
390
+ url = url.split('/').map(p => {
391
+ let isParam = p.startsWith(':');
392
+ if (isParam) {
393
+ let part = p.slice(1);
394
+ if (regexInt.test(part)) {
395
+ part = part.replace('[[', '');
396
+ part = part.replace(']]', '');
397
+ }
398
+ return `:${part}`;
399
+ }
400
+ return p;
401
+ }).join('/');
402
+ let slash = {
403
+ start: url.charAt(0) === '\/',
404
+ end: url.charAt(url.length - 1) === '\/'
405
+ };
406
+ let morePramsOnEnd = url.match(/(\/:[a-zA-Z0-9\.]+){2,10}/g);
407
+ if (morePramsOnEnd && (Array.isArray(morePramsOnEnd) && morePramsOnEnd.length === 1)) {
408
+ let m = morePramsOnEnd[0];
409
+ let match = m.match(/\/:[a-zA-Z0-9\.]+/g);
410
+ match.forEach(e => {
411
+ let c = e.replace('\/:', '');
412
+ if (regexisPath.test(c)) {
413
+ url = url.replace(e, `/${_.get(params, c)}`);
414
+ }
415
+ else {
416
+ url = url.replace(e, `/${params[c]}`);
417
+ }
418
+ });
419
+ return url;
420
+ }
421
+ let nestedParams = url.match(/[a-zA-Z0-9]+\/:[a-zA-Z0-9\.]+/g);
422
+ if (!nestedParams || (Array.isArray(nestedParams) && nestedParams.length === 0))
423
+ return url;
424
+ if (!slash.end)
425
+ url = `${url}/`;
426
+ let addUndefinedForAlone = (!/:[a-zA-Z0-9\.]+\/$/g.test(url) && /[a-zA-Z0-9]+\/$/g.test(url));
427
+ let replace = (nestedParams.length > 1 ? nestedParams.join('\/') : nestedParams[0]) +
428
+ (addUndefinedForAlone ? '\/' + url.match(/[a-zA-Z0-9]+\/$/g)[0] : '\/');
429
+ let beginHref = url.replace(replace, '');
430
+ if (addUndefinedForAlone) {
431
+ url = url.replace(/\/$/g, '/:undefined');
432
+ nestedParams = url.match(/[a-zA-Z0-9]+\/:[a-zA-Z0-9\.]+/g);
433
+ url = cutUrlModel(params, nestedParams, []);
434
+ }
435
+ else {
436
+ url = cutUrlModel(params, nestedParams, []);
437
+ }
438
+ url = beginHref + url;
439
+ if (url.charAt(url.length - 1) !== '/' && slash.end)
440
+ url = `${url}/`;
441
+ if (url.charAt(0) !== '\/' && slash.start)
442
+ url = `/${url}`;
443
+ return url;
444
+ }
445
+ /**
446
+ * Get query params from url, like 'ex' in /api/books?ex=value
447
+ */
448
+ function decodeUrl(url) {
449
+ let regex = /[?&]([^=#]+)=([^&#]*)/g, params = {}, match;
450
+ while (match = regex.exec(url)) {
451
+ params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
452
+ }
453
+ let paramsObject = params;
454
+ for (let p in paramsObject) {
455
+ if (paramsObject[p] === void 0) {
456
+ delete paramsObject[p];
457
+ continue;
458
+ }
459
+ if (paramsObject.hasOwnProperty(p)) {
460
+ let n = Number(params[p]);
461
+ if (!isNaN(n)) {
462
+ params[p] = n;
463
+ continue;
464
+ }
465
+ if (typeof params[p] === 'string') {
466
+ let json;
467
+ try {
468
+ json = JSON.parse(params[p]);
469
+ }
470
+ catch (error) { }
471
+ if (json !== void 0) {
472
+ params[p] = json;
473
+ continue;
474
+ }
475
+ }
476
+ }
477
+ }
478
+ return params;
479
+ }
480
+ /**
481
+ * Create query params string for url
482
+ *
483
+ * @export
484
+ * @param {UrlParams[]} params
485
+ * @returns {string}
486
+ */
487
+ function getParamsUrl(params, doNotSerialize = false) {
488
+ let urlparts = [];
489
+ if (!params)
490
+ return '';
491
+ if (!(params instanceof Array))
492
+ return '';
493
+ if (params.length === 0)
494
+ return '';
495
+ params.forEach(urlparam => {
496
+ if (JSON.stringify(urlparam) !== '{}') {
497
+ let parameters = [];
498
+ let paramObject = urlparam;
499
+ for (let p in paramObject) {
500
+ if (paramObject[p] === void 0)
501
+ delete paramObject[p];
502
+ if (paramObject.hasOwnProperty(p) && typeof p === 'string' && p !== 'regex' && !(paramObject[p] instanceof RegExp)) {
503
+ if (p.length > 0 && p[0] === '/') {
504
+ let newName = p.slice(1, p.length - 1);
505
+ urlparam[newName] = urlparam[p];
506
+ urlparam[p] = void 0;
507
+ p = newName;
508
+ }
509
+ if (p.length > 0 && p[p.length - 1] === '/') {
510
+ let newName = p.slice(0, p.length - 2);
511
+ urlparam[newName] = urlparam[p];
512
+ urlparam[p] = void 0;
513
+ p = newName;
514
+ }
515
+ let v = urlparam[p];
516
+ if (v instanceof Object) {
517
+ urlparam[p] = JSON.stringify(urlparam[p]);
518
+ }
519
+ urlparam[p] = doNotSerialize ? urlparam[p] : encodeURIComponent(urlparam[p]);
520
+ if (urlparam.regex !== void 0 && urlparam.regex instanceof RegExp) {
521
+ if (!urlparam.regex.test(urlparam[p])) {
522
+ console.warn(`Data: ${urlparam[p]} incostistent with regex ${urlparam.regex.source}`);
523
+ }
524
+ }
525
+ parameters.push(`${p}=${urlparam[p]}`);
526
+ }
527
+ }
528
+ urlparts.push(parameters.join('&'));
529
+ }
530
+ });
531
+ let join = urlparts.join().trim();
532
+ if (join.trim() === '')
533
+ return '';
534
+ return `?${urlparts.join('&')}`;
535
+ }
536
+ function transform(o) {
537
+ if (typeof o === 'object') {
538
+ return encodeURIComponent(JSON.stringify(o));
539
+ }
540
+ return o;
541
+ }
542
+ function prepareUrlOldWay(params) {
543
+ if (!params)
544
+ return this.endpoint;
545
+ if (typeof params === 'object') {
546
+ params = transform(params);
547
+ }
548
+ return this.endpoint + '/' + params;
549
+ }
550
+ ;
551
551
  ({}); // @--end-of-file-for-module=ng2-rest lib/params.ts
552
552
 
553
- class RestHeaders {
554
- constructor(headers) {
555
- /** @internal header names are lower case */
556
- this._headers = new Map();
557
- /** @internal map lower case names to actual names */
558
- this._normalizedNames = new Map();
559
- if (headers instanceof RestHeaders) {
560
- headers.forEach((values, name) => {
561
- values.forEach(value => this.set(name, value));
562
- });
563
- }
564
- else {
565
- Object.keys(headers).forEach((name) => {
566
- const values = (Array.isArray(headers[name]) ? headers[name] : [headers[name]]);
567
- this.delete(name);
568
- values.forEach(value => this.set(name, value));
569
- });
570
- }
571
- }
572
- static from(headers) {
573
- if (!headers) {
574
- return void 0;
575
- }
576
- return new RestHeaders(headers);
577
- }
578
- /**
579
- * Returns a new RestHeaders instance from the given DOMString of Response RestHeaders
580
- */
581
- static fromResponseHeaderString(headersString) {
582
- const headers = new RestHeaders();
583
- headersString.split('\n').forEach(line => {
584
- const index = line.indexOf(':');
585
- if (index > 0) {
586
- const name = line.slice(0, index);
587
- const value = line.slice(index + 1).trim();
588
- headers.set(name, value);
589
- }
590
- });
591
- return headers;
592
- }
593
- /**
594
- * Appends a header to existing list of header values for a given header name.
595
- */
596
- append(name, value) {
597
- const values = this.getAll(name);
598
- if (values === null) {
599
- this.set(name, value);
600
- }
601
- else {
602
- values.push(value);
603
- }
604
- }
605
- /**
606
- * Deletes all header values for the given name.
607
- */
608
- delete(name) {
609
- const lcName = name.toLowerCase();
610
- this._normalizedNames.delete(lcName);
611
- this._headers.delete(lcName);
612
- }
613
- forEach(fn) {
614
- this._headers.forEach((values, lcName) => fn(values, this._normalizedNames.get(lcName), this._headers));
615
- }
616
- /**
617
- * Returns first header that matches given name.
618
- */
619
- get(name) {
620
- const values = this.getAll(name);
621
- if (values === null) {
622
- return null;
623
- }
624
- return values.length > 0 ? values[0] : null;
625
- }
626
- /**
627
- * Checks for existence of header by given name.
628
- */
629
- has(name) { return this._headers.has(name.toLowerCase()); }
630
- /**
631
- * Returns the names of the headers
632
- */
633
- keys() { return Array.from(this._normalizedNames.values()); }
634
- /**
635
- * Sets or overrides header value for given name.
636
- */
637
- set(name, value) {
638
- if (Array.isArray(value)) {
639
- if (value.length) {
640
- this._headers.set(name.toLowerCase(), [value.join(',')]);
641
- }
642
- }
643
- else {
644
- this._headers.set(name.toLowerCase(), [value]);
645
- }
646
- this.mayBeSetNormalizedName(name);
647
- }
648
- /**
649
- * Returns values of all headers.
650
- */
651
- values() { return Array.from(this._headers.values()); }
652
- /**
653
- * Returns string of all headers.
654
- */
655
- toJSON() {
656
- const serialized = {};
657
- if (!this._headers) {
658
- }
659
- this._headers.forEach((values, name) => {
660
- const split = [];
661
- values.forEach(v => split.push(...v.split(',')));
662
- serialized[this._normalizedNames.get(name)] = split;
663
- });
664
- return serialized;
665
- }
666
- /**
667
- * Returns list of header values for a given name.
668
- */
669
- getAll(name) {
670
- return this.has(name) ? this._headers.get(name.toLowerCase()) : null;
671
- }
672
- mayBeSetNormalizedName(name) {
673
- const lcName = name.toLowerCase();
674
- if (!this._normalizedNames.has(lcName)) {
675
- this._normalizedNames.set(lcName, name);
676
- }
677
- }
678
- }
679
- ;
553
+ class RestHeaders {
554
+ constructor(headers) {
555
+ /** @internal header names are lower case */
556
+ this._headers = new Map();
557
+ /** @internal map lower case names to actual names */
558
+ this._normalizedNames = new Map();
559
+ if (headers instanceof RestHeaders) {
560
+ headers.forEach((values, name) => {
561
+ values.forEach(value => this.set(name, value));
562
+ });
563
+ }
564
+ else {
565
+ Object.keys(headers).forEach((name) => {
566
+ const values = (Array.isArray(headers[name]) ? headers[name] : [headers[name]]);
567
+ this.delete(name);
568
+ values.forEach(value => this.set(name, value));
569
+ });
570
+ }
571
+ }
572
+ static from(headers) {
573
+ if (!headers) {
574
+ return void 0;
575
+ }
576
+ return new RestHeaders(headers);
577
+ }
578
+ /**
579
+ * Returns a new RestHeaders instance from the given DOMString of Response RestHeaders
580
+ */
581
+ static fromResponseHeaderString(headersString) {
582
+ const headers = new RestHeaders();
583
+ headersString.split('\n').forEach(line => {
584
+ const index = line.indexOf(':');
585
+ if (index > 0) {
586
+ const name = line.slice(0, index);
587
+ const value = line.slice(index + 1).trim();
588
+ headers.set(name, value);
589
+ }
590
+ });
591
+ return headers;
592
+ }
593
+ /**
594
+ * Appends a header to existing list of header values for a given header name.
595
+ */
596
+ append(name, value) {
597
+ const values = this.getAll(name);
598
+ if (values === null) {
599
+ this.set(name, value);
600
+ }
601
+ else {
602
+ values.push(value);
603
+ }
604
+ }
605
+ /**
606
+ * Deletes all header values for the given name.
607
+ */
608
+ delete(name) {
609
+ const lcName = name.toLowerCase();
610
+ this._normalizedNames.delete(lcName);
611
+ this._headers.delete(lcName);
612
+ }
613
+ forEach(fn) {
614
+ this._headers.forEach((values, lcName) => fn(values, this._normalizedNames.get(lcName), this._headers));
615
+ }
616
+ /**
617
+ * Returns first header that matches given name.
618
+ */
619
+ get(name) {
620
+ const values = this.getAll(name);
621
+ if (values === null) {
622
+ return null;
623
+ }
624
+ return values.length > 0 ? values[0] : null;
625
+ }
626
+ /**
627
+ * Checks for existence of header by given name.
628
+ */
629
+ has(name) { return this._headers.has(name.toLowerCase()); }
630
+ /**
631
+ * Returns the names of the headers
632
+ */
633
+ keys() { return Array.from(this._normalizedNames.values()); }
634
+ /**
635
+ * Sets or overrides header value for given name.
636
+ */
637
+ set(name, value) {
638
+ if (Array.isArray(value)) {
639
+ if (value.length) {
640
+ this._headers.set(name.toLowerCase(), [value.join(',')]);
641
+ }
642
+ }
643
+ else {
644
+ this._headers.set(name.toLowerCase(), [value]);
645
+ }
646
+ this.mayBeSetNormalizedName(name);
647
+ }
648
+ /**
649
+ * Returns values of all headers.
650
+ */
651
+ values() { return Array.from(this._headers.values()); }
652
+ /**
653
+ * Returns string of all headers.
654
+ */
655
+ toJSON() {
656
+ const serialized = {};
657
+ if (!this._headers) {
658
+ }
659
+ this._headers.forEach((values, name) => {
660
+ const split = [];
661
+ values.forEach(v => split.push(...v.split(',')));
662
+ serialized[this._normalizedNames.get(name)] = split;
663
+ });
664
+ return serialized;
665
+ }
666
+ /**
667
+ * Returns list of header values for a given name.
668
+ */
669
+ getAll(name) {
670
+ return this.has(name) ? this._headers.get(name.toLowerCase()) : null;
671
+ }
672
+ mayBeSetNormalizedName(name) {
673
+ const lcName = name.toLowerCase();
674
+ if (!this._normalizedNames.has(lcName)) {
675
+ this._normalizedNames.set(lcName, name);
676
+ }
677
+ }
678
+ }
679
+ ;
680
680
  ({}); // @--end-of-file-for-module=ng2-rest lib/rest-headers.ts
681
681
 
682
- const CONTENT_TYPE = {
683
- APPLICATION_JSON: RestHeaders.from({
684
- 'Content-Type': 'application/json',
685
- 'Accept': 'application/json'
686
- }),
687
- APPLICATINO_VND_API_JSON: RestHeaders.from({
688
- 'Content-Type': 'application/vnd.api+json',
689
- 'Accept': 'application/vnd.api+json'
690
- }),
691
- };
682
+ const CONTENT_TYPE = {
683
+ APPLICATION_JSON: RestHeaders.from({
684
+ 'Content-Type': 'application/json',
685
+ 'Accept': 'application/json'
686
+ }),
687
+ APPLICATINO_VND_API_JSON: RestHeaders.from({
688
+ 'Content-Type': 'application/vnd.api+json',
689
+ 'Accept': 'application/vnd.api+json'
690
+ }),
691
+ };
692
692
  ({}); // @--end-of-file-for-module=ng2-rest lib/content-type.ts
693
693
 
694
- class Rest {
695
- constructor(endpoint, request, meta, customContentType) {
696
- this.request = request;
697
- this.meta = meta;
698
- this.customContentType = customContentType;
699
- this._headers = RestHeaders.from(CONTENT_TYPE.APPLICATION_JSON);
700
- this.array = {
701
- get: (params = void 0, doNotSerializeParams) => {
702
- return this.req('get', void 0, params, doNotSerializeParams, true);
703
- },
704
- head: (params = void 0, doNotSerializeParams) => {
705
- return this.req('head', void 0, params, doNotSerializeParams, true);
706
- },
707
- post: (item, params, doNotSerializeParams) => {
708
- return this.req('post', item, params, doNotSerializeParams, true);
709
- },
710
- put: (item, params, doNotSerializeParams) => {
711
- return this.req('put', item, params, doNotSerializeParams, true);
712
- },
713
- patch: (item, params, doNotSerializeParams) => {
714
- return this.req('patch', item, params, doNotSerializeParams, true);
715
- },
716
- delete: (params, doNotSerializeParams) => {
717
- return this.req('delete', void 0, params, doNotSerializeParams, true);
718
- },
719
- jsonp: (params, doNotSerializeParams) => {
720
- return this.req('jsonp', void 0, params, doNotSerializeParams, true);
721
- }
722
- };
723
- this.__meta_endpoint = endpoint;
724
- }
725
- mock(mock) {
726
- if ((typeof mock === 'function') || (typeof mock === 'object')) {
727
- this.mockHttp = mock;
728
- }
729
- else {
694
+ class Rest {
695
+ constructor(endpoint, request, meta, customContentType) {
696
+ this.request = request;
697
+ this.meta = meta;
698
+ this.customContentType = customContentType;
699
+ this._headers = RestHeaders.from(CONTENT_TYPE.APPLICATION_JSON);
700
+ this.array = {
701
+ get: (params = void 0, doNotSerializeParams) => {
702
+ return this.req('get', void 0, params, doNotSerializeParams, true);
703
+ },
704
+ head: (params = void 0, doNotSerializeParams) => {
705
+ return this.req('head', void 0, params, doNotSerializeParams, true);
706
+ },
707
+ post: (item, params, doNotSerializeParams) => {
708
+ return this.req('post', item, params, doNotSerializeParams, true);
709
+ },
710
+ put: (item, params, doNotSerializeParams) => {
711
+ return this.req('put', item, params, doNotSerializeParams, true);
712
+ },
713
+ patch: (item, params, doNotSerializeParams) => {
714
+ return this.req('patch', item, params, doNotSerializeParams, true);
715
+ },
716
+ delete: (params, doNotSerializeParams) => {
717
+ return this.req('delete', void 0, params, doNotSerializeParams, true);
718
+ },
719
+ jsonp: (params, doNotSerializeParams) => {
720
+ return this.req('jsonp', void 0, params, doNotSerializeParams, true);
721
+ }
722
+ };
723
+ this.__meta_endpoint = endpoint;
724
+ }
725
+ mock(mock) {
726
+ if ((typeof mock === 'function') || (typeof mock === 'object')) {
727
+ this.mockHttp = mock;
728
+ }
729
+ else {
730
730
  throw `[ng2-rest]
731
731
  .model(...)
732
732
  .mock( < BAD MOCK DATA > )
733
733
  ...
734
- `;
735
- }
736
- return this;
737
- }
738
- get endpoint() {
739
- let e = this.__meta_endpoint;
740
- if (this.restQueryParams !== void 0 && this._endpointRest !== void 0
741
- && typeof this._endpointRest === 'string' && this._endpointRest.trim() !== '')
742
- e = this._endpointRest;
743
- return e;
744
- }
745
- set __rest_endpoint(endpoint) {
746
- this._endpointRest = endpoint;
747
- if (endpoint === void 0) {
748
- this.restQueryParams = void 0;
749
- }
750
- else {
751
- this.restQueryParams = getRestParams(endpoint, this.__meta_endpoint);
752
- }
753
- }
754
- creatUrl(params, doNotSerializeParams = false) {
755
- return `${this.endpoint}${getParamsUrl(params, doNotSerializeParams)}`;
756
- }
757
- get headers() {
758
- return this._headers;
759
- }
760
- req(method, requestBody, params, doNotSerializeParams = false, isArray = false) {
761
- const modelUrl = this.creatUrl(params, doNotSerializeParams);
762
- const body = (CLASS.getNameFromObject(requestBody) === 'FormData')
763
- ? requestBody
764
- : (requestBody ? JSON.stringify(requestBody) : void 0);
765
- if (this.customContentType) {
766
- const customHeaderKeys = this.customContentType.keys();
767
- const currentHeaderKeys = this._headers.keys();
768
- currentHeaderKeys
769
- .filter(key => !customHeaderKeys.includes(key))
770
- .forEach(key => {
771
- this.customContentType.set(key, this._headers.get(key));
772
- });
773
- this._headers = this.customContentType;
774
- }
775
- else {
776
- this._headers = RestHeaders.from(CONTENT_TYPE.APPLICATION_JSON);
777
- }
778
- const result = this.request[method.toLowerCase()](modelUrl, body, this.headers, this.meta, isArray, this.mockHttp);
779
- this.mockHttp = void 0;
780
- return result;
781
- }
782
- replay(method) {
783
- this.request.replay(method, this.meta);
784
- }
785
- get(params, doNotSerializeParams = false) {
786
- return this.req('get', void 0, params, doNotSerializeParams);
787
- }
788
- head(params, doNotSerializeParams = false) {
789
- return this.req('head', void 0, params, doNotSerializeParams);
790
- }
791
- post(item, params, doNotSerializeParams = false) {
792
- return this.req('post', item, params, doNotSerializeParams);
793
- }
794
- put(item, params, doNotSerializeParams = false) {
795
- return this.req('put', item, params, doNotSerializeParams);
796
- }
797
- patch(item, params, doNotSerializeParams = false) {
798
- return this.req('patch', item, params, doNotSerializeParams);
799
- }
800
- delete(params, doNotSerializeParams = false) {
801
- return this.req('delete', void 0, params, doNotSerializeParams);
802
- }
803
- jsonp(params, doNotSerializeParams = false) {
804
- return this.req('jsonp', void 0, params, doNotSerializeParams);
805
- }
806
- }
807
- ;
734
+ `;
735
+ }
736
+ return this;
737
+ }
738
+ get endpoint() {
739
+ let e = this.__meta_endpoint;
740
+ if (this.restQueryParams !== void 0 && this._endpointRest !== void 0
741
+ && typeof this._endpointRest === 'string' && this._endpointRest.trim() !== '')
742
+ e = this._endpointRest;
743
+ return e;
744
+ }
745
+ set __rest_endpoint(endpoint) {
746
+ this._endpointRest = endpoint;
747
+ if (endpoint === void 0) {
748
+ this.restQueryParams = void 0;
749
+ }
750
+ else {
751
+ this.restQueryParams = getRestParams(endpoint, this.__meta_endpoint);
752
+ }
753
+ }
754
+ creatUrl(params, doNotSerializeParams = false) {
755
+ return `${this.endpoint}${getParamsUrl(params, doNotSerializeParams)}`;
756
+ }
757
+ get headers() {
758
+ return this._headers;
759
+ }
760
+ req(method, requestBody, params, doNotSerializeParams = false, isArray = false) {
761
+ const modelUrl = this.creatUrl(params, doNotSerializeParams);
762
+ const body = (CLASS.getNameFromObject(requestBody) === 'FormData')
763
+ ? requestBody
764
+ : (requestBody ? JSON.stringify(requestBody) : void 0);
765
+ if (this.customContentType) {
766
+ const customHeaderKeys = this.customContentType.keys();
767
+ const currentHeaderKeys = this._headers.keys();
768
+ currentHeaderKeys
769
+ .filter(key => !customHeaderKeys.includes(key))
770
+ .forEach(key => {
771
+ this.customContentType.set(key, this._headers.get(key));
772
+ });
773
+ this._headers = this.customContentType;
774
+ }
775
+ else {
776
+ this._headers = RestHeaders.from(CONTENT_TYPE.APPLICATION_JSON);
777
+ }
778
+ const result = this.request[method.toLowerCase()](modelUrl, body, this.headers, this.meta, isArray, this.mockHttp);
779
+ this.mockHttp = void 0;
780
+ return result;
781
+ }
782
+ replay(method) {
783
+ this.request.replay(method, this.meta);
784
+ }
785
+ get(params, doNotSerializeParams = false) {
786
+ return this.req('get', void 0, params, doNotSerializeParams);
787
+ }
788
+ head(params, doNotSerializeParams = false) {
789
+ return this.req('head', void 0, params, doNotSerializeParams);
790
+ }
791
+ post(item, params, doNotSerializeParams = false) {
792
+ return this.req('post', item, params, doNotSerializeParams);
793
+ }
794
+ put(item, params, doNotSerializeParams = false) {
795
+ return this.req('put', item, params, doNotSerializeParams);
796
+ }
797
+ patch(item, params, doNotSerializeParams = false) {
798
+ return this.req('patch', item, params, doNotSerializeParams);
799
+ }
800
+ delete(params, doNotSerializeParams = false) {
801
+ return this.req('delete', void 0, params, doNotSerializeParams);
802
+ }
803
+ jsonp(params, doNotSerializeParams = false) {
804
+ return this.req('jsonp', void 0, params, doNotSerializeParams);
805
+ }
806
+ }
807
+ ;
808
808
  ({}); // @--end-of-file-for-module=ng2-rest lib/rest.class.ts
809
809
 
810
- class Cookie {
811
- constructor() {
812
- }
813
- static get Instance() {
814
- if (!Cookie.__instance) {
815
- Cookie.__instance = new Cookie();
816
- }
817
- return Cookie.__instance;
818
- }
819
- read(name) {
820
- var result = new RegExp('(?:^|; )' + encodeURIComponent(name) + '=([^;]*)').exec(document.cookie);
821
- return result ? result[1] : null;
822
- }
823
- write(name, value, days) {
824
- if (!days) {
825
- days = 365 * 20;
826
- }
827
- var date = new Date();
828
- date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
829
- var expires = "; expires=" + date.toUTCString();
830
- document.cookie = name + "=" + value + expires + "; path=/";
831
- }
832
- remove(name) {
833
- this.write(name, "", -1);
834
- }
835
- }
836
- ;
810
+ class Cookie {
811
+ constructor() {
812
+ }
813
+ static get Instance() {
814
+ if (!Cookie.__instance) {
815
+ Cookie.__instance = new Cookie();
816
+ }
817
+ return Cookie.__instance;
818
+ }
819
+ read(name) {
820
+ var result = new RegExp('(?:^|; )' + encodeURIComponent(name) + '=([^;]*)').exec(document.cookie);
821
+ return result ? result[1] : null;
822
+ }
823
+ write(name, value, days) {
824
+ if (!days) {
825
+ days = 365 * 20;
826
+ }
827
+ var date = new Date();
828
+ date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
829
+ var expires = "; expires=" + date.toUTCString();
830
+ document.cookie = name + "=" + value + expires + "; path=/";
831
+ }
832
+ remove(name) {
833
+ this.write(name, "", -1);
834
+ }
835
+ }
836
+ ;
837
837
  ({}); // @--end-of-file-for-module=ng2-rest lib/cookie.ts
838
838
 
839
- const log$2 = Log.create('request-cache', Level.__NOTHING);
840
- /**
841
- * @deprecated
842
- * there is Cache API for that
843
- */
844
- class RequestCache {
845
- constructor(response) {
846
- this.response = response;
847
- }
848
- static restoreFromLocalStorage() {
849
- if (Helpers$1.isNode) {
850
- return;
851
- }
852
- if (!RequestCache.isRestoredFromLocalStorage) {
853
- RequestCache.isRestoredFromLocalStorage = true;
854
- const data = localStorage.getItem(RequestCache.LOCAL_STORAGE_KEY);
855
- let requests = [];
856
- if (data) {
857
- try {
858
- requests = JSON.parse(data);
859
- }
860
- catch (error) {
861
- }
862
- const restored = requests.map(r => {
863
- let { sourceRequest, responseText, body, headers, circular, entity, isArray, cookies, statusCode } = r.response;
864
- r.response = new Models.HttpResponse(sourceRequest, responseText, RestHeaders.from(headers), statusCode, entity, circular, -1, // jobid from local storage TODO
865
- isArray);
866
- r = new RequestCache(r.response);
867
- r.response.rq = r;
868
- return r;
869
- });
870
- log$2.i('RESTORED FROM LOCAL STORAGE', restored);
871
- RequestCache.cached = restored;
872
- }
873
- }
874
- }
875
- static findBy(sourceRequest) {
876
- log$2.i('findby', sourceRequest);
877
- log$2.i('RequestCache.cached', RequestCache.cached);
878
- RequestCache.restoreFromLocalStorage();
879
- return RequestCache.cached.find(c => {
880
- const a = c.response.sourceRequest;
881
- const b = sourceRequest;
882
- return (a.isArray === b.isArray &&
883
- a.url === b.url &&
884
- a.method === b.method &&
885
- a.body === b.body);
886
- });
887
- }
888
- get containsCache() {
889
- RequestCache.restoreFromLocalStorage();
890
- return RequestCache.cached.includes(this);
891
- }
892
- persistsInLocalStorage() {
893
- localStorage.setItem(RequestCache.LOCAL_STORAGE_KEY, JSON.stringify(RequestCache.cached.map(r => {
894
- return {
895
- response: {
896
- sourceRequest: r.response.sourceRequest,
897
- responseText: r.response.responseText,
898
- headers: r.response.headers,
899
- statusCode: r.response.statusCode,
900
- entity: r.response.entity,
901
- circular: r.response.circular,
902
- isArray: r.response.isArray,
903
- }
904
- };
905
- })));
906
- }
907
- store() {
908
- RequestCache.restoreFromLocalStorage();
909
- if (!this.containsCache) {
910
- RequestCache.cached.push(this);
911
- this.persistsInLocalStorage();
912
- }
913
- else {
914
- console.log('already stored');
915
- }
916
- return this;
917
- }
918
- remove() {
919
- RequestCache.restoreFromLocalStorage();
920
- const index = RequestCache.cached.indexOf(this);
921
- if (index !== -1) {
922
- RequestCache.cached.splice(index, 1);
923
- this.persistsInLocalStorage();
924
- }
925
- else {
926
- console.log('already removed');
927
- }
928
- }
929
- }
930
- RequestCache.LOCAL_STORAGE_KEY = 'ng2restrequestcache';
931
- RequestCache.cached = [];
932
- RequestCache.isRestoredFromLocalStorage = false;
933
- ;
839
+ const log$2 = Log.create('request-cache', Level.__NOTHING);
840
+ /**
841
+ * @deprecated
842
+ * there is Cache API for that
843
+ */
844
+ class RequestCache {
845
+ constructor(response) {
846
+ this.response = response;
847
+ }
848
+ static restoreFromLocalStorage() {
849
+ if (Helpers$1.isNode) {
850
+ return;
851
+ }
852
+ if (!RequestCache.isRestoredFromLocalStorage) {
853
+ RequestCache.isRestoredFromLocalStorage = true;
854
+ const data = localStorage.getItem(RequestCache.LOCAL_STORAGE_KEY);
855
+ let requests = [];
856
+ if (data) {
857
+ try {
858
+ requests = JSON.parse(data);
859
+ }
860
+ catch (error) {
861
+ }
862
+ const restored = requests.map(r => {
863
+ let { sourceRequest, responseText, body, headers, circular, entity, isArray, cookies, statusCode } = r.response;
864
+ r.response = new Models.HttpResponse(sourceRequest, responseText, RestHeaders.from(headers), statusCode, entity, circular, -1, // jobid from local storage TODO
865
+ isArray);
866
+ r = new RequestCache(r.response);
867
+ r.response.rq = r;
868
+ return r;
869
+ });
870
+ log$2.i('RESTORED FROM LOCAL STORAGE', restored);
871
+ RequestCache.cached = restored;
872
+ }
873
+ }
874
+ }
875
+ static findBy(sourceRequest) {
876
+ log$2.i('findby', sourceRequest);
877
+ log$2.i('RequestCache.cached', RequestCache.cached);
878
+ RequestCache.restoreFromLocalStorage();
879
+ return RequestCache.cached.find(c => {
880
+ const a = c.response.sourceRequest;
881
+ const b = sourceRequest;
882
+ return (a.isArray === b.isArray &&
883
+ a.url === b.url &&
884
+ a.method === b.method &&
885
+ a.body === b.body);
886
+ });
887
+ }
888
+ get containsCache() {
889
+ RequestCache.restoreFromLocalStorage();
890
+ return RequestCache.cached.includes(this);
891
+ }
892
+ persistsInLocalStorage() {
893
+ localStorage.setItem(RequestCache.LOCAL_STORAGE_KEY, JSON.stringify(RequestCache.cached.map(r => {
894
+ return {
895
+ response: {
896
+ sourceRequest: r.response.sourceRequest,
897
+ responseText: r.response.responseText,
898
+ headers: r.response.headers,
899
+ statusCode: r.response.statusCode,
900
+ entity: r.response.entity,
901
+ circular: r.response.circular,
902
+ isArray: r.response.isArray,
903
+ }
904
+ };
905
+ })));
906
+ }
907
+ store() {
908
+ RequestCache.restoreFromLocalStorage();
909
+ if (!this.containsCache) {
910
+ RequestCache.cached.push(this);
911
+ this.persistsInLocalStorage();
912
+ }
913
+ else {
914
+ console.log('already stored');
915
+ }
916
+ return this;
917
+ }
918
+ remove() {
919
+ RequestCache.restoreFromLocalStorage();
920
+ const index = RequestCache.cached.indexOf(this);
921
+ if (index !== -1) {
922
+ RequestCache.cached.splice(index, 1);
923
+ this.persistsInLocalStorage();
924
+ }
925
+ else {
926
+ console.log('already removed');
927
+ }
928
+ }
929
+ }
930
+ RequestCache.LOCAL_STORAGE_KEY = 'ng2restrequestcache';
931
+ RequestCache.cached = [];
932
+ RequestCache.isRestoredFromLocalStorage = false;
933
+ ;
934
934
  ({}); // @--end-of-file-for-module=ng2-rest lib/request-cache.ts
935
935
 
936
- var Models;
937
- (function (Models) {
938
- Models.MethodConfig = Models$1.MethodConfig;
939
- Models.ClassConfig = Models$1.ClassConfig;
940
- Models.ParamConfig = Models$1.ParamConfig;
941
- ;
942
- ;
943
- [];
944
- class BaseBody {
945
- toJSON(data, isJSONArray = false) {
946
- let r = isJSONArray ? [] : {};
947
- if (typeof data === 'string') {
948
- try {
949
- r = JSON.parse(data);
950
- }
951
- catch (e) { }
952
- }
953
- else if (typeof data === 'object') {
954
- return data;
955
- }
956
- return r;
957
- }
958
- }
959
- Models.BaseBody = BaseBody;
960
- class HttpBody extends BaseBody {
961
- constructor(responseText, isArray = false, entity, circular) {
962
- super();
963
- this.responseText = responseText;
964
- this.isArray = isArray;
965
- this.entity = entity;
966
- this.circular = circular;
967
- }
968
- get blob() {
969
- return this.responseText;
970
- }
971
- get booleanValue() {
972
- if (!isBlob(this.responseText)) {
973
- return ['ok', 'true'].includes(this.responseText.trim());
974
- }
975
- }
976
- get rawJson() {
977
- if (!isBlob(this.responseText)) {
978
- let res = this.toJSON(this.responseText, this.isArray);
979
- if (this.circular && Array.isArray(this.circular)) {
980
- res = JSON10.parse(JSON.stringify(res), this.circular);
981
- }
982
- return res;
983
- }
984
- }
985
- get json() {
986
- if (!isBlob(this.responseText)) {
987
- if (this.entity && typeof this.entity === 'function') {
988
- return this.entity(); // @LAST
989
- }
990
- if (this.entity && typeof this.entity === 'object') {
991
- const json = this.toJSON(this.responseText, this.isArray);
992
- return Mapping.encode(json, this.entity, this.circular);
993
- }
994
- let res = this.toJSON(this.responseText, this.isArray);
995
- if (this.circular && Array.isArray(this.circular)) {
996
- res = JSON10.parse(JSON.stringify(res), this.circular);
997
- }
998
- return res;
999
- }
1000
- }
1001
- get text() {
1002
- if (!isBlob(this.responseText)) {
1003
- return this.responseText.replace(/^\"/, '').replace(/\"$/, '');
1004
- }
1005
- }
1006
- }
1007
- Models.HttpBody = HttpBody;
1008
- class ErrorBody extends BaseBody {
1009
- constructor(data) {
1010
- super();
1011
- this.data = data;
1012
- }
1013
- get json() {
1014
- return this.toJSON(this.data);
1015
- }
1016
- get text() {
1017
- return this.data;
1018
- }
1019
- }
1020
- Models.ErrorBody = ErrorBody;
1021
- class BaseResponse {
1022
- constructor(responseText, headers, statusCode, isArray = false) {
1023
- this.responseText = responseText;
1024
- this.headers = headers;
1025
- this.statusCode = statusCode;
1026
- this.isArray = isArray;
1027
- }
1028
- get cookies() {
1029
- return BaseResponse.cookies;
1030
- }
1031
- }
1032
- BaseResponse.cookies = Cookie.Instance;
1033
- Models.BaseResponse = BaseResponse;
1034
- class HttpResponse extends BaseResponse {
1035
- constructor(sourceRequest, responseText, headers, statusCode, entity, circular, jobid, isArray = false) {
1036
- super(responseText, headers, statusCode, isArray);
1037
- this.sourceRequest = sourceRequest;
1038
- this.responseText = responseText;
1039
- this.headers = headers;
1040
- this.statusCode = statusCode;
1041
- this.entity = entity;
1042
- this.circular = circular;
1043
- this.jobid = jobid;
1044
- this.isArray = isArray;
1045
- this.init();
1046
- }
1047
- init() {
1048
- if (typeof this.entity === 'string') {
1049
- let entityJSON = this.headers.getAll(this.entity);
1050
- if (!!entityJSON) {
1051
- this.entity = JSON.parse(entityJSON.join());
1052
- }
1053
- }
1054
- if (typeof this.circular === 'string') {
1055
- let circuralJSON = this.headers.getAll(this.circular);
1056
- if (!!circuralJSON) {
1057
- this.circular = JSON.parse(circuralJSON.join());
1058
- }
1059
- }
1060
- this.body = new HttpBody(this.responseText, this.isArray, this.entity, this.circular);
1061
- }
1062
- get cache() {
1063
- if (_.isUndefined(this.rq)) {
1064
- this.rq = new RequestCache(this);
1065
- }
1066
- return new RequestCache(this);
1067
- }
1068
- }
1069
- Models.HttpResponse = HttpResponse;
1070
- class HttpResponseError extends BaseResponse {
1071
- constructor(message, responseText, headers, statusCode, jobid) {
1072
- super(responseText, headers, statusCode);
1073
- this.message = message;
1074
- this.jobid = jobid;
1075
- this.body = new ErrorBody(responseText);
1076
- }
1077
- }
1078
- Models.HttpResponseError = HttpResponseError;
1079
- /* */
1080
- /* */
1081
- /* */
1082
- /* */
1083
- /* */
1084
- /* */
1085
- })(Models || (Models = {}));
1086
- function isBlob(maybeBlob) {
1087
- if (typeof Blob === 'undefined') { // OK because there is no Blob in node
1088
- return false;
1089
- }
1090
- return maybeBlob instanceof Blob; // || toString.call(maybeBlob) === '[object Blob]';
1091
- }
1092
- ;
936
+ var Models;
937
+ (function (Models) {
938
+ Models.MethodConfig = Models$1.MethodConfig;
939
+ Models.ClassConfig = Models$1.ClassConfig;
940
+ Models.ParamConfig = Models$1.ParamConfig;
941
+ ;
942
+ ;
943
+ [];
944
+ class BaseBody {
945
+ toJSON(data, isJSONArray = false) {
946
+ let r = isJSONArray ? [] : {};
947
+ if (typeof data === 'string') {
948
+ try {
949
+ r = JSON.parse(data);
950
+ }
951
+ catch (e) { }
952
+ }
953
+ else if (typeof data === 'object') {
954
+ return data;
955
+ }
956
+ return r;
957
+ }
958
+ }
959
+ Models.BaseBody = BaseBody;
960
+ class HttpBody extends BaseBody {
961
+ constructor(responseText, isArray = false, entity, circular) {
962
+ super();
963
+ this.responseText = responseText;
964
+ this.isArray = isArray;
965
+ this.entity = entity;
966
+ this.circular = circular;
967
+ }
968
+ get blob() {
969
+ return this.responseText;
970
+ }
971
+ get booleanValue() {
972
+ if (!Helpers$1.isBlob(this.responseText)) {
973
+ return ['ok', 'true'].includes(this.responseText.trim());
974
+ }
975
+ }
976
+ get rawJson() {
977
+ if (!Helpers$1.isBlob(this.responseText)) {
978
+ let res = this.toJSON(this.responseText, this.isArray);
979
+ if (this.circular && Array.isArray(this.circular)) {
980
+ res = JSON10.parse(JSON.stringify(res), this.circular);
981
+ }
982
+ return res;
983
+ }
984
+ }
985
+ get json() {
986
+ if (!Helpers$1.isBlob(this.responseText)) {
987
+ if (this.entity && typeof this.entity === 'function') {
988
+ return this.entity(); // @LAST
989
+ }
990
+ if (this.entity && typeof this.entity === 'object') {
991
+ const json = this.toJSON(this.responseText, this.isArray);
992
+ return Mapping.encode(json, this.entity, this.circular);
993
+ }
994
+ let res = this.toJSON(this.responseText, this.isArray);
995
+ if (this.circular && Array.isArray(this.circular)) {
996
+ res = JSON10.parse(JSON.stringify(res), this.circular);
997
+ }
998
+ return res;
999
+ }
1000
+ }
1001
+ get text() {
1002
+ if (!Helpers$1.isBlob(this.responseText)) {
1003
+ return this.responseText.replace(/^\"/, '').replace(/\"$/, '');
1004
+ }
1005
+ }
1006
+ }
1007
+ Models.HttpBody = HttpBody;
1008
+ class ErrorBody extends BaseBody {
1009
+ constructor(data) {
1010
+ super();
1011
+ this.data = data;
1012
+ }
1013
+ get json() {
1014
+ return this.toJSON(this.data);
1015
+ }
1016
+ get text() {
1017
+ return this.data;
1018
+ }
1019
+ }
1020
+ Models.ErrorBody = ErrorBody;
1021
+ class BaseResponse {
1022
+ constructor(responseText, headers, statusCode, isArray = false) {
1023
+ this.responseText = responseText;
1024
+ this.headers = headers;
1025
+ this.statusCode = statusCode;
1026
+ this.isArray = isArray;
1027
+ }
1028
+ get cookies() {
1029
+ return BaseResponse.cookies;
1030
+ }
1031
+ }
1032
+ BaseResponse.cookies = Cookie.Instance;
1033
+ Models.BaseResponse = BaseResponse;
1034
+ class HttpResponse extends BaseResponse {
1035
+ constructor(sourceRequest, responseText, headers, statusCode, entity, circular, jobid, isArray = false) {
1036
+ super(responseText, headers, statusCode, isArray);
1037
+ this.sourceRequest = sourceRequest;
1038
+ this.responseText = responseText;
1039
+ this.headers = headers;
1040
+ this.statusCode = statusCode;
1041
+ this.entity = entity;
1042
+ this.circular = circular;
1043
+ this.jobid = jobid;
1044
+ this.isArray = isArray;
1045
+ this.init();
1046
+ }
1047
+ init() {
1048
+ if (typeof this.entity === 'string') {
1049
+ let entityJSON = this.headers.getAll(this.entity);
1050
+ if (!!entityJSON) {
1051
+ this.entity = JSON.parse(entityJSON.join());
1052
+ }
1053
+ }
1054
+ if (typeof this.circular === 'string') {
1055
+ let circuralJSON = this.headers.getAll(this.circular);
1056
+ if (!!circuralJSON) {
1057
+ this.circular = JSON.parse(circuralJSON.join());
1058
+ }
1059
+ }
1060
+ this.body = new HttpBody(this.responseText, this.isArray, this.entity, this.circular);
1061
+ }
1062
+ get cache() {
1063
+ if (_.isUndefined(this.rq)) {
1064
+ this.rq = new RequestCache(this);
1065
+ }
1066
+ return new RequestCache(this);
1067
+ }
1068
+ }
1069
+ Models.HttpResponse = HttpResponse;
1070
+ class HttpResponseError extends BaseResponse {
1071
+ constructor(message, responseText, headers, statusCode, jobid) {
1072
+ super(responseText, headers, statusCode);
1073
+ this.message = message;
1074
+ this.jobid = jobid;
1075
+ this.body = new ErrorBody(responseText);
1076
+ }
1077
+ }
1078
+ Models.HttpResponseError = HttpResponseError;
1079
+ /* */
1080
+ /* */
1081
+ /* */
1082
+ /* */
1083
+ /* */
1084
+ /* */
1085
+ })(Models || (Models = {}));
1086
+ ;
1093
1087
  ({}); // @--end-of-file-for-module=ng2-rest lib/models.ts
1094
1088
 
1095
- const log$1 = Log.create('[ng2-rest] rest-request', Level.__NOTHING);
1096
- const jobIDkey = 'jobID';
1097
- const customObs = 'customObs';
1098
- const cancelFn = 'cancelFn';
1099
- const isCanceled = 'isCanceled';
1100
- class RestRequest {
1101
- constructor() {
1102
- this.subjectInuUse = {};
1103
- this.meta = {};
1104
- this.replaySubjects = {};
1105
- }
1106
- handlerResult(options, sourceRequest) {
1107
- if (_.isUndefined(options)) {
1108
- options = {};
1109
- }
1110
- const { res, jobid, isArray, method } = options;
1111
- if (typeof res !== 'object') {
1112
- throw new Error('No resposnse for request. ');
1113
- }
1114
- if (Helpers$1.isBrowser) {
1115
- res.headers = RestHeaders.from(res.headers);
1116
- }
1117
- if (res.error) {
1118
- this.subjectInuUse[jobid].error(new Models.HttpResponseError(res.error, res.data, res.headers, res.code, jobid));
1119
- return;
1120
- }
1121
- const entity = this.meta[jobid].entity;
1122
- const circular = this.meta[jobid].circular;
1123
- const success = Resource['_listenSuccess'];
1124
- const reqResp = new Models.HttpResponse(sourceRequest, res.data, res.headers, res.code, entity, circular, jobid, isArray);
1125
- success.next(reqResp);
1126
- this.subjectInuUse[jobid].next(reqResp);
1127
- this.meta[jobid] = void 0;
1128
- this.subjectInuUse[jobid].complete();
1129
- }
1130
- checkCache(sourceRequest, jobid) {
1131
- const existedInCache = RequestCache.findBy(sourceRequest);
1132
- if (existedInCache) {
1133
- const success = Resource['_listenSuccess'];
1134
- success.next(existedInCache.response);
1135
- this.subjectInuUse[jobid].next(existedInCache);
1136
- this.subjectInuUse[jobid].complete();
1137
- return true;
1138
- }
1139
- return false;
1140
- }
1141
- req(url, method, headers, body, jobid, isArray = false, mockHttp) {
1142
- return __awaiter(this, void 0, void 0, function* () {
1143
- if (this.checkCache({
1144
- url,
1145
- body,
1146
- isArray,
1147
- method
1148
- }, jobid)) {
1149
- return;
1150
- }
1151
- const CancelToken = axios.CancelToken;
1152
- const source = CancelToken.source();
1153
- this.subjectInuUse[jobid][cancelFn] = source.cancel;
1154
- var response;
1155
- if (mockHttp) {
1156
- if (typeof mockHttp === 'object') {
1157
- response = {
1158
- data: mockHttp.data,
1159
- status: mockHttp.code,
1160
- headers: mockHttp.headers,
1161
- statusText: mockHttp.error,
1162
- config: {}
1163
- };
1164
- }
1165
- else if (typeof mockHttp === 'function') {
1166
- const r = mockHttp(url, method, headers, body);
1167
- response = {
1168
- data: r.data,
1169
- status: r.code,
1170
- headers: r.headers,
1171
- statusText: r.error,
1172
- config: {}
1173
- };
1174
- }
1175
- }
1176
- const headersJson = headers.toJSON();
1177
- const responseType = headersJson.responsetypeaxios ? headersJson.responsetypeaxios : 'text';
1178
- try {
1179
- if (!response) {
1180
- response = yield axios({
1181
- url,
1182
- method,
1183
- data: body,
1184
- responseType,
1185
- headers: headersJson,
1186
- cancelToken: source.token,
1187
- });
1188
- }
1189
- if (this.subjectInuUse[jobid][isCanceled]) {
1190
- return;
1191
- }
1192
- this.handlerResult({
1193
- res: {
1194
- code: response.status,
1195
- data: response.data,
1196
- isArray,
1197
- jobid,
1198
- headers: RestHeaders.from(response.headers)
1199
- },
1200
- method,
1201
- jobid,
1202
- isArray
1203
- }, {
1204
- url,
1205
- body,
1206
- method,
1207
- isArray,
1208
- });
1209
- }
1210
- catch (catchedError) {
1211
- if (this.subjectInuUse[jobid][isCanceled]) {
1212
- return;
1213
- }
1214
- if (typeof catchedError === 'object' && catchedError.response && catchedError.response.data) {
1215
- const err = catchedError.response.data;
1216
- const msg = catchedError.response.data.message || '';
1217
- let stack = (err.stack || '').split('\n');
1218
- const errObs = Resource['_listenErrors'];
1219
- errObs.next({
1220
- msg,
1221
- stack,
1222
- data: catchedError.response.data
1223
- });
1224
- }
1225
- const error = (catchedError && catchedError.response) ? `[${catchedError.response.statusText}]: ` : '';
1226
- this.handlerResult({
1227
- res: {
1228
- code: (catchedError && catchedError.response) ? catchedError.response.status : void 0,
1229
- error: `${error}${catchedError.message}`,
1230
- data: (catchedError && catchedError.response) ? JSON.stringify(catchedError.response.data) : void 0,
1231
- isArray,
1232
- jobid,
1233
- headers: RestHeaders.from(catchedError && catchedError.response && catchedError.response.headers)
1234
- },
1235
- method,
1236
- jobid,
1237
- isArray
1238
- }, {
1239
- url,
1240
- body,
1241
- isArray,
1242
- method
1243
- });
1244
- }
1245
- });
1246
- }
1247
- getReplay(method, meta, onlyGetLastReplayForMethod) {
1248
- let replay;
1249
- if (_.isUndefined(this.replaySubjects[meta.endpoint])) {
1250
- this.replaySubjects[meta.endpoint] = {};
1251
- }
1252
- if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path])) {
1253
- this.replaySubjects[meta.endpoint][meta.path] = {};
1254
- }
1255
- if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path][method])) {
1256
- this.replaySubjects[meta.endpoint][meta.path][method] = {};
1257
- }
1258
- const objectIDToCreateOrLast = (Object.keys(this.replaySubjects[meta.endpoint][meta.path][method]).length) +
1259
- (onlyGetLastReplayForMethod ? 0 : 1);
1260
- if (onlyGetLastReplayForMethod && (objectIDToCreateOrLast === 0)) {
1261
- return replay;
1262
- }
1263
- if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast])) {
1264
- this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast] = {
1265
- subject: new Subject(),
1266
- data: void 0,
1267
- };
1268
- }
1269
- replay = this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast];
1270
- if (!_.isNumber(replay.id)) {
1271
- if (RestRequest.jobId === Number.MAX_SAFE_INTEGER) {
1272
- RestRequest.jobId = 0;
1273
- }
1274
- const jobid = RestRequest.jobId++;
1275
- replay.id = jobid;
1276
- const subject = replay.subject;
1277
- subject[jobIDkey] = jobid; // modify internal rxjs subject obj
1278
- this.meta[jobid] = meta;
1279
- this.subjectInuUse[jobid] = subject;
1280
- this.subjectInuUse[jobid][customObs] = new Observable((observer) => {
1281
- observer.add(() => {
1282
- if (!this.subjectInuUse[jobid][isCanceled]) {
1283
- this.subjectInuUse[jobid][isCanceled] = true;
1284
- if (typeof this.subjectInuUse[jobid][cancelFn] === 'function') {
1285
- this.subjectInuUse[jobid][cancelFn]('[ng2-rest] on purpose canceled http request');
1286
- }
1287
- }
1288
- else {
1289
- }
1290
- });
1291
- const sub = subject.subscribe({
1292
- next: a => observer.next(a),
1293
- error: a => observer.error(a),
1294
- complete: () => {
1295
- sub.unsubscribe();
1296
- observer.complete();
1297
- },
1298
- });
1299
- });
1300
- }
1301
- return replay;
1302
- }
1303
- generalReq(method, url, body, headers, meta, isArray, mockHttp) {
1304
- const replay = this.getReplay(method, meta, false);
1305
- replay.data = { url, body, headers, isArray };
1306
- ((pthis, purl, pmethod, pheaders, pbody, pid, pisArray, pmockHttp) => {
1307
- setTimeout(() => pthis.req(purl, pmethod, pheaders, pbody, pid, pisArray, pmockHttp));
1308
- })(this, url, method, headers, body, replay.id, isArray, mockHttp);
1309
- const resp = firstValueFrom(replay.subject[customObs]);
1310
- resp.observable = replay.subject[customObs];
1311
- resp.cache = RequestCache.findBy({
1312
- body,
1313
- isArray,
1314
- method,
1315
- url
1316
- });
1317
- return resp;
1318
- }
1319
- get(url, body, headers, meta, isArray, mockHttp) {
1320
- return this.generalReq('get', url, body, headers, meta, isArray, mockHttp);
1321
- }
1322
- head(url, body, headers, meta, isArray, mockHttp) {
1323
- return this.generalReq('head', url, body, headers, meta, isArray, mockHttp);
1324
- }
1325
- delete(url, body, headers, meta, isArray, mockHttp) {
1326
- return this.generalReq('delete', url, body, headers, meta, isArray, mockHttp);
1327
- }
1328
- post(url, body, headers, meta, isArray, mockHttp) {
1329
- return this.generalReq('post', url, body, headers, meta, isArray, mockHttp);
1330
- }
1331
- put(url, body, headers, meta, isArray, mockHttp) {
1332
- return this.generalReq('put', url, body, headers, meta, isArray, mockHttp);
1333
- }
1334
- patch(url, body, headers, meta, isArray, mockHttp) {
1335
- return this.generalReq('patch', url, body, headers, meta, isArray, mockHttp);
1336
- }
1337
- jsonp(url, body, headers, meta, isArray, mockHttp) {
1338
- const replay = this.getReplay('jsonp', meta, false);
1339
- const jobid = replay.id;
1340
- const method = 'jsonp';
1341
- setTimeout(() => {
1342
- if (url.endsWith('/'))
1343
- url = url.slice(0, url.length - 1);
1344
- let num = Math.round(10000 * Math.random());
1345
- let callbackMethodName = "cb_" + num;
1346
- window[callbackMethodName] = (data) => {
1347
- if (this.checkCache({
1348
- url,
1349
- body,
1350
- isArray,
1351
- method
1352
- }, jobid)) {
1353
- return;
1354
- }
1355
- this.handlerResult({
1356
- res: {
1357
- data, isArray
1358
- },
1359
- method,
1360
- jobid,
1361
- isArray
1362
- }, {
1363
- url,
1364
- body,
1365
- isArray,
1366
- method,
1367
- });
1368
- };
1369
- let sc = document.createElement('script');
1370
- sc.src = `${url}?callback=${callbackMethodName}`;
1371
- document.body.appendChild(sc);
1372
- document.body.removeChild(sc);
1373
- });
1374
- const resp = firstValueFrom(replay.subject[customObs]);
1375
- resp.observable = replay.subject[customObs];
1376
- console.log('assiging custom observable');
1377
- resp.cache = RequestCache.findBy({
1378
- body,
1379
- isArray,
1380
- method,
1381
- url
1382
- });
1383
- return resp;
1384
- }
1385
- replay(method, meta) {
1386
- const replay = this.getReplay(method, meta, true);
1387
- if (!replay || !replay.data) {
1388
- console.warn(`Canno replay first ${method} request from ${meta.endpoint}/${meta.path}`);
1389
- return;
1390
- }
1391
- ;
1392
- if (replay && replay.subject && Array.isArray(replay.subject.observers) &&
1393
- replay.subject.observers.length === 0) {
1394
- console.warn(`No observators for ${method} request from ${meta.endpoint}/${meta.path}`);
1395
- return;
1396
- }
1397
- const url = replay.data.url;
1398
- const headers = replay.data.headers;
1399
- const body = replay.data.body;
1400
- const isArray = replay.data.isArray;
1401
- setTimeout(() => this.req(url, method, headers, body, replay.id, isArray));
1402
- }
1403
- }
1404
- RestRequest.jobId = 0;
1405
- ;
1089
+ const log$1 = Log.create('[ng2-rest] rest-request', Level.__NOTHING);
1090
+ const jobIDkey = 'jobID';
1091
+ const customObs = 'customObs';
1092
+ const cancelFn = 'cancelFn';
1093
+ const isCanceled = 'isCanceled';
1094
+ class RestRequest {
1095
+ constructor() {
1096
+ this.subjectInuUse = {};
1097
+ this.meta = {};
1098
+ this.replaySubjects = {};
1099
+ }
1100
+ handlerResult(options, sourceRequest) {
1101
+ if (_.isUndefined(options)) {
1102
+ options = {};
1103
+ }
1104
+ const { res, jobid, isArray, method } = options;
1105
+ if (typeof res !== 'object') {
1106
+ throw new Error('No resposnse for request. ');
1107
+ }
1108
+ if (Helpers$1.isBrowser) {
1109
+ res.headers = RestHeaders.from(res.headers);
1110
+ }
1111
+ if (res.error) {
1112
+ this.subjectInuUse[jobid].error(new Models.HttpResponseError(res.error, res.data, res.headers, res.code, jobid));
1113
+ return;
1114
+ }
1115
+ const entity = this.meta[jobid].entity;
1116
+ const circular = this.meta[jobid].circular;
1117
+ const success = Resource['_listenSuccess'];
1118
+ const reqResp = new Models.HttpResponse(sourceRequest, res.data, res.headers, res.code, entity, circular, jobid, isArray);
1119
+ success.next(reqResp);
1120
+ this.subjectInuUse[jobid].next(reqResp);
1121
+ this.meta[jobid] = void 0;
1122
+ this.subjectInuUse[jobid].complete();
1123
+ }
1124
+ checkCache(sourceRequest, jobid) {
1125
+ const existedInCache = RequestCache.findBy(sourceRequest);
1126
+ if (existedInCache) {
1127
+ const success = Resource['_listenSuccess'];
1128
+ success.next(existedInCache.response);
1129
+ this.subjectInuUse[jobid].next(existedInCache);
1130
+ this.subjectInuUse[jobid].complete();
1131
+ return true;
1132
+ }
1133
+ return false;
1134
+ }
1135
+ req(url, method, headers, body, jobid, isArray = false, mockHttp) {
1136
+ return __awaiter(this, void 0, void 0, function* () {
1137
+ if (this.checkCache({
1138
+ url,
1139
+ body,
1140
+ isArray,
1141
+ method
1142
+ }, jobid)) {
1143
+ return;
1144
+ }
1145
+ const CancelToken = axios.CancelToken;
1146
+ const source = CancelToken.source();
1147
+ this.subjectInuUse[jobid][cancelFn] = source.cancel;
1148
+ var response;
1149
+ if (mockHttp) {
1150
+ if (typeof mockHttp === 'object') {
1151
+ response = {
1152
+ data: mockHttp.data,
1153
+ status: mockHttp.code,
1154
+ headers: mockHttp.headers,
1155
+ statusText: mockHttp.error,
1156
+ config: {}
1157
+ };
1158
+ }
1159
+ else if (typeof mockHttp === 'function') {
1160
+ const r = mockHttp(url, method, headers, body);
1161
+ response = {
1162
+ data: r.data,
1163
+ status: r.code,
1164
+ headers: r.headers,
1165
+ statusText: r.error,
1166
+ config: {}
1167
+ };
1168
+ }
1169
+ }
1170
+ const headersJson = headers.toJSON();
1171
+ const responseType = headersJson.responsetypeaxios ? headersJson.responsetypeaxios : 'text';
1172
+ try {
1173
+ if (!response) {
1174
+ response = yield axios({
1175
+ url,
1176
+ method,
1177
+ data: body,
1178
+ responseType,
1179
+ headers: headersJson,
1180
+ cancelToken: source.token,
1181
+ });
1182
+ }
1183
+ if (this.subjectInuUse[jobid][isCanceled]) {
1184
+ return;
1185
+ }
1186
+ this.handlerResult({
1187
+ res: {
1188
+ code: response.status,
1189
+ data: response.data,
1190
+ isArray,
1191
+ jobid,
1192
+ headers: RestHeaders.from(response.headers)
1193
+ },
1194
+ method,
1195
+ jobid,
1196
+ isArray
1197
+ }, {
1198
+ url,
1199
+ body,
1200
+ method,
1201
+ isArray,
1202
+ });
1203
+ }
1204
+ catch (catchedError) {
1205
+ if (this.subjectInuUse[jobid][isCanceled]) {
1206
+ return;
1207
+ }
1208
+ if (typeof catchedError === 'object' && catchedError.response && catchedError.response.data) {
1209
+ const err = catchedError.response.data;
1210
+ const msg = catchedError.response.data.message || '';
1211
+ let stack = (err.stack || '').split('\n');
1212
+ const errObs = Resource['_listenErrors'];
1213
+ errObs.next({
1214
+ msg,
1215
+ stack,
1216
+ data: catchedError.response.data
1217
+ });
1218
+ }
1219
+ const error = (catchedError && catchedError.response) ? `[${catchedError.response.statusText}]: ` : '';
1220
+ this.handlerResult({
1221
+ res: {
1222
+ code: (catchedError && catchedError.response) ? catchedError.response.status : void 0,
1223
+ error: `${error}${catchedError.message}`,
1224
+ data: (catchedError && catchedError.response) ? JSON.stringify(catchedError.response.data) : void 0,
1225
+ isArray,
1226
+ jobid,
1227
+ headers: RestHeaders.from(catchedError && catchedError.response && catchedError.response.headers)
1228
+ },
1229
+ method,
1230
+ jobid,
1231
+ isArray
1232
+ }, {
1233
+ url,
1234
+ body,
1235
+ isArray,
1236
+ method
1237
+ });
1238
+ }
1239
+ });
1240
+ }
1241
+ getReplay(method, meta, onlyGetLastReplayForMethod) {
1242
+ let replay;
1243
+ if (_.isUndefined(this.replaySubjects[meta.endpoint])) {
1244
+ this.replaySubjects[meta.endpoint] = {};
1245
+ }
1246
+ if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path])) {
1247
+ this.replaySubjects[meta.endpoint][meta.path] = {};
1248
+ }
1249
+ if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path][method])) {
1250
+ this.replaySubjects[meta.endpoint][meta.path][method] = {};
1251
+ }
1252
+ const objectIDToCreateOrLast = (Object.keys(this.replaySubjects[meta.endpoint][meta.path][method]).length) +
1253
+ (onlyGetLastReplayForMethod ? 0 : 1);
1254
+ if (onlyGetLastReplayForMethod && (objectIDToCreateOrLast === 0)) {
1255
+ return replay;
1256
+ }
1257
+ if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast])) {
1258
+ this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast] = {
1259
+ subject: new Subject(),
1260
+ data: void 0,
1261
+ };
1262
+ }
1263
+ replay = this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast];
1264
+ if (!_.isNumber(replay.id)) {
1265
+ if (RestRequest.jobId === Number.MAX_SAFE_INTEGER) {
1266
+ RestRequest.jobId = 0;
1267
+ }
1268
+ const jobid = RestRequest.jobId++;
1269
+ replay.id = jobid;
1270
+ const subject = replay.subject;
1271
+ subject[jobIDkey] = jobid; // modify internal rxjs subject obj
1272
+ this.meta[jobid] = meta;
1273
+ this.subjectInuUse[jobid] = subject;
1274
+ this.subjectInuUse[jobid][customObs] = new Observable((observer) => {
1275
+ observer.add(() => {
1276
+ if (!this.subjectInuUse[jobid][isCanceled]) {
1277
+ this.subjectInuUse[jobid][isCanceled] = true;
1278
+ if (typeof this.subjectInuUse[jobid][cancelFn] === 'function') {
1279
+ this.subjectInuUse[jobid][cancelFn]('[ng2-rest] on purpose canceled http request');
1280
+ }
1281
+ }
1282
+ else {
1283
+ }
1284
+ });
1285
+ const sub = subject.subscribe({
1286
+ next: a => observer.next(a),
1287
+ error: a => observer.error(a),
1288
+ complete: () => {
1289
+ sub.unsubscribe();
1290
+ observer.complete();
1291
+ },
1292
+ });
1293
+ });
1294
+ }
1295
+ return replay;
1296
+ }
1297
+ generalReq(method, url, body, headers, meta, isArray, mockHttp) {
1298
+ const replay = this.getReplay(method, meta, false);
1299
+ replay.data = { url, body, headers, isArray };
1300
+ ((pthis, purl, pmethod, pheaders, pbody, pid, pisArray, pmockHttp) => {
1301
+ setTimeout(() => pthis.req(purl, pmethod, pheaders, pbody, pid, pisArray, pmockHttp));
1302
+ })(this, url, method, headers, body, replay.id, isArray, mockHttp);
1303
+ const resp = firstValueFrom(replay.subject[customObs]);
1304
+ resp.observable = replay.subject[customObs];
1305
+ resp.cache = RequestCache.findBy({
1306
+ body,
1307
+ isArray,
1308
+ method,
1309
+ url
1310
+ });
1311
+ return resp;
1312
+ }
1313
+ get(url, body, headers, meta, isArray, mockHttp) {
1314
+ return this.generalReq('get', url, body, headers, meta, isArray, mockHttp);
1315
+ }
1316
+ head(url, body, headers, meta, isArray, mockHttp) {
1317
+ return this.generalReq('head', url, body, headers, meta, isArray, mockHttp);
1318
+ }
1319
+ delete(url, body, headers, meta, isArray, mockHttp) {
1320
+ return this.generalReq('delete', url, body, headers, meta, isArray, mockHttp);
1321
+ }
1322
+ post(url, body, headers, meta, isArray, mockHttp) {
1323
+ return this.generalReq('post', url, body, headers, meta, isArray, mockHttp);
1324
+ }
1325
+ put(url, body, headers, meta, isArray, mockHttp) {
1326
+ return this.generalReq('put', url, body, headers, meta, isArray, mockHttp);
1327
+ }
1328
+ patch(url, body, headers, meta, isArray, mockHttp) {
1329
+ return this.generalReq('patch', url, body, headers, meta, isArray, mockHttp);
1330
+ }
1331
+ jsonp(url, body, headers, meta, isArray, mockHttp) {
1332
+ const replay = this.getReplay('jsonp', meta, false);
1333
+ const jobid = replay.id;
1334
+ const method = 'jsonp';
1335
+ setTimeout(() => {
1336
+ if (url.endsWith('/'))
1337
+ url = url.slice(0, url.length - 1);
1338
+ let num = Math.round(10000 * Math.random());
1339
+ let callbackMethodName = "cb_" + num;
1340
+ window[callbackMethodName] = (data) => {
1341
+ if (this.checkCache({
1342
+ url,
1343
+ body,
1344
+ isArray,
1345
+ method
1346
+ }, jobid)) {
1347
+ return;
1348
+ }
1349
+ this.handlerResult({
1350
+ res: {
1351
+ data, isArray
1352
+ },
1353
+ method,
1354
+ jobid,
1355
+ isArray
1356
+ }, {
1357
+ url,
1358
+ body,
1359
+ isArray,
1360
+ method,
1361
+ });
1362
+ };
1363
+ let sc = document.createElement('script');
1364
+ sc.src = `${url}?callback=${callbackMethodName}`;
1365
+ document.body.appendChild(sc);
1366
+ document.body.removeChild(sc);
1367
+ });
1368
+ const resp = firstValueFrom(replay.subject[customObs]);
1369
+ resp.observable = replay.subject[customObs];
1370
+ console.log('assiging custom observable');
1371
+ resp.cache = RequestCache.findBy({
1372
+ body,
1373
+ isArray,
1374
+ method,
1375
+ url
1376
+ });
1377
+ return resp;
1378
+ }
1379
+ replay(method, meta) {
1380
+ const replay = this.getReplay(method, meta, true);
1381
+ if (!replay || !replay.data) {
1382
+ console.warn(`Canno replay first ${method} request from ${meta.endpoint}/${meta.path}`);
1383
+ return;
1384
+ }
1385
+ ;
1386
+ if (replay && replay.subject && Array.isArray(replay.subject.observers) &&
1387
+ replay.subject.observers.length === 0) {
1388
+ console.warn(`No observators for ${method} request from ${meta.endpoint}/${meta.path}`);
1389
+ return;
1390
+ }
1391
+ const url = replay.data.url;
1392
+ const headers = replay.data.headers;
1393
+ const body = replay.data.body;
1394
+ const isArray = replay.data.isArray;
1395
+ setTimeout(() => this.req(url, method, headers, body, replay.id, isArray));
1396
+ }
1397
+ }
1398
+ RestRequest.jobId = 0;
1399
+ ;
1406
1400
  ({}); // @--end-of-file-for-module=ng2-rest lib/rest-request.ts
1407
1401
 
1408
- const log = Log.create('resouce-service', Level.__NOTHING);
1409
- class Resource {
1410
- constructor() {
1411
- setTimeout(() => {
1412
- const zone = this.getZone();
1413
- if (!RestRequest.zone) {
1414
- RestRequest.zone = zone;
1415
- }
1416
- ;
1417
- });
1418
- }
1419
- static get listenErrors() {
1420
- return this._listenErrors.asObservable();
1421
- }
1422
- static get listenSuccessOperations() {
1423
- return this._listenSuccess.asObservable();
1424
- }
1425
- getZone() {
1426
- const isNode = (typeof window === 'undefined');
1427
- if (isNode) {
1428
- return;
1429
- }
1430
- ;
1431
- const ng = window['ng'];
1432
- const getAllAngularRootElements = window['getAllAngularRootElements'];
1433
- if (!ng || !getAllAngularRootElements) {
1434
- return;
1435
- }
1436
- const probe = ng.probe;
1437
- const coreTokens = ng.coreTokens;
1438
- if (!coreTokens || !coreTokens.NgZone) {
1439
- return;
1440
- }
1441
- const zoneClass = coreTokens.NgZone;
1442
- if (!probe || typeof probe !== 'function' || !getAllAngularRootElements) {
1443
- return;
1444
- }
1445
- const angularElements = getAllAngularRootElements();
1446
- if (!Array.isArray(angularElements) || angularElements.length === 0) {
1447
- return;
1448
- }
1449
- const rootElement = ng.probe(angularElements[0]);
1450
- if (!rootElement) {
1451
- return;
1452
- }
1453
- const injector = rootElement.injector;
1454
- if (!injector || !injector.get || typeof injector.get !== 'function') {
1455
- return;
1456
- }
1457
- const zone = injector.get(zoneClass);
1458
- return zone;
1459
- }
1460
- static initAngularNgZone(zone) {
1461
- RestRequest.zone = zone;
1462
- }
1463
- checkNestedModels(model, allModels) {
1464
- for (let p in allModels) {
1465
- if (allModels.hasOwnProperty(p)) {
1466
- let m = allModels[p];
1467
- if (isValid(p)) {
1468
- let urlModels = getModels(p);
1469
- if (containsModels(model, urlModels)) {
1470
- model = p;
1471
- break;
1472
- }
1473
- }
1474
- }
1475
- }
1476
- return model;
1477
- }
1478
- static getModel(endpoint, model) {
1479
- model = Resource.prepareModel(model);
1480
- const e = Resource.endpoints[endpoint];
1481
- if (!e) {
1482
- return void 0;
1483
- }
1484
- const r = Resource.endpoints[endpoint].models[model];
1485
- return Resource.endpoints[endpoint].models[model];
1486
- }
1487
- static create(e, model, entityMapping, circular, customContentType) {
1488
- const badRestRegEX = new RegExp('((\/:)[a-z]+)+', 'g');
1489
- const matchArr = model.match(badRestRegEX) || [];
1490
- const badModelsNextToEachOther = matchArr.join();
1491
- const atleas2DoubleDots = ((badModelsNextToEachOther.match(new RegExp(':', 'g')) || []).length >= 2);
1492
- if (atleas2DoubleDots && model.search(badModelsNextToEachOther) !== -1) {
1402
+ const log = Log.create('resouce-service', Level.__NOTHING);
1403
+ class Resource {
1404
+ constructor() {
1405
+ setTimeout(() => {
1406
+ const zone = this.getZone();
1407
+ if (!RestRequest.zone) {
1408
+ RestRequest.zone = zone;
1409
+ }
1410
+ ;
1411
+ });
1412
+ }
1413
+ static get listenErrors() {
1414
+ return this._listenErrors.asObservable();
1415
+ }
1416
+ static get listenSuccessOperations() {
1417
+ return this._listenSuccess.asObservable();
1418
+ }
1419
+ getZone() {
1420
+ const isNode = (typeof window === 'undefined');
1421
+ if (isNode) {
1422
+ return;
1423
+ }
1424
+ ;
1425
+ const ng = window['ng'];
1426
+ const getAllAngularRootElements = window['getAllAngularRootElements'];
1427
+ if (!ng || !getAllAngularRootElements) {
1428
+ return;
1429
+ }
1430
+ const probe = ng.probe;
1431
+ const coreTokens = ng.coreTokens;
1432
+ if (!coreTokens || !coreTokens.NgZone) {
1433
+ return;
1434
+ }
1435
+ const zoneClass = coreTokens.NgZone;
1436
+ if (!probe || typeof probe !== 'function' || !getAllAngularRootElements) {
1437
+ return;
1438
+ }
1439
+ const angularElements = getAllAngularRootElements();
1440
+ if (!Array.isArray(angularElements) || angularElements.length === 0) {
1441
+ return;
1442
+ }
1443
+ const rootElement = ng.probe(angularElements[0]);
1444
+ if (!rootElement) {
1445
+ return;
1446
+ }
1447
+ const injector = rootElement.injector;
1448
+ if (!injector || !injector.get || typeof injector.get !== 'function') {
1449
+ return;
1450
+ }
1451
+ const zone = injector.get(zoneClass);
1452
+ return zone;
1453
+ }
1454
+ static initAngularNgZone(zone) {
1455
+ RestRequest.zone = zone;
1456
+ }
1457
+ checkNestedModels(model, allModels) {
1458
+ for (let p in allModels) {
1459
+ if (allModels.hasOwnProperty(p)) {
1460
+ let m = allModels[p];
1461
+ if (isValid(p)) {
1462
+ let urlModels = getModels(p);
1463
+ if (containsModels(model, urlModels)) {
1464
+ model = p;
1465
+ break;
1466
+ }
1467
+ }
1468
+ }
1469
+ }
1470
+ return model;
1471
+ }
1472
+ static getModel(endpoint, model) {
1473
+ model = Resource.prepareModel(model);
1474
+ const e = Resource.endpoints[endpoint];
1475
+ if (!e) {
1476
+ return void 0;
1477
+ }
1478
+ const r = Resource.endpoints[endpoint].models[model];
1479
+ return Resource.endpoints[endpoint].models[model];
1480
+ }
1481
+ static create(e, model, entityMapping, circular, customContentType) {
1482
+ const badRestRegEX = new RegExp('((\/:)[a-z]+)+', 'g');
1483
+ const matchArr = model.match(badRestRegEX) || [];
1484
+ const badModelsNextToEachOther = matchArr.join();
1485
+ const atleas2DoubleDots = ((badModelsNextToEachOther.match(new RegExp(':', 'g')) || []).length >= 2);
1486
+ if (atleas2DoubleDots && model.search(badModelsNextToEachOther) !== -1) {
1493
1487
  throw new Error(`
1494
1488
 
1495
1489
  Bad rest model: ${model}
1496
1490
 
1497
1491
  Do not create rest models like this: /book/author/:bookid/:authorid
1498
1492
  Instead use nested approach: /book/:bookid/author/:authorid
1499
- `);
1500
- }
1501
- ;
1502
- Resource.map(e, e);
1503
- Resource.instance.add(e, model ? model : '', entityMapping, circular, customContentType);
1504
- return {
1505
- model: (params) => Resource.instance.api(e, interpolateParamsToUrl(params, model)),
1506
- replay: (method) => {
1507
- Resource.getModel(e, model).replay(method);
1508
- },
1509
- get headers() {
1510
- return Resource.getModel(e, model).headers;
1511
- }
1512
- };
1513
- }
1514
- static reset() {
1515
- Resource.endpoints = {};
1516
- }
1517
- static map(endpoint, url) {
1518
- log.i('url', url);
1519
- let regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
1520
- let e = endpoint;
1521
- if (!regex.test(url)) {
1522
- throw `Url address is not correct: ${url}`;
1523
- }
1524
- if (url.charAt(url.length - 1) === '/')
1525
- url = url.slice(0, url.length - 1);
1526
- log.i('url after', url);
1527
- if (Resource.endpoints[e] !== void 0) {
1528
- Helpers$1.log('Cannot use map function at the same API endpoint again ('
1529
- + Resource.endpoints[e].url + ')');
1530
- return false;
1531
- }
1532
- Resource.endpoints[e] = {
1533
- url: url,
1534
- models: {},
1535
- entity: null
1536
- };
1537
- log.i('enpoints', Resource.endpoints);
1538
- return true;
1539
- }
1540
- static prepareModel(model) {
1541
- if (model.charAt(model.length - 1) === '/')
1542
- model = model.slice(0, model.length - 1);
1543
- if (model.charAt(0) === '/')
1544
- model = model.slice(1, model.length);
1545
- return model;
1546
- }
1547
- /**
1548
- * And enipoint to application
1549
- *
1550
- * @param {E} endpoint
1551
- * @param {string} model
1552
- * @returns {boolean}
1553
- */
1554
- add(endpoint, model, entity, circular, customContentType) {
1555
- log.i(`I am maping ${model} on ${endpoint}`);
1556
- model = Resource.prepareModel(model);
1557
- let e;
1558
- e = (endpoint).toString();
1559
- if (Resource.endpoints[e] === void 0) {
1560
- console.error('Endpoint is not mapped ! Cannot add model ' + model);
1561
- return;
1562
- }
1563
- if (Resource.endpoints[e].models[model] !== void 0) {
1564
- if (Resource.enableWarnings)
1565
- console.warn(`Model '${model}' is already defined in endpoint: `
1566
- + Resource.endpoints[e].url);
1567
- return;
1568
- }
1569
- Resource.endpoints[e].models[model] =
1570
- new Rest(Resource.endpoints[e].url
1571
- + '/' + model, Resource.request, {
1572
- endpoint: e,
1573
- path: model,
1574
- entity,
1575
- circular,
1576
- }, customContentType); // TODO put custom content type in meta ?
1577
- return;
1578
- }
1579
- /**
1580
- * Access api throught endpoint
1581
- *
1582
- * @param {E} endpoint
1583
- * @param {string} model
1584
- * @returns {Rest<T, TA>}
1585
- */
1586
- api(endpoint, model) {
1587
- if (model.charAt(0) === '/')
1588
- model = model.slice(1, model.length);
1589
- let e = (endpoint).toString();
1590
- if (Resource.endpoints[e] === void 0) {
1591
- throw `Endpoint: ${endpoint} is not mapped ! Cannot add model: ${model}`;
1592
- }
1593
- let allModels = Resource.endpoints[e].models;
1594
- let orgModel = model;
1595
- model = this.checkNestedModels(model, allModels);
1596
- if (Resource.endpoints[e].models[model] === void 0) {
1597
- throw `Model '${model}' is undefined in endpoint: ${Resource.endpoints[e].url} `;
1598
- }
1599
- let res = Resource.endpoints[(endpoint).toString()].models[model];
1600
- if (orgModel !== model) {
1601
- let baseUrl = Resource.endpoints[(endpoint).toString()].url;
1602
- res.__rest_endpoint = `${baseUrl}/${orgModel}`;
1603
- }
1604
- else {
1605
- res.__rest_endpoint = void 0;
1606
- }
1607
- ;
1608
- return res;
1609
- }
1610
- }
1611
- Resource._listenErrors = new Subject();
1612
- Resource._listenSuccess = new Subject();
1613
- Resource.enableWarnings = true;
1614
- Resource.instance = new Resource();
1615
- Resource.endpoints = {};
1616
- Resource.request = new RestRequest();
1617
- Resource.Cookies = Cookie.Instance;
1618
- ;
1493
+ `);
1494
+ }
1495
+ ;
1496
+ Resource.map(e, e);
1497
+ Resource.instance.add(e, model ? model : '', entityMapping, circular, customContentType);
1498
+ return {
1499
+ model: (params) => Resource.instance.api(e, interpolateParamsToUrl(params, model)),
1500
+ replay: (method) => {
1501
+ Resource.getModel(e, model).replay(method);
1502
+ },
1503
+ get headers() {
1504
+ return Resource.getModel(e, model).headers;
1505
+ }
1506
+ };
1507
+ }
1508
+ static reset() {
1509
+ Resource.endpoints = {};
1510
+ }
1511
+ static map(endpoint, url) {
1512
+ log.i('url', url);
1513
+ let regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
1514
+ let e = endpoint;
1515
+ if (!regex.test(url)) {
1516
+ throw `Url address is not correct: ${url}`;
1517
+ }
1518
+ if (url.charAt(url.length - 1) === '/')
1519
+ url = url.slice(0, url.length - 1);
1520
+ log.i('url after', url);
1521
+ if (Resource.endpoints[e] !== void 0) {
1522
+ Helpers$1.log('Cannot use map function at the same API endpoint again ('
1523
+ + Resource.endpoints[e].url + ')');
1524
+ return false;
1525
+ }
1526
+ Resource.endpoints[e] = {
1527
+ url: url,
1528
+ models: {},
1529
+ entity: null
1530
+ };
1531
+ log.i('enpoints', Resource.endpoints);
1532
+ return true;
1533
+ }
1534
+ static prepareModel(model) {
1535
+ if (model.charAt(model.length - 1) === '/')
1536
+ model = model.slice(0, model.length - 1);
1537
+ if (model.charAt(0) === '/')
1538
+ model = model.slice(1, model.length);
1539
+ return model;
1540
+ }
1541
+ /**
1542
+ * And enipoint to application
1543
+ *
1544
+ * @param {E} endpoint
1545
+ * @param {string} model
1546
+ * @returns {boolean}
1547
+ */
1548
+ add(endpoint, model, entity, circular, customContentType) {
1549
+ log.i(`I am maping ${model} on ${endpoint}`);
1550
+ model = Resource.prepareModel(model);
1551
+ let e;
1552
+ e = (endpoint).toString();
1553
+ if (Resource.endpoints[e] === void 0) {
1554
+ console.error('Endpoint is not mapped ! Cannot add model ' + model);
1555
+ return;
1556
+ }
1557
+ if (Resource.endpoints[e].models[model] !== void 0) {
1558
+ if (Resource.enableWarnings)
1559
+ console.warn(`Model '${model}' is already defined in endpoint: `
1560
+ + Resource.endpoints[e].url);
1561
+ return;
1562
+ }
1563
+ Resource.endpoints[e].models[model] =
1564
+ new Rest(Resource.endpoints[e].url
1565
+ + '/' + model, Resource.request, {
1566
+ endpoint: e,
1567
+ path: model,
1568
+ entity,
1569
+ circular,
1570
+ }, customContentType); // TODO put custom content type in meta ?
1571
+ return;
1572
+ }
1573
+ /**
1574
+ * Access api throught endpoint
1575
+ *
1576
+ * @param {E} endpoint
1577
+ * @param {string} model
1578
+ * @returns {Rest<T, TA>}
1579
+ */
1580
+ api(endpoint, model) {
1581
+ if (model.charAt(0) === '/')
1582
+ model = model.slice(1, model.length);
1583
+ let e = (endpoint).toString();
1584
+ if (Resource.endpoints[e] === void 0) {
1585
+ throw `Endpoint: ${endpoint} is not mapped ! Cannot add model: ${model}`;
1586
+ }
1587
+ let allModels = Resource.endpoints[e].models;
1588
+ let orgModel = model;
1589
+ model = this.checkNestedModels(model, allModels);
1590
+ if (Resource.endpoints[e].models[model] === void 0) {
1591
+ throw `Model '${model}' is undefined in endpoint: ${Resource.endpoints[e].url} `;
1592
+ }
1593
+ let res = Resource.endpoints[(endpoint).toString()].models[model];
1594
+ if (orgModel !== model) {
1595
+ let baseUrl = Resource.endpoints[(endpoint).toString()].url;
1596
+ res.__rest_endpoint = `${baseUrl}/${orgModel}`;
1597
+ }
1598
+ else {
1599
+ res.__rest_endpoint = void 0;
1600
+ }
1601
+ ;
1602
+ return res;
1603
+ }
1604
+ }
1605
+ Resource._listenErrors = new Subject();
1606
+ Resource._listenSuccess = new Subject();
1607
+ Resource.enableWarnings = true;
1608
+ Resource.instance = new Resource();
1609
+ Resource.endpoints = {};
1610
+ Resource.request = new RestRequest();
1611
+ Resource.Cookies = Cookie.Instance;
1612
+ ;
1619
1613
  ({}); // @--end-of-file-for-module=ng2-rest lib/resource.service.ts
1620
1614
 
1621
- /**
1622
- *
1623
- * @export
1624
- * @abstract
1625
- * @class SimpleResource
1626
- * @extends {Resource<T, A, TA>}
1627
- * @template E Endpoint type
1628
- * @template A Single modle type
1629
- * @template TA Array Model Type
1630
- * @template RP rest url parameters type
1631
- * @template QP query parameter type
1632
- */
1633
- class ExtendedResource {
1634
- constructor(endpoint, path_model) {
1635
- this.endpoint = endpoint;
1636
- this.path_model = path_model;
1637
- /**
1638
- * Get model by rest params
1639
- */
1640
- this.model = (restParams) => {
1641
- return {
1642
- get: (queryPrams) => {
1643
- return Observable.create((observer) => {
1644
- ExtendedResource.handlers.push(this.rest.model(restParams)
1645
- .get([queryPrams], ExtendedResource.doNotSerializeQueryParams)
1646
- .observable
1647
- .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1648
- });
1649
- },
1650
- patch: (item, queryParams) => {
1651
- return Observable.create((observer) => {
1652
- ExtendedResource.handlers.push(this.rest.model(restParams)
1653
- .put(item, [queryParams], ExtendedResource.doNotSerializeQueryParams)
1654
- .observable
1655
- .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1656
- });
1657
- },
1658
- head: (queryPrams) => {
1659
- return Observable.create((observer) => {
1660
- ExtendedResource.handlers.push(this.rest.model(restParams)
1661
- .head([queryPrams], ExtendedResource.doNotSerializeQueryParams)
1662
- .observable
1663
- .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1664
- });
1665
- },
1666
- query: (queryPrams) => {
1667
- return Observable.create((observer) => {
1668
- ExtendedResource.handlers.push(this.rest.model(restParams).
1669
- array
1670
- .get([queryPrams], ExtendedResource.doNotSerializeQueryParams)
1671
- .observable
1672
- .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1673
- });
1674
- },
1675
- post: (item, queryParams) => {
1676
- return Observable.create((observer) => {
1677
- ExtendedResource.handlers.push(this.rest.model(restParams)
1678
- .post(item, [queryParams], ExtendedResource.doNotSerializeQueryParams)
1679
- .observable
1680
- .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1681
- });
1682
- },
1683
- put: (item, queryParams) => {
1684
- return Observable.create((observer) => {
1685
- ExtendedResource.handlers.push(this.rest.model(restParams)
1686
- .put(item, [queryParams], ExtendedResource.doNotSerializeQueryParams)
1687
- .observable
1688
- .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1689
- });
1690
- },
1691
- delete: (queryPrams) => {
1692
- return Observable.create((observer) => {
1693
- ExtendedResource.handlers.push(this.rest.model(restParams)
1694
- .delete([queryPrams], ExtendedResource.doNotSerializeQueryParams)
1695
- .observable
1696
- .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1697
- });
1698
- }
1699
- };
1700
- };
1701
- this.rest = Resource.create(endpoint, path_model);
1702
- }
1703
- }
1704
- ExtendedResource.doNotSerializeQueryParams = false;
1705
- ExtendedResource.handlers = [];
1706
- /**
1707
- *
1708
- * @export
1709
- * @class SimpleResource
1710
- * @template A single model type
1711
- * @template TA array model type
1712
- * @template RP rest parameters type
1713
- * @template QP query parameters type
1714
- */
1715
- class SimpleResource {
1716
- constructor(endpoint, model) {
1717
- let rest = new ExtendedResource(endpoint, model);
1718
- this.model = rest.model;
1719
- }
1720
- static set doNotSerializeQueryParams(value) {
1721
- if (!SimpleResource._isSetQueryParamsSerialization) {
1722
- SimpleResource._isSetQueryParamsSerialization = true;
1723
- ExtendedResource.doNotSerializeQueryParams = value;
1724
- return;
1725
- }
1615
+ /**
1616
+ *
1617
+ * @export
1618
+ * @abstract
1619
+ * @class SimpleResource
1620
+ * @extends {Resource<T, A, TA>}
1621
+ * @template E Endpoint type
1622
+ * @template A Single modle type
1623
+ * @template TA Array Model Type
1624
+ * @template RP rest url parameters type
1625
+ * @template QP query parameter type
1626
+ */
1627
+ class ExtendedResource {
1628
+ constructor(endpoint, path_model) {
1629
+ this.endpoint = endpoint;
1630
+ this.path_model = path_model;
1631
+ /**
1632
+ * Get model by rest params
1633
+ */
1634
+ this.model = (restParams) => {
1635
+ return {
1636
+ get: (queryPrams) => {
1637
+ return Observable.create((observer) => {
1638
+ ExtendedResource.handlers.push(this.rest.model(restParams)
1639
+ .get([queryPrams], ExtendedResource.doNotSerializeQueryParams)
1640
+ .observable
1641
+ .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1642
+ });
1643
+ },
1644
+ patch: (item, queryParams) => {
1645
+ return Observable.create((observer) => {
1646
+ ExtendedResource.handlers.push(this.rest.model(restParams)
1647
+ .put(item, [queryParams], ExtendedResource.doNotSerializeQueryParams)
1648
+ .observable
1649
+ .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1650
+ });
1651
+ },
1652
+ head: (queryPrams) => {
1653
+ return Observable.create((observer) => {
1654
+ ExtendedResource.handlers.push(this.rest.model(restParams)
1655
+ .head([queryPrams], ExtendedResource.doNotSerializeQueryParams)
1656
+ .observable
1657
+ .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1658
+ });
1659
+ },
1660
+ query: (queryPrams) => {
1661
+ return Observable.create((observer) => {
1662
+ ExtendedResource.handlers.push(this.rest.model(restParams).
1663
+ array
1664
+ .get([queryPrams], ExtendedResource.doNotSerializeQueryParams)
1665
+ .observable
1666
+ .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1667
+ });
1668
+ },
1669
+ post: (item, queryParams) => {
1670
+ return Observable.create((observer) => {
1671
+ ExtendedResource.handlers.push(this.rest.model(restParams)
1672
+ .post(item, [queryParams], ExtendedResource.doNotSerializeQueryParams)
1673
+ .observable
1674
+ .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1675
+ });
1676
+ },
1677
+ put: (item, queryParams) => {
1678
+ return Observable.create((observer) => {
1679
+ ExtendedResource.handlers.push(this.rest.model(restParams)
1680
+ .put(item, [queryParams], ExtendedResource.doNotSerializeQueryParams)
1681
+ .observable
1682
+ .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1683
+ });
1684
+ },
1685
+ delete: (queryPrams) => {
1686
+ return Observable.create((observer) => {
1687
+ ExtendedResource.handlers.push(this.rest.model(restParams)
1688
+ .delete([queryPrams], ExtendedResource.doNotSerializeQueryParams)
1689
+ .observable
1690
+ .subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
1691
+ });
1692
+ }
1693
+ };
1694
+ };
1695
+ this.rest = Resource.create(endpoint, path_model);
1696
+ }
1697
+ }
1698
+ ExtendedResource.doNotSerializeQueryParams = false;
1699
+ ExtendedResource.handlers = [];
1700
+ /**
1701
+ *
1702
+ * @export
1703
+ * @class SimpleResource
1704
+ * @template A single model type
1705
+ * @template TA array model type
1706
+ * @template RP rest parameters type
1707
+ * @template QP query parameters type
1708
+ */
1709
+ class SimpleResource {
1710
+ constructor(endpoint, model) {
1711
+ let rest = new ExtendedResource(endpoint, model);
1712
+ this.model = rest.model;
1713
+ }
1714
+ static set doNotSerializeQueryParams(value) {
1715
+ if (!SimpleResource._isSetQueryParamsSerialization) {
1716
+ SimpleResource._isSetQueryParamsSerialization = true;
1717
+ ExtendedResource.doNotSerializeQueryParams = value;
1718
+ return;
1719
+ }
1726
1720
  console.warn(`Query params serialization already set as
1727
- ${ExtendedResource.doNotSerializeQueryParams},`);
1728
- }
1729
- static __destroy() {
1730
- ExtendedResource.handlers.forEach(h => h.unsubscribe());
1731
- }
1732
- }
1733
- SimpleResource._isSetQueryParamsSerialization = false;
1734
- ;
1721
+ ${ExtendedResource.doNotSerializeQueryParams},`);
1722
+ }
1723
+ static __destroy() {
1724
+ ExtendedResource.handlers.forEach(h => h.unsubscribe());
1725
+ }
1726
+ }
1727
+ SimpleResource._isSetQueryParamsSerialization = false;
1728
+ ;
1735
1729
  ({}); // @--end-of-file-for-module=ng2-rest lib/other/simple-resource.ts
1736
1730
 
1737
- ;
1731
+ ;
1738
1732
  ({}); // @--end-of-file-for-module=ng2-rest lib/index.ts
1739
1733
 
1740
- /**
1741
- * Generated bundle index. Do not edit.
1734
+ /**
1735
+ * Generated bundle index. Do not edit.
1742
1736
  */
1743
1737
 
1744
1738
  export { CONTENT_TYPE, Helpers, Mapping, Models, RequestCache, Resource, Rest, RestHeaders, SimpleResource, interpolateParamsToUrl };