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