ng2-rest 11.0.41 → 13.0.3

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