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