ng2-rest 21.0.12 → 21.0.17

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