ng2-rest 13.0.30 → 13.0.33

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