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