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