ng2-rest 13.0.30 → 13.0.34

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